Archive eaglerxbackendrpc (plugin, 1.8.8, clean)
This commit is contained in:
+29
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public class AbortLoadException extends RuntimeException {
|
||||
|
||||
public AbortLoadException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public AbortLoadException(String message, Throwable reason) {
|
||||
super(message, reason);
|
||||
}
|
||||
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public abstract class AbstractScheduler implements IPlatformScheduler {
|
||||
|
||||
private static abstract class RepeatingTaskBase implements IPlatformTask {
|
||||
|
||||
private final Runnable runnable;
|
||||
private final Runnable reschedule;
|
||||
private IPlatformTask task;
|
||||
|
||||
protected RepeatingTaskBase(Runnable runnable, long interval) {
|
||||
this.runnable = runnable;
|
||||
this.reschedule = () -> {
|
||||
if (task == null) {
|
||||
return;
|
||||
}
|
||||
long start = System.nanoTime();
|
||||
try {
|
||||
runnable.run();
|
||||
} finally {
|
||||
if (task == null) {
|
||||
return;
|
||||
}
|
||||
synchronized (this) {
|
||||
if (task == null) {
|
||||
return;
|
||||
}
|
||||
task = reschedule(getReschedule(),
|
||||
Math.max(interval - ((System.nanoTime() - start) / 1000000l), 5l));
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Runnable getTask() {
|
||||
return runnable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
if (task == null) {
|
||||
return;
|
||||
}
|
||||
IPlatformTask t;
|
||||
synchronized (this) {
|
||||
t = task;
|
||||
if (t == null) {
|
||||
return;
|
||||
}
|
||||
task = null;
|
||||
}
|
||||
t.cancel();
|
||||
}
|
||||
|
||||
protected Runnable getReschedule() {
|
||||
return reschedule;
|
||||
}
|
||||
|
||||
protected IPlatformTask bootstrap(long delay) {
|
||||
task = reschedule(reschedule, delay);
|
||||
return this;
|
||||
}
|
||||
|
||||
protected abstract IPlatformTask reschedule(Runnable runnable, long delay);
|
||||
|
||||
}
|
||||
|
||||
private class RepeatingTask extends RepeatingTaskBase {
|
||||
|
||||
protected RepeatingTask(Runnable runnable, long interval) {
|
||||
super(runnable, interval);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IPlatformTask reschedule(Runnable runnable, long delay) {
|
||||
return AbstractScheduler.this.executeDelayedTask(runnable, delay);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private class RepeatingTaskAsync extends RepeatingTaskBase {
|
||||
|
||||
protected RepeatingTaskAsync(Runnable runnable, long interval) {
|
||||
super(runnable, interval);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IPlatformTask reschedule(Runnable runnable, long delay) {
|
||||
return AbstractScheduler.this.executeAsyncDelayedTask(runnable, delay);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlatformTask executeRepeatingTask(Runnable runnable, long delay, long interval) {
|
||||
if (runnable == null) {
|
||||
throw new NullPointerException("runnable");
|
||||
}
|
||||
return (new RepeatingTask(runnable, interval)).bootstrap(delay);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlatformTask executeAsyncRepeatingTask(Runnable runnable, long delay, long interval) {
|
||||
if (runnable == null) {
|
||||
throw new NullPointerException("runnable");
|
||||
}
|
||||
return (new RepeatingTaskAsync(runnable, interval)).bootstrap(delay);
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public enum EnumAdapterPlatformType {
|
||||
BUNGEE(true), VELOCITY(true), BUKKIT(false);
|
||||
|
||||
public final boolean proxy;
|
||||
|
||||
private EnumAdapterPlatformType(boolean proxy) {
|
||||
this.proxy = proxy;
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IEaglerXServerCommandHandler<PlayerObject> {
|
||||
|
||||
void handle(IEaglerXServerCommandType<PlayerObject> command, IPlatformCommandSender<PlayerObject> sender,
|
||||
String[] args);
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IEaglerXServerCommandType<PlayerObject> {
|
||||
|
||||
String getCommandName();
|
||||
|
||||
String getPermission();
|
||||
|
||||
String[] getCommandAliases();
|
||||
|
||||
IEaglerXServerCommandHandler<PlayerObject> getHandler();
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IEaglerXServerImpl<PlayerObject> {
|
||||
|
||||
void load(IPlatform.Init<PlayerObject> platf);
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IEaglerXServerJoinListener<PlayerObject> {
|
||||
|
||||
void handlePreConnect(IPlatformPlayer<PlayerObject> player);
|
||||
|
||||
void handlePostConnect(IPlatformPlayer<PlayerObject> player, IPlatformServer<PlayerObject> server);
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
|
||||
public interface IEaglerXServerListener {
|
||||
|
||||
boolean matchListenerAddress(SocketAddress addr);
|
||||
|
||||
default boolean isCloneListenerEnabled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
default SocketAddress getCloneListenerAddress() {
|
||||
return null;
|
||||
}
|
||||
|
||||
default void reportVelocityInjected(Channel channel) {
|
||||
}
|
||||
|
||||
default void reportPaperMCInjected() {
|
||||
}
|
||||
|
||||
default void reportNettyInjected(Channel channel) {
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IEaglerXServerLoginInitializer<PipelineAttachment extends IPipelineData> {
|
||||
|
||||
void initializeLogin(IPlatformLoginInitializer<PipelineAttachment> initializer);
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IEaglerXServerMessageChannel<PlayerObject> {
|
||||
|
||||
String getLegacyName();
|
||||
|
||||
String getModernName();
|
||||
|
||||
IEaglerXServerMessageHandler<PlayerObject> getHandler();
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IEaglerXServerMessageHandler<PlayerObject> {
|
||||
|
||||
void handle(IEaglerXServerMessageChannel<PlayerObject> channel, IPlatformPlayer<PlayerObject> player,
|
||||
byte[] contents);
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IEaglerXServerNettyPipelineInitializer<PipelineAttachment extends IPipelineData> {
|
||||
|
||||
void initialize(IPlatformNettyPipelineInitializer<PipelineAttachment> initializer);
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IEaglerXServerPlayerCountHandler {
|
||||
|
||||
int getPlayerTotal();
|
||||
|
||||
int getPlayerMax();
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IEaglerXServerPlayerInitializer<PipelineAttachment extends IPipelineData, PlayerAttachment, PlayerObject> {
|
||||
|
||||
void initializePlayer(IPlatformPlayerInitializer<PipelineAttachment, PlayerAttachment, PlayerObject> initializer);
|
||||
|
||||
void destroyPlayer(IPlatformPlayer<PlayerObject> player);
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import io.netty.channel.ChannelHandler;
|
||||
|
||||
public interface IPipelineComponent {
|
||||
|
||||
public static enum EnumPipelineComponent {
|
||||
FRAME_DECODER, VIA_DECODER, MINECRAFT_DECODER, FRAME_ENCODER, VIA_ENCODER, MINECRAFT_ENCODER,
|
||||
READ_TIMEOUT_HANDLER, HAPROXY_HANDLER, BUKKIT_LEGACY_HANDLER, BUNGEE_LEGACY_HANDLER, BUNGEE_LEGACY_KICK_ENCODER,
|
||||
VELOCITY_LEGACY_PING_ENCODER, PROTOCOLLIB_INBOUND_INTERCEPTOR, PROTOCOLLIB_PROTOCOL_GETTER_NAME,
|
||||
PROTOCOLLIB_WIRE_PACKET_ENCODER, PROTOCOLIZE_DECODER, PROTOCOLIZE_ENCODER, PACKETEVENTS_ENCODER,
|
||||
PACKETEVENTS_DECODER, PACKETEVENTS_TIMEOUT_HANDLER, INBOUND_PACKET_HANDLER, UNIDENTIFIED;
|
||||
}
|
||||
|
||||
EnumPipelineComponent getIdentifiedType();
|
||||
|
||||
String getName();
|
||||
|
||||
ChannelHandler getHandle();
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IPipelineData {
|
||||
|
||||
boolean isEaglerPlayer();
|
||||
|
||||
boolean isCompressionDisable();
|
||||
|
||||
void awaitPlayState(Runnable continueHandler);
|
||||
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.event.IEventDispatchAdapter;
|
||||
import net.lax1dude.eaglercraft.backend.server.config.EnumConfigFormat;
|
||||
|
||||
public interface IPlatform<PlayerObject> {
|
||||
|
||||
public interface Init<PlayerObject> {
|
||||
|
||||
void setOnServerEnable(Runnable enable);
|
||||
|
||||
void setOnServerDisable(Runnable disable);
|
||||
|
||||
void setEaglerPlayerChannels(Collection<IEaglerXServerMessageChannel<PlayerObject>> channels);
|
||||
|
||||
void setPipelineInitializer(IEaglerXServerNettyPipelineInitializer<? extends IPipelineData> initializer);
|
||||
|
||||
void setConnectionInitializer(IEaglerXServerLoginInitializer<? extends IPipelineData> initializer);
|
||||
|
||||
void setPlayerInitializer(IEaglerXServerPlayerInitializer<? extends IPipelineData, ?, PlayerObject> initializer);
|
||||
|
||||
void setServerJoinListener(IEaglerXServerJoinListener<PlayerObject> listener);
|
||||
|
||||
void setCommandRegistry(Collection<IEaglerXServerCommandType<PlayerObject>> commands);
|
||||
|
||||
IPlatform<PlayerObject> getPlatform();
|
||||
|
||||
}
|
||||
|
||||
public interface InitProxying<PlayerObject> extends Init<PlayerObject> {
|
||||
|
||||
void setEaglerListeners(Collection<IEaglerXServerListener> listeners);
|
||||
|
||||
void setEaglerBackendChannels(Collection<IEaglerXServerMessageChannel<PlayerObject>> channels);
|
||||
|
||||
}
|
||||
|
||||
public interface InitNonProxying<PlayerObject> extends Init<PlayerObject> {
|
||||
|
||||
void setEaglerListener(IEaglerXServerListener listener);
|
||||
|
||||
SocketAddress getListenerAddress();
|
||||
|
||||
}
|
||||
|
||||
EnumAdapterPlatformType getType();
|
||||
|
||||
String getVersion();
|
||||
|
||||
Class<PlayerObject> getPlayerClass();
|
||||
|
||||
String getPluginId();
|
||||
|
||||
File getDataFolder();
|
||||
|
||||
IPlatformLogger logger();
|
||||
|
||||
IPlatformCommandSender<PlayerObject> getConsole();
|
||||
|
||||
void forEachPlayer(Consumer<IPlatformPlayer<PlayerObject>> playerCallback);
|
||||
|
||||
IPlatformPlayer<PlayerObject> getPlayer(PlayerObject playerObj);
|
||||
|
||||
IPlatformPlayer<PlayerObject> getPlayer(String username);
|
||||
|
||||
IPlatformPlayer<PlayerObject> getPlayer(UUID uuid);
|
||||
|
||||
Collection<IPlatformPlayer<PlayerObject>> getAllPlayers();
|
||||
|
||||
Map<String, IPlatformServer<PlayerObject>> getRegisteredServers();
|
||||
|
||||
IPlatformServer<PlayerObject> getServer(String serverName);
|
||||
|
||||
IEventDispatchAdapter<PlayerObject, ?> eventDispatcher();
|
||||
|
||||
IPlatformScheduler getScheduler();
|
||||
|
||||
Set<EnumConfigFormat> getConfigFormats();
|
||||
|
||||
IPlatformComponentHelper getComponentHelper();
|
||||
|
||||
boolean isOnlineMode();
|
||||
|
||||
boolean isModernPluginChannelNamesOnly();
|
||||
|
||||
int getPlayerTotal();
|
||||
|
||||
int getPlayerMax();
|
||||
|
||||
void setPlayerCountHandler(IEaglerXServerPlayerCountHandler playerCountHandler);
|
||||
|
||||
Bootstrap setChannelFactory(Bootstrap bootstrap, SocketAddress address);
|
||||
|
||||
ServerBootstrap setServerChannelFactory(ServerBootstrap bootstrap, SocketAddress address);
|
||||
|
||||
EventLoopGroup getBossEventLoopGroup();
|
||||
|
||||
EventLoopGroup getWorkerEventLoopGroup();
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IPlatformCommandSender<PlayerObject> {
|
||||
|
||||
boolean checkPermission(String permission);
|
||||
|
||||
<ComponentObject> void sendMessage(ComponentObject component);
|
||||
|
||||
boolean isPlayer();
|
||||
|
||||
IPlatformPlayer<PlayerObject> asPlayer();
|
||||
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface IPlatformComponentBuilder {
|
||||
|
||||
public static enum EnumChatColor {
|
||||
BLACK, DARK_BLUE, DARK_GREEN, DARK_AQUA, DARK_RED, DARK_PURPLE, GOLD, GRAY, DARK_GRAY, BLUE, GREEN, AQUA, RED,
|
||||
LIGHT_PURPLE, YELLOW, WHITE
|
||||
}
|
||||
|
||||
public static enum EnumClickAction {
|
||||
OPEN_URL, OPEN_FILE, RUN_COMMAND, SUGGEST_COMMAND, CHANGE_PAGE, COPY_TO_CLIPBOARD
|
||||
}
|
||||
|
||||
public static enum EnumHoverAction {
|
||||
SHOW_TEXT
|
||||
}
|
||||
|
||||
public interface IBuilderBase<ParentType> {
|
||||
|
||||
ParentType end();
|
||||
|
||||
}
|
||||
|
||||
public interface IBuilderComponent<ParentType, ThisType> extends IBuilderBase<ParentType> {
|
||||
|
||||
IBuilderStyle<ThisType> beginStyle();
|
||||
|
||||
IBuilderClickEvent<ThisType> beginClickEvent();
|
||||
|
||||
IBuilderHoverEvent<ThisType> beginHoverEvent();
|
||||
|
||||
IBuilderComponentText<ThisType> appendTextComponent();
|
||||
|
||||
IBuilderComponentTranslation<ThisType> appendTranslationComponent();
|
||||
|
||||
ThisType insertion(String txt);
|
||||
|
||||
}
|
||||
|
||||
public interface IBuilderComponentText<ParentType>
|
||||
extends IBuilderComponent<ParentType, IBuilderComponentText<ParentType>> {
|
||||
|
||||
IBuilderComponentText<ParentType> text(String txt);
|
||||
|
||||
}
|
||||
|
||||
public interface IBuilderComponentTranslation<ParentType>
|
||||
extends IBuilderComponent<ParentType, IBuilderComponentTranslation<ParentType>> {
|
||||
|
||||
IBuilderComponentTranslation<ParentType> translation(String key);
|
||||
|
||||
IBuilderComponentTranslation<ParentType> stringArgs(Object... args);
|
||||
|
||||
IBuilderComponentTranslation<ParentType> stringArgs(List<Object> args);
|
||||
|
||||
IBuilderComponentTranslation<ParentType> componentArgs(Object... args);
|
||||
|
||||
IBuilderComponentTranslation<ParentType> componentArgs(List<Object> args);
|
||||
|
||||
IBuilderComponentTranslationArgs<IBuilderComponentTranslation<ParentType>> args();
|
||||
|
||||
}
|
||||
|
||||
public interface IBuilderComponentTranslationArgs<ParentType> extends IBuilderBase<ParentType> {
|
||||
|
||||
IBuilderComponentText<IBuilderComponentTranslationArgs<ParentType>> textArg();
|
||||
|
||||
IBuilderComponentTranslation<IBuilderComponentTranslationArgs<ParentType>> translateArg();
|
||||
|
||||
IBuilderComponentTranslationArgs<ParentType> rawArg(Object component);
|
||||
|
||||
}
|
||||
|
||||
public interface IBuilderStyle<ParentType> extends IBuilderBase<ParentType> {
|
||||
|
||||
IBuilderStyle<ParentType> color(EnumChatColor color);
|
||||
|
||||
IBuilderStyle<ParentType> bold(boolean bold);
|
||||
|
||||
IBuilderStyle<ParentType> italic(boolean italic);
|
||||
|
||||
IBuilderStyle<ParentType> strikethrough(boolean strikethrough);
|
||||
|
||||
IBuilderStyle<ParentType> underline(boolean underline);
|
||||
|
||||
IBuilderStyle<ParentType> obfuscated(boolean obfuscated);
|
||||
|
||||
}
|
||||
|
||||
public interface IBuilderClickEvent<ParentType> extends IBuilderBase<ParentType> {
|
||||
|
||||
IBuilderClickEvent<ParentType> clickAction(EnumClickAction action);
|
||||
|
||||
IBuilderClickEvent<ParentType> clickValue(String value);
|
||||
|
||||
}
|
||||
|
||||
public interface IBuilderHoverEvent<ParentType> extends IBuilderBase<ParentType> {
|
||||
|
||||
IBuilderHoverEvent<ParentType> hoverAction(EnumHoverAction action);
|
||||
|
||||
IBuilderComponentText<IBuilderHoverEvent<ParentType>> appendTextContent();
|
||||
|
||||
IBuilderComponentTranslation<IBuilderHoverEvent<ParentType>> appendTranslationContent();
|
||||
|
||||
}
|
||||
|
||||
IBuilderComponentText<Object> buildTextComponent();
|
||||
|
||||
IBuilderComponentTranslation<Object> buildTranslationComponent();
|
||||
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IPlatformComponentHelper {
|
||||
|
||||
IPlatformComponentBuilder builder();
|
||||
|
||||
Class<?> getComponentType();
|
||||
|
||||
Object getStandardKickAlreadyPlaying();
|
||||
|
||||
String serializeLegacySection(Object component);
|
||||
|
||||
String serializePlainText(Object component);
|
||||
|
||||
/**
|
||||
* Use for components that do not contain hover events
|
||||
*/
|
||||
String serializeGenericJSON(Object component);
|
||||
|
||||
/**
|
||||
* Use for components that contain hover events, on 1.8 clients
|
||||
*/
|
||||
String serializeLegacyJSON(Object component);
|
||||
|
||||
/**
|
||||
* Use for components that contain hover events, on modern clients
|
||||
*/
|
||||
String serializeModernJSON(Object component);
|
||||
|
||||
/**
|
||||
* Use for components that do not contain hover events
|
||||
*/
|
||||
Object parseGenericJSON(String json) throws IllegalArgumentException;
|
||||
|
||||
/**
|
||||
* Use for components that contain hover events, on 1.8 clients
|
||||
*/
|
||||
Object parseLegacyJSON(String json) throws IllegalArgumentException;
|
||||
|
||||
/**
|
||||
* Use for components that contain hover events, on modern clients
|
||||
*/
|
||||
Object parseModernJSON(String json) throws IllegalArgumentException;
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.supervisor.protocol.util.ILoggerSv;
|
||||
import net.lax1dude.eaglercraft.backend.util.ILoggerAdapter;
|
||||
|
||||
public interface IPlatformLogger extends ILoggerSv, ILoggerAdapter {
|
||||
|
||||
void info(String msg);
|
||||
|
||||
void info(String msg, Throwable thrown);
|
||||
|
||||
void warn(String msg);
|
||||
|
||||
void warn(String msg, Throwable thrown);
|
||||
|
||||
void error(String msg);
|
||||
|
||||
void error(String msg, Throwable thrown);
|
||||
|
||||
IPlatformSubLogger createSubLogger(String name);
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface IPlatformLoginInitializer<PipelineAttachment extends IPipelineData> {
|
||||
|
||||
PipelineAttachment getPipelineAttachment();
|
||||
|
||||
void setUniqueId(UUID uuid);
|
||||
|
||||
void setTexturesProperty(String propertyValue, String propertySignature);
|
||||
|
||||
void setEaglerPlayerProperty(boolean enable);
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
|
||||
public interface IPlatformNettyPipelineInitializer<PipelineAttachment extends IPipelineData> {
|
||||
|
||||
List<IPipelineComponent> getPipeline();
|
||||
|
||||
IEaglerXServerListener getListener();
|
||||
|
||||
Channel getChannel();
|
||||
|
||||
Consumer<SocketAddress> realAddressHandle();
|
||||
|
||||
void setAttachment(PipelineAttachment object);
|
||||
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
import java.util.UUID;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
|
||||
public interface IPlatformPlayer<PlayerObject> extends IPlatformCommandSender<PlayerObject> {
|
||||
|
||||
PlayerObject getPlayerObject();
|
||||
|
||||
Channel getChannel();
|
||||
|
||||
IPlatformServer<PlayerObject> getServer();
|
||||
|
||||
String getUsername();
|
||||
|
||||
UUID getUniqueId();
|
||||
|
||||
SocketAddress getSocketAddress();
|
||||
|
||||
int getMinecraftProtocol();
|
||||
|
||||
boolean isConnected();
|
||||
|
||||
boolean isOnlineMode();
|
||||
|
||||
String getMinecraftBrand();
|
||||
|
||||
String getTexturesProperty();
|
||||
|
||||
void sendDataClient(String channel, byte[] message);
|
||||
|
||||
void sendDataBackend(String channel, byte[] message);
|
||||
|
||||
boolean isSetViewDistanceSupportedPaper();
|
||||
|
||||
void setViewDistancePaper(int distance);
|
||||
|
||||
void sendMessage(String message);
|
||||
|
||||
void disconnect();
|
||||
|
||||
void disconnect(String kickMessage);
|
||||
|
||||
<ComponentObject> void disconnect(ComponentObject kickMessage);
|
||||
|
||||
<T> T getPlayerAttachment();
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IPlatformPlayerInitializer<PipelineAttachment extends IPipelineData, PlayerAttachment, PlayerObject> {
|
||||
|
||||
IPlatformPlayer<PlayerObject> getPlayer();
|
||||
|
||||
PipelineAttachment getPipelineAttachment();
|
||||
|
||||
void setPlayerAttachment(PlayerAttachment attachment);
|
||||
|
||||
void complete();
|
||||
|
||||
void cancel();
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IScheduler;
|
||||
|
||||
public interface IPlatformScheduler extends IScheduler {
|
||||
|
||||
IPlatformTask executeDelayedTask(Runnable runnable, long delay);
|
||||
|
||||
IPlatformTask executeAsyncDelayedTask(Runnable runnable, long delay);
|
||||
|
||||
IPlatformTask executeRepeatingTask(Runnable runnable, long delay, long interval);
|
||||
|
||||
IPlatformTask executeAsyncRepeatingTask(Runnable runnable, long delay, long interval);
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public interface IPlatformServer<PlayerObject> {
|
||||
|
||||
boolean isEaglerRegistered();
|
||||
|
||||
String getServerConfName();
|
||||
|
||||
Collection<IPlatformPlayer<PlayerObject>> getAllPlayers();
|
||||
|
||||
void forEachPlayer(Consumer<IPlatformPlayer<PlayerObject>> callback);
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
public interface IPlatformSubLogger extends IPlatformLogger {
|
||||
|
||||
IPlatformLogger getParent();
|
||||
|
||||
String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.ITask;
|
||||
|
||||
public interface IPlatformTask extends ITask {
|
||||
|
||||
Runnable getTask();
|
||||
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class JavaLogger implements IPlatformLogger {
|
||||
|
||||
protected final Logger logger;
|
||||
|
||||
public JavaLogger(Logger logger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String msg) {
|
||||
logger.info(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String msg, Throwable thrown) {
|
||||
logger.log(Level.INFO, msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warn(String msg) {
|
||||
logger.warning(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warn(String msg, Throwable thrown) {
|
||||
logger.log(Level.WARNING, msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String msg) {
|
||||
logger.severe(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String msg, Throwable thrown) {
|
||||
logger.log(Level.SEVERE, msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlatformSubLogger createSubLogger(String name) {
|
||||
return new SubLogger(name, this);
|
||||
}
|
||||
|
||||
public class SubLogger implements IPlatformSubLogger {
|
||||
|
||||
private String name;
|
||||
private IPlatformLogger parent;
|
||||
|
||||
public SubLogger(String name, IPlatformLogger parent) {
|
||||
this.name = name;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String msg) {
|
||||
logger.info("[" + name + "]: " + msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String msg, Throwable thrown) {
|
||||
logger.log(Level.INFO, "[" + name + "]: " + msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warn(String msg) {
|
||||
logger.warning("[" + name + "]: " + msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warn(String msg, Throwable thrown) {
|
||||
logger.log(Level.WARNING, "[" + name + "]: " + msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String msg) {
|
||||
logger.severe("[" + name + "]: " + msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String msg, Throwable thrown) {
|
||||
logger.log(Level.SEVERE, "[" + name + "]: " + msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlatformSubLogger createSubLogger(String name) {
|
||||
return new SubLogger(name + "|" + name, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlatformLogger getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import io.netty.util.AttributeKey;
|
||||
|
||||
public class PipelineAttributes {
|
||||
|
||||
public static final AttributeKey<Object> EAGLER_LISTENER_DATA = AttributeKey.valueOf("$eagler0");
|
||||
public static final AttributeKey<Object> EAGLER_PIPELINE_DATA = AttributeKey.valueOf("$eagler1");
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> AttributeKey<T> listenerData() {
|
||||
return (AttributeKey<T>) EAGLER_LISTENER_DATA;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> AttributeKey<T> pipelineData() {
|
||||
return (AttributeKey<T>) EAGLER_PIPELINE_DATA;
|
||||
}
|
||||
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
|
||||
public class SLF4JLogger implements IPlatformLogger {
|
||||
|
||||
protected final Logger logger;
|
||||
|
||||
public SLF4JLogger(Logger logger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String msg) {
|
||||
logger.info(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String msg, Throwable thrown) {
|
||||
logger.info(msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warn(String msg) {
|
||||
logger.warn(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warn(String msg, Throwable thrown) {
|
||||
logger.warn(msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String msg) {
|
||||
logger.error(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String msg, Throwable thrown) {
|
||||
logger.error(msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlatformSubLogger createSubLogger(String name) {
|
||||
return new SubLogger(name, this);
|
||||
}
|
||||
|
||||
public class SubLogger implements IPlatformSubLogger {
|
||||
|
||||
private String name;
|
||||
private IPlatformLogger parent;
|
||||
|
||||
public SubLogger(String name, IPlatformLogger parent) {
|
||||
this.name = name;
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String msg) {
|
||||
logger.info("[{}]: {}", name, msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String msg, Throwable thrown) {
|
||||
logger.info("[" + name + "]: " + msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warn(String msg) {
|
||||
logger.warn("[{}]: {}", name, msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warn(String msg, Throwable thrown) {
|
||||
logger.warn("[" + name + "]: " + msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String msg) {
|
||||
logger.error("[{}]: {}", name, msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String msg, Throwable thrown) {
|
||||
logger.error("[" + name + "]: " + msg, thrown);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlatformSubLogger createSubLogger(String name) {
|
||||
return new SubLogger(name + "|" + name, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPlatformLogger getParent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter.event;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import io.netty.handler.codec.http.FullHttpRequest;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerConnection;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerLoginConnection;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerPendingConnection;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerPlayer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerXServerAPI;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftAuthCheckRequiredEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftWebViewChannelEvent.EnumEventType;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftWebViewMessageEvent.EnumMessageType;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftWebViewMessageEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.query.IMOTDConnection;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.query.IQueryConnection;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.voice.EnumVoiceState;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftAuthCookieEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftAuthPasswordEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftClientBrandEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftDestroyPlayerEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftInitializePlayerEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftLoginEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftMOTDEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftRegisterSkinEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftRevokeSessionQueryEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftVoiceChangeEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftWebSocketOpenEvent;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.event.IEaglercraftWebViewChannelEvent;
|
||||
|
||||
public interface IEventDispatchAdapter<PlayerObject, ComponentObject> {
|
||||
|
||||
void setAPI(IEaglerXServerAPI<PlayerObject> api);
|
||||
|
||||
void dispatchAuthCheckRequired(IEaglerPendingConnection pendingConnection, boolean clientSolicitingPassword,
|
||||
byte[] authUsername,
|
||||
IEventDispatchCallback<IEaglercraftAuthCheckRequiredEvent<PlayerObject, ComponentObject>> onComplete);
|
||||
|
||||
void dispatchAuthCookieEvent(IEaglerLoginConnection pendingConnection, byte[] authUsername,
|
||||
boolean nicknameSelectionEnabled, boolean cookiesEnabled, byte[] cookieData, String requestedUsername,
|
||||
String profileUsername, UUID profileUUID, byte authType, String authMessage, String authRequestedServer,
|
||||
IEventDispatchCallback<IEaglercraftAuthCookieEvent<PlayerObject, ComponentObject>> onComplete);
|
||||
|
||||
void dispatchAuthPasswordEvent(IEaglerLoginConnection pendingConnection, byte[] authUsername,
|
||||
boolean nicknameSelectionEnabled, byte[] authSaltingData, byte[] authPasswordData, boolean cookiesEnabled,
|
||||
byte[] cookieData, String requestedUsername, String profileUsername, UUID profileUUID, byte authType,
|
||||
String authMessage, String authRequestedServer,
|
||||
IEventDispatchCallback<IEaglercraftAuthPasswordEvent<PlayerObject, ComponentObject>> onComplete);
|
||||
|
||||
void dispatchClientBrandEvent(IEaglerPendingConnection pendingConnection,
|
||||
IEventDispatchCallback<IEaglercraftClientBrandEvent<PlayerObject, ComponentObject>> onComplete);
|
||||
|
||||
void dispatchLoginEvent(IEaglerLoginConnection loginConnection, boolean redirectSupport, String requestedServer,
|
||||
IEventDispatchCallback<IEaglercraftLoginEvent<PlayerObject, ComponentObject>> onComplete);
|
||||
|
||||
void dispatchInitializePlayerEvent(IEaglerPlayer<PlayerObject> player, Map<String, byte[]> extraProfileData,
|
||||
IEventDispatchCallback<IEaglercraftInitializePlayerEvent<PlayerObject>> onComplete);
|
||||
|
||||
void dispatchDestroyPlayerEvent(IEaglerPlayer<PlayerObject> player,
|
||||
IEventDispatchCallback<IEaglercraftDestroyPlayerEvent<PlayerObject>> onComplete);
|
||||
|
||||
void dispatchMOTDEvent(IMOTDConnection connection,
|
||||
IEventDispatchCallback<IEaglercraftMOTDEvent<PlayerObject>> onComplete);
|
||||
|
||||
void dispatchRegisterSkinEvent(IEaglerLoginConnection pendingConnection, IRegisterSkinDelegate delegate,
|
||||
IEventDispatchCallback<IEaglercraftRegisterSkinEvent<PlayerObject>> onComplete);
|
||||
|
||||
void dispatchRevokeSessionQueryEvent(IQueryConnection query, byte[] cookieData,
|
||||
IEventDispatchCallback<IEaglercraftRevokeSessionQueryEvent<PlayerObject>> onComplete);
|
||||
|
||||
void dispatchVoiceChangeEvent(IEaglerPlayer<PlayerObject> player, EnumVoiceState voiceStateOld,
|
||||
EnumVoiceState voiceStateNew,
|
||||
IEventDispatchCallback<IEaglercraftVoiceChangeEvent<PlayerObject>> onComplete);
|
||||
|
||||
void dispatchWebSocketOpenEvent(IEaglerConnection delegate, FullHttpRequest request,
|
||||
IEventDispatchCallback<IEaglercraftWebSocketOpenEvent<PlayerObject>> onComplete);
|
||||
|
||||
void dispatchWebViewChannelEvent(IEaglerPlayer<PlayerObject> player, EnumEventType type, String channel,
|
||||
IEventDispatchCallback<IEaglercraftWebViewChannelEvent<PlayerObject>> onComplete);
|
||||
|
||||
void dispatchWebViewMessageEvent(IEaglerPlayer<PlayerObject> player, String channel, EnumMessageType type,
|
||||
byte[] data, IEventDispatchCallback<IEaglercraftWebViewMessageEvent<PlayerObject>> onComplete);
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter.event;
|
||||
|
||||
public interface IEventDispatchCallback<T> {
|
||||
|
||||
void complete(T result, Throwable error);
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.adapter.event;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.skins.EnumSkinModel;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.skins.IEaglerPlayerCape;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.skins.IEaglerPlayerSkin;
|
||||
|
||||
public interface IRegisterSkinDelegate {
|
||||
|
||||
IEaglerPlayerSkin getEaglerSkin();
|
||||
|
||||
IEaglerPlayerCape getEaglerCape();
|
||||
|
||||
void forceFromVanillaTexturesProperty(String value);
|
||||
|
||||
void forceFromVanillaLoginProfile();
|
||||
|
||||
void forceSkinFromURL(String url, EnumSkinModel skinModel);
|
||||
|
||||
void forceSkinFromVanillaTexturesProperty(String value);
|
||||
|
||||
void forceSkinFromVanillaLoginProfile();
|
||||
|
||||
void forceCapeFromURL(String url);
|
||||
|
||||
void forceCapeFromVanillaTexturesProperty(String value);
|
||||
|
||||
void forceCapeFromVanillaLoginProfile();
|
||||
|
||||
void forceSkinEagler(IEaglerPlayerSkin skin);
|
||||
|
||||
void forceCapeEagler(IEaglerPlayerCape skin);
|
||||
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerXServerAPI;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.attribute.IAttributeManager;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.internal.factory.EaglerXServerAPIFactory;
|
||||
|
||||
class APIFactoryImpl extends EaglerXServerAPIFactory.Factory {
|
||||
|
||||
static final APIFactoryImpl INSTANCE = new APIFactoryImpl();
|
||||
|
||||
private Class<?> playerClass;
|
||||
private Set<Class<?>> playerClassSet;
|
||||
private final EaglerAttributeManager attributeManager = new EaglerAttributeManager();
|
||||
private IEaglerXServerAPI<?> handle;
|
||||
|
||||
private APIFactoryImpl() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Class<?>> getPlayerTypes() {
|
||||
Set<Class<?>> classSet = this.playerClassSet;
|
||||
if (classSet == null) {
|
||||
throw new IllegalStateException("EaglerXServer has not been initialized yet!");
|
||||
}
|
||||
return classSet;
|
||||
}
|
||||
|
||||
EaglerAttributeManager getEaglerAttribManager() {
|
||||
return attributeManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IAttributeManager getGlobalAttributeManager() {
|
||||
return attributeManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> IEaglerXServerAPI<T> getAPI(Class<T> playerClass) {
|
||||
IEaglerXServerAPI<?> handle = this.handle;
|
||||
if (handle == null) {
|
||||
throw new IllegalStateException("EaglerXServer has not been initialized yet!");
|
||||
}
|
||||
if (!playerClass.isAssignableFrom(this.playerClass)) {
|
||||
throw new ClassCastException(
|
||||
"Class \"" + this.playerClass.getName() + "\" cannot be cast to \"" + playerClass.getName() + "\"");
|
||||
}
|
||||
return (IEaglerXServerAPI<T>) handle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerXServerAPI<?> getDefaultAPI() {
|
||||
IEaglerXServerAPI<?> handle = this.handle;
|
||||
if (handle == null) {
|
||||
throw new IllegalStateException("EaglerXServer has not been initialized yet!");
|
||||
}
|
||||
return handle;
|
||||
}
|
||||
|
||||
<T> void initialize(Class<T> playerClass, IEaglerXServerAPI<T> handle) {
|
||||
this.playerClass = playerClass;
|
||||
this.playerClassSet = Collections.singleton(playerClass);
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
static EaglerXServerAPIFactory.Factory createFactory() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
import java.util.UUID;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformPlayer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IBasePlayer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerXServerAPI;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.INettyChannel;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.attribute.IAttributeKey;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.brand.IBrandRegistry;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.skins.ISkinManagerBase;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.rpc.BasePlayerRPCManager;
|
||||
|
||||
public class BasePlayerInstance<PlayerObject> extends IIdentifiedConnection.Base
|
||||
implements IBasePlayer<PlayerObject>, INettyChannel.NettyUnsafe {
|
||||
|
||||
protected final IPlatformPlayer<PlayerObject> player;
|
||||
protected final EaglerAttributeManager.EaglerAttributeHolder attributeHolder;
|
||||
protected final EaglerXServer<PlayerObject> server;
|
||||
ISkinManagerBase<PlayerObject> skinManager;
|
||||
BasePlayerRPCManager<PlayerObject> backendRPCManager;
|
||||
DataSerializationContext serializationContext;
|
||||
|
||||
public BasePlayerInstance(IPlatformPlayer<PlayerObject> player,
|
||||
EaglerAttributeManager.EaglerAttributeHolder attributeHolder, EaglerXServer<PlayerObject> server) {
|
||||
this.player = player;
|
||||
this.attributeHolder = attributeHolder;
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
public IPlatformPlayer<PlayerObject> getPlatformPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return player.getUsername();
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUniqueId() {
|
||||
return player.getUniqueId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getSocketAddress() {
|
||||
return player.getChannel().remoteAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMinecraftProtocol() {
|
||||
return player.getMinecraftProtocol();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getPlayerAddress() {
|
||||
return player.getSocketAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEaglerPlayer() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EaglerPlayerInstance<PlayerObject> asEaglerPlayer() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getIdentityToken() {
|
||||
return attributeHolder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T get(IAttributeKey<T> key) {
|
||||
return attributeHolder.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void set(IAttributeKey<T> key, T value) {
|
||||
attributeHolder.set(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerXServerAPI<PlayerObject> getServerAPI() {
|
||||
return server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerObject getPlayerObject() {
|
||||
return player.getPlayerObject();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMinecraftBrand() {
|
||||
return player.getMinecraftBrand();
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getEaglerBrandUUID() {
|
||||
return IBrandRegistry.BRAND_VANILLA;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConnected() {
|
||||
return player.isConnected();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOnlineMode() {
|
||||
return player.isOnlineMode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ISkinManagerBase<PlayerObject> getSkinManager() {
|
||||
return skinManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendChatMessage(String message) {
|
||||
if (message == null) {
|
||||
throw new NullPointerException("message");
|
||||
}
|
||||
player.sendMessage(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <ComponentObject> void sendChatMessage(ComponentObject message) {
|
||||
if (message == null) {
|
||||
throw new NullPointerException("message");
|
||||
}
|
||||
player.sendMessage(message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnect() {
|
||||
player.disconnect();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnect(String kickMessage) {
|
||||
if (kickMessage == null) {
|
||||
throw new NullPointerException("kickMessage");
|
||||
}
|
||||
player.disconnect(kickMessage);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <ComponentObject> void disconnect(ComponentObject kickMessage) {
|
||||
if (kickMessage == null) {
|
||||
throw new NullPointerException("kickMessage");
|
||||
}
|
||||
player.disconnect(kickMessage);
|
||||
}
|
||||
|
||||
public EaglerXServer<PlayerObject> getEaglerXServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NettyUnsafe netty() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Channel getChannel() {
|
||||
return player.getChannel();
|
||||
}
|
||||
|
||||
public BasePlayerRPCManager<PlayerObject> getPlayerRPCManager() {
|
||||
return backendRPCManager;
|
||||
}
|
||||
|
||||
public DataSerializationContext getSerializationContext() {
|
||||
if (serializationContext == null) {
|
||||
serializationContext = new DataSerializationContext();
|
||||
}
|
||||
return serializationContext;
|
||||
}
|
||||
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.EnumRequestMethod;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IBinaryHTTPClient;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IBinaryHTTPResponse;
|
||||
import net.lax1dude.eaglercraft.backend.skin_cache.IHTTPClient;
|
||||
import net.lax1dude.eaglercraft.backend.skin_cache.IHTTPClient.Response;
|
||||
|
||||
public class BinaryHTTPClient implements IBinaryHTTPClient {
|
||||
|
||||
private static class ResponseWrapper
|
||||
implements Consumer<Response>, IBinaryHTTPResponse, IBinaryHTTPResponse.NettyUnsafe {
|
||||
|
||||
private final Consumer<IBinaryHTTPResponse> responseCallback;
|
||||
private Response response;
|
||||
|
||||
public ResponseWrapper(Consumer<IBinaryHTTPResponse> responseCallback) {
|
||||
this.responseCallback = responseCallback;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(Response t) {
|
||||
try {
|
||||
if (response != null || t == null) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
response = t;
|
||||
responseCallback.accept(this);
|
||||
} finally {
|
||||
if (t.data != null) {
|
||||
t.data.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSuccess() {
|
||||
return response.exception == null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Throwable getFailureReason() {
|
||||
return response.exception;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRedirected() {
|
||||
return response.redirected;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getResponseCode() {
|
||||
return response.code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getResponseBody() {
|
||||
ByteBuf buf = response.data;
|
||||
if (buf == null) {
|
||||
return null;
|
||||
}
|
||||
byte[] data = new byte[buf.readableBytes()];
|
||||
buf.getBytes(buf.readerIndex(), data);
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NettyUnsafe netty() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ByteBuf getResponseBodyBuffer() {
|
||||
ByteBuf buf = response.data;
|
||||
return buf != null ? buf.retainedSlice() : null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private final IHTTPClient httpClient;
|
||||
|
||||
public BinaryHTTPClient(IHTTPClient httpClient) {
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void asyncRequest(EnumRequestMethod method, URI requestURI, Consumer<IBinaryHTTPResponse> responseCallback) {
|
||||
if (method == null) {
|
||||
throw new NullPointerException("method");
|
||||
}
|
||||
if (requestURI == null) {
|
||||
throw new NullPointerException("requestURI");
|
||||
}
|
||||
if (responseCallback == null) {
|
||||
throw new NullPointerException("responseCallback");
|
||||
}
|
||||
httpClient.asyncRequest(method.name(), requestURI, new ResponseWrapper(responseCallback));
|
||||
}
|
||||
|
||||
}
|
||||
+379
@@ -0,0 +1,379 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerXServerAPI;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.brand.IBrandRegistration;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.brand.IBrandService;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.supervisor.ISupervisorServiceImpl;
|
||||
import net.lax1dude.eaglercraft.backend.server.util.GsonMap;
|
||||
|
||||
public class BrandService<PlayerObject> implements IBrandService<PlayerObject> {
|
||||
|
||||
private static class BrandRegistrationVanilla implements IBrandRegistration {
|
||||
|
||||
@Override
|
||||
public UUID getBrandUUID() {
|
||||
return BRAND_VANILLA;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrandDesc() {
|
||||
return "Vanilla";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanillaMinecraft() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanillaEagler() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLegacyClient() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHackedClient() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class BrandRegistrationEaglerV4 implements IBrandRegistration {
|
||||
|
||||
@Override
|
||||
public UUID getBrandUUID() {
|
||||
return BRAND_EAGLERCRAFTX_V4;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrandDesc() {
|
||||
return "EaglercraftX";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanillaMinecraft() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanillaEagler() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLegacyClient() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHackedClient() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class BrandRegistrationEagler112 implements IBrandRegistration {
|
||||
|
||||
@Override
|
||||
public UUID getBrandUUID() {
|
||||
return BRAND_EAGLERCRAFT_1_12;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrandDesc() {
|
||||
return "Eaglercraft 1.12";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanillaMinecraft() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanillaEagler() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLegacyClient() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHackedClient() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class BrandRegistrationEaglerOld implements IBrandRegistration {
|
||||
|
||||
@Override
|
||||
public UUID getBrandUUID() {
|
||||
return BRAND_EAGLERCRAFTX_LEGACY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrandDesc() {
|
||||
return "EaglercraftX (pre-u37)";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanillaMinecraft() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanillaEagler() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLegacyClient() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHackedClient() {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static class BrandRegistration implements IBrandRegistration {
|
||||
|
||||
protected final UUID uuid;
|
||||
protected final String desc;
|
||||
protected final boolean hacked;
|
||||
protected final boolean legacy;
|
||||
|
||||
protected BrandRegistration(UUID uuid, String desc, boolean hacked, boolean legacy) {
|
||||
this.uuid = uuid;
|
||||
this.desc = desc;
|
||||
this.hacked = hacked;
|
||||
this.legacy = legacy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getBrandUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBrandDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanillaMinecraft() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVanillaEagler() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLegacyClient() {
|
||||
return legacy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHackedClient() {
|
||||
return hacked;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private final EaglerXServer<PlayerObject> server;
|
||||
private final ReadWriteLock mapLock;
|
||||
private final Map<UUID, IBrandRegistration> map;
|
||||
|
||||
private static final Set<UUID> builtinUUIDs = ImmutableSet.<UUID>builder().add(BRAND_VANILLA)
|
||||
.add(BRAND_EAGLERCRAFTX_V4).add(BRAND_EAGLERCRAFTX_LEGACY).add(BRAND_EAGLERCRAFT_1_12).build();
|
||||
|
||||
private static final Set<UUID> invalidUUIDs = ImmutableSet.<UUID>builder().add(BRAND_VANILLA)
|
||||
.add(new UUID(0x6969696969696969L, 0x6969696969696969L))
|
||||
.add(ClientStateFlagUUIDs.LEGACY_EAGLER_PLAYER_FLAG_PRESENT).build();
|
||||
|
||||
public BrandService(EaglerXServer<PlayerObject> serverIn) {
|
||||
server = serverIn;
|
||||
mapLock = new ReentrantReadWriteLock();
|
||||
map = new HashMap<>();
|
||||
map.put(BRAND_VANILLA, new BrandRegistrationVanilla());
|
||||
map.put(serverIn.intern(BRAND_EAGLERCRAFTX_V4), new BrandRegistrationEaglerV4());
|
||||
map.put(serverIn.intern(BRAND_EAGLERCRAFTX_LEGACY), new BrandRegistrationEaglerOld());
|
||||
map.put(serverIn.intern(BRAND_EAGLERCRAFT_1_12), new BrandRegistrationEagler112());
|
||||
InputStream brands = BrandService.class.getResourceAsStream("brands.json");
|
||||
if (brands != null) {
|
||||
JsonObject brandsFile = null;
|
||||
try (Reader reader = new InputStreamReader(brands, StandardCharsets.UTF_8)) {
|
||||
brandsFile = EaglerXServer.GSON_PRETTY.fromJson(reader, JsonObject.class);
|
||||
} catch (IOException | JsonParseException ex) {
|
||||
serverIn.logger().error("Could not read brands.json", ex);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
for (Entry<String, JsonElement> etr : GsonMap.asMap(brandsFile).entrySet()) {
|
||||
UUID uuid = serverIn.intern(UUID.fromString(etr.getKey()));
|
||||
JsonObject val = etr.getValue().getAsJsonObject();
|
||||
map.put(uuid, new BrandRegistration(uuid, val.get("desc").getAsString(),
|
||||
val.get("legacy").getAsBoolean(), val.get("hacked").getAsBoolean()));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
serverIn.logger().error("brands.json is invalid", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerXServerAPI<PlayerObject> getServerAPI() {
|
||||
return server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resolvePlayerBrand(UUID playerUUID, Consumer<UUID> callback) {
|
||||
if (playerUUID == null) {
|
||||
throw new NullPointerException("playerUUID");
|
||||
}
|
||||
if (callback == null) {
|
||||
throw new NullPointerException("callback");
|
||||
}
|
||||
BasePlayerInstance<PlayerObject> player = server.getPlayerByUUID(playerUUID);
|
||||
if (player != null) {
|
||||
callback.accept(player.getEaglerBrandUUID());
|
||||
} else {
|
||||
ISupervisorServiceImpl<PlayerObject> supervisorService = server.getSupervisorService();
|
||||
if (supervisorService.isSupervisorEnabled() && !supervisorService.shouldIgnoreUUID(playerUUID)) {
|
||||
supervisorService.getRemoteOnlyResolver().resolvePlayerBrand(playerUUID, callback);
|
||||
} else {
|
||||
callback.accept(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resolvePlayerRegisteredBrand(UUID playerUUID, BiConsumer<UUID, IBrandRegistration> callback) {
|
||||
if (playerUUID == null) {
|
||||
throw new NullPointerException("playerUUID");
|
||||
}
|
||||
if (callback == null) {
|
||||
throw new NullPointerException("callback");
|
||||
}
|
||||
BasePlayerInstance<PlayerObject> player = server.getPlayerByUUID(playerUUID);
|
||||
if (player != null) {
|
||||
UUID uuid = player.getEaglerBrandUUID();
|
||||
callback.accept(uuid, lookupRegisteredBrand(uuid));
|
||||
} else {
|
||||
ISupervisorServiceImpl<PlayerObject> supervisorService = server.getSupervisorService();
|
||||
if (supervisorService.isSupervisorEnabled() && !supervisorService.shouldIgnoreUUID(playerUUID)) {
|
||||
supervisorService.getRemoteOnlyResolver().resolvePlayerRegisteredBrand(playerUUID, callback);
|
||||
} else {
|
||||
callback.accept(null, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getBrandUUIDClient(String brandString) {
|
||||
return UUID.nameUUIDFromBytes(("EaglercraftXClient:" + brandString).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getBrandUUIDClientLegacy(String brandString) {
|
||||
return UUID.nameUUIDFromBytes(("EaglercraftXClientOld:" + brandString).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerBrand(UUID brandUUID, String brandDesc, boolean hacked, boolean legacy) {
|
||||
if (brandUUID == null) {
|
||||
throw new NullPointerException("brandUUID");
|
||||
}
|
||||
if (brandDesc == null) {
|
||||
throw new NullPointerException("brandDesc");
|
||||
}
|
||||
if (!builtinUUIDs.contains(brandUUID)) {
|
||||
IBrandRegistration reg = new BrandRegistration(brandUUID, brandDesc, hacked, legacy);
|
||||
mapLock.writeLock().lock();
|
||||
try {
|
||||
map.put(brandUUID, reg);
|
||||
} finally {
|
||||
mapLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregisterBrand(UUID brandUUID) {
|
||||
if (brandUUID == null) {
|
||||
throw new NullPointerException("brandUUID");
|
||||
}
|
||||
if (!builtinUUIDs.contains(brandUUID)) {
|
||||
mapLock.writeLock().lock();
|
||||
try {
|
||||
map.remove(brandUUID);
|
||||
} finally {
|
||||
mapLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBrandRegistration lookupRegisteredBrand(UUID brandUUID) {
|
||||
if (brandUUID == null) {
|
||||
throw new NullPointerException("brandUUID");
|
||||
}
|
||||
mapLock.readLock().lock();
|
||||
try {
|
||||
return map.get(brandUUID);
|
||||
} finally {
|
||||
mapLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean sanitizeUUID(UUID uuid) {
|
||||
return !invalidUUIDs.contains(uuid);
|
||||
}
|
||||
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
public class CapabilityBits {
|
||||
|
||||
public static boolean hasCapability(int mask, byte[] vers, int id, int ver) {
|
||||
int bit = 1 << id;
|
||||
if ((mask & bit) != 0) {
|
||||
int versIndex = Integer.bitCount(mask & (bit - 1));
|
||||
if (versIndex < vers.length) {
|
||||
return (vers[versIndex] & 0xFF) >= ver;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static int getCapability(int mask, byte[] vers, int id) {
|
||||
int bit = 1 << id;
|
||||
if ((mask & bit) != 0) {
|
||||
int versIndex = Integer.bitCount(mask & (bit - 1));
|
||||
if (versIndex < vers.length) {
|
||||
return vers[versIndex] & 0xFF;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class ClientStateFlagUUIDs {
|
||||
|
||||
public static final UUID EAGLER_PLAYER_FLAG_PRESENT = new UUID(0x55F63601694140D9L, 0xB77BCE7B99A62E52L);
|
||||
|
||||
public static final UUID LEGACY_EAGLER_PLAYER_FLAG_PRESENT = new UUID(0xEEEEA64771094C4EL, 0x86E55B81D17E67EBL);
|
||||
|
||||
public static final UUID DISABLE_SKIN_URL_LOOKUP = new UUID(0xC41D641BE2DA4094L, 0xB1B2DFF2E9D08180L);
|
||||
|
||||
public static final UUID SET_MAX_MULTI_PACKET = new UUID(0x877BC5F5A2154DDBL, 0xB493BE790A763E90L);
|
||||
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformComponentHelper;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IComponentSerializer;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.config.ChatColor;
|
||||
|
||||
public class ComponentHelper<ComponentType> implements IComponentSerializer<ComponentType> {
|
||||
|
||||
private final IPlatformComponentHelper platformImpl;
|
||||
|
||||
public ComponentHelper(IPlatformComponentHelper platformImpl) {
|
||||
this.platformImpl = platformImpl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serializeLegacySection(ComponentType component) {
|
||||
if (component == null) {
|
||||
throw new NullPointerException("component is null");
|
||||
}
|
||||
return platformImpl.serializeLegacySection(component);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serializePlainText(ComponentType component) {
|
||||
if (component == null) {
|
||||
throw new NullPointerException("component is null");
|
||||
}
|
||||
return platformImpl.serializePlainText(component);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serializeGenericJSON(ComponentType component) {
|
||||
if (component == null) {
|
||||
throw new NullPointerException("component is null");
|
||||
}
|
||||
return platformImpl.serializeGenericJSON(component);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serializeLegacyJSON(ComponentType component) {
|
||||
if (component == null) {
|
||||
throw new NullPointerException("component is null");
|
||||
}
|
||||
return platformImpl.serializeLegacyJSON(component);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serializeModernJSON(ComponentType component) {
|
||||
if (component == null) {
|
||||
throw new NullPointerException("component is null");
|
||||
}
|
||||
return platformImpl.serializeModernJSON(component);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public ComponentType parseGenericJSON(String json) throws IllegalArgumentException {
|
||||
if (json == null) {
|
||||
throw new NullPointerException("json is null");
|
||||
}
|
||||
return (ComponentType) platformImpl.parseGenericJSON(json);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public ComponentType parseLegacyJSON(String json) throws IllegalArgumentException {
|
||||
if (json == null) {
|
||||
throw new NullPointerException("json is null");
|
||||
}
|
||||
return (ComponentType) platformImpl.parseLegacyJSON(json);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public ComponentType parseModernJSON(String json) throws IllegalArgumentException {
|
||||
if (json == null) {
|
||||
throw new NullPointerException("json is null");
|
||||
}
|
||||
return (ComponentType) platformImpl.parseModernJSON(json);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convertJSONToLegacySection(String json) throws IllegalArgumentException {
|
||||
if (json == null) {
|
||||
throw new NullPointerException("json is null");
|
||||
}
|
||||
return platformImpl.serializeLegacySection(platformImpl.parseGenericJSON(json));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convertJSONToPlainText(String json) throws IllegalArgumentException {
|
||||
if (json == null) {
|
||||
throw new NullPointerException("json is null");
|
||||
}
|
||||
return platformImpl.serializePlainText(platformImpl.parseGenericJSON(json));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String translateAlternateColorCodes(char altColorChar, String textToTranslate) {
|
||||
if (textToTranslate == null) {
|
||||
throw new NullPointerException("textToTranslate is null");
|
||||
}
|
||||
return ChatColor.translateAlternateColorCodes(altColorChar, textToTranslate);
|
||||
}
|
||||
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.base.config.ConfigDataListener;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.config.ConfigDataListener.ConfigRateLimit;
|
||||
import net.lax1dude.eaglercraft.backend.server.util.EnumRateLimitState;
|
||||
import net.lax1dude.eaglercraft.backend.server.util.RateLimiterExclusions;
|
||||
import net.lax1dude.eaglercraft.backend.server.util.RateLimiterLocking;
|
||||
import net.lax1dude.eaglercraft.backend.server.util.RateLimiterLocking.Config;
|
||||
|
||||
public class CompoundRateLimiterMap {
|
||||
|
||||
public static CompoundRateLimiterMap create(ConfigDataListener.ConfigRateLimit ratelimitIPConfIn,
|
||||
ConfigDataListener.ConfigRateLimit ratelimitLoginConfIn,
|
||||
ConfigDataListener.ConfigRateLimit ratelimitMOTDConfIn,
|
||||
ConfigDataListener.ConfigRateLimit ratelimitQueryConfIn,
|
||||
ConfigDataListener.ConfigRateLimit ratelimitHTTPConfIn, RateLimiterExclusions ratelimitExclusions) {
|
||||
if (!ratelimitIPConfIn.isEnabled() && !ratelimitLoginConfIn.isEnabled() && !ratelimitMOTDConfIn.isEnabled()
|
||||
&& !ratelimitQueryConfIn.isEnabled() && !ratelimitHTTPConfIn.isEnabled()) {
|
||||
return null;
|
||||
}
|
||||
RateLimiterLocking.Config ratelimitIPConf = createConf(ratelimitIPConfIn);
|
||||
RateLimiterLocking.Config ratelimitLoginConf = createConf(ratelimitLoginConfIn);
|
||||
RateLimiterLocking.Config ratelimitMOTDConf = createConf(ratelimitMOTDConfIn);
|
||||
RateLimiterLocking.Config ratelimitQueryConf = createConf(ratelimitQueryConfIn);
|
||||
RateLimiterLocking.Config ratelimitHTTPConf = createConf(ratelimitHTTPConfIn);
|
||||
return new CompoundRateLimiterMap(ratelimitIPConf, ratelimitLoginConf, ratelimitMOTDConf, ratelimitQueryConf,
|
||||
ratelimitHTTPConf, ratelimitExclusions);
|
||||
}
|
||||
|
||||
private static RateLimiterLocking.Config createConf(ConfigRateLimit ratelimitIPConfIn) {
|
||||
if (!ratelimitIPConfIn.isEnabled()) {
|
||||
return null;
|
||||
}
|
||||
return new RateLimiterLocking.Config(ratelimitIPConfIn.getPeriod(), ratelimitIPConfIn.getLimit(),
|
||||
ratelimitIPConfIn.getLimitLockout(), ratelimitIPConfIn.getLockoutDuration());
|
||||
}
|
||||
|
||||
public static interface ICompoundRatelimits {
|
||||
EnumRateLimitState rateLimitLogin();
|
||||
|
||||
EnumRateLimitState rateLimitMOTD();
|
||||
|
||||
EnumRateLimitState rateLimitQuery();
|
||||
|
||||
EnumRateLimitState rateLimitHTTP();
|
||||
}
|
||||
|
||||
private static final ICompoundRatelimits ALWAYS_OK = new ICompoundRatelimits() {
|
||||
@Override
|
||||
public EnumRateLimitState rateLimitLogin() {
|
||||
return EnumRateLimitState.OK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumRateLimitState rateLimitMOTD() {
|
||||
return EnumRateLimitState.OK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumRateLimitState rateLimitQuery() {
|
||||
return EnumRateLimitState.OK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumRateLimitState rateLimitHTTP() {
|
||||
return EnumRateLimitState.OK;
|
||||
}
|
||||
};
|
||||
|
||||
private class RateLimits extends RateLimiterLocking implements ICompoundRatelimits {
|
||||
|
||||
private RateLimiterLocking ratelimitLogin;
|
||||
private RateLimiterLocking ratelimitMOTD;
|
||||
private RateLimiterLocking ratelimitQuery;
|
||||
private RateLimiterLocking ratelimitHTTP;
|
||||
|
||||
@Override
|
||||
public EnumRateLimitState rateLimitLogin() {
|
||||
if (ratelimitLoginConf == null) {
|
||||
return EnumRateLimitState.OK;
|
||||
}
|
||||
RateLimiterLocking limiter = ratelimitLogin;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitLogin = new RateLimiterLocking();
|
||||
}
|
||||
return limiter.rateLimit(ratelimitLoginConf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumRateLimitState rateLimitMOTD() {
|
||||
if (ratelimitMOTDConf == null) {
|
||||
return EnumRateLimitState.OK;
|
||||
}
|
||||
RateLimiterLocking limiter = ratelimitMOTD;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitMOTD = new RateLimiterLocking();
|
||||
}
|
||||
return limiter.rateLimit(ratelimitMOTDConf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumRateLimitState rateLimitQuery() {
|
||||
if (ratelimitQueryConf == null) {
|
||||
return EnumRateLimitState.OK;
|
||||
}
|
||||
RateLimiterLocking limiter = ratelimitQuery;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitQuery = new RateLimiterLocking();
|
||||
}
|
||||
return limiter.rateLimit(ratelimitQueryConf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EnumRateLimitState rateLimitHTTP() {
|
||||
if (ratelimitHTTPConf == null) {
|
||||
return EnumRateLimitState.OK;
|
||||
}
|
||||
RateLimiterLocking limiter = ratelimitHTTP;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitHTTP = new RateLimiterLocking();
|
||||
}
|
||||
return limiter.rateLimit(ratelimitHTTPConf);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private final LoadingCache<InetAddress, RateLimits> cache;
|
||||
|
||||
private final RateLimiterLocking.Config ratelimitIPConf;
|
||||
private final RateLimiterLocking.Config ratelimitLoginConf;
|
||||
private final RateLimiterLocking.Config ratelimitMOTDConf;
|
||||
private final RateLimiterLocking.Config ratelimitQueryConf;
|
||||
private final RateLimiterLocking.Config ratelimitHTTPConf;
|
||||
private final RateLimiterExclusions ratelimitExclusions;
|
||||
|
||||
private CompoundRateLimiterMap(Config ratelimitIPConf, Config ratelimitLoginConf, Config ratelimitMOTDConf,
|
||||
Config ratelimitQueryConf, Config ratelimitHTTPConf, RateLimiterExclusions ratelimitExclusions) {
|
||||
this.cache = CacheBuilder.newBuilder().expireAfterAccess(5l, TimeUnit.MINUTES).maximumSize(8192)
|
||||
.build(new CacheLoader<InetAddress, RateLimits>() {
|
||||
@Override
|
||||
public RateLimits load(InetAddress arg0) throws Exception {
|
||||
return new RateLimits();
|
||||
}
|
||||
});
|
||||
this.ratelimitIPConf = ratelimitIPConf;
|
||||
this.ratelimitLoginConf = ratelimitLoginConf;
|
||||
this.ratelimitMOTDConf = ratelimitMOTDConf;
|
||||
this.ratelimitQueryConf = ratelimitQueryConf;
|
||||
this.ratelimitHTTPConf = ratelimitHTTPConf;
|
||||
this.ratelimitExclusions = ratelimitExclusions;
|
||||
}
|
||||
|
||||
private RateLimits load(InetAddress address) {
|
||||
try {
|
||||
return cache.get(address);
|
||||
} catch (ExecutionException e) {
|
||||
if (e.getCause() instanceof RuntimeException ee)
|
||||
throw ee;
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public ICompoundRatelimits rateLimit(InetAddress address) {
|
||||
if (ratelimitExclusions != null && ratelimitExclusions.testExclusion(address)) {
|
||||
return ALWAYS_OK;
|
||||
} else {
|
||||
RateLimits limits = load(address);
|
||||
return (ratelimitIPConf == null || limits.rateLimit(ratelimitIPConf).isOk()) ? limits : null;
|
||||
}
|
||||
}
|
||||
|
||||
public ICompoundRatelimits getRateLimit(InetAddress address) {
|
||||
if (ratelimitExclusions != null && ratelimitExclusions.testExclusion(address)) {
|
||||
return ALWAYS_OK;
|
||||
} else {
|
||||
return load(address);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
|
||||
import net.lax1dude.eaglercraft.v1_8.socket.protocol.util.ReusableByteArrayInputStream;
|
||||
import net.lax1dude.eaglercraft.v1_8.socket.protocol.util.ReusableByteArrayOutputStream;
|
||||
|
||||
public class DataSerializationContext {
|
||||
|
||||
public final ReusableByteArrayInputStream byteInputStreamSingleton = new ReusableByteArrayInputStream();
|
||||
public final ReusableByteArrayOutputStream byteOutputStreamSingleton = new ReusableByteArrayOutputStream();
|
||||
public final DataInputStream inputStreamSingleton = new DataInputStream(byteInputStreamSingleton);
|
||||
public final DataOutputStream outputStreamSingleton = new DataOutputStream(byteOutputStreamSingleton);
|
||||
public final byte[] outputTempBuffer = new byte[512];
|
||||
|
||||
private volatile int inputStreamLock;
|
||||
private volatile int outputStreamLock;
|
||||
|
||||
private static final VarHandle IS_LOCK_HANDLE;
|
||||
private static final VarHandle OS_LOCK_HANDLE;
|
||||
|
||||
static {
|
||||
try {
|
||||
MethodHandles.Lookup l = MethodHandles.lookup();
|
||||
IS_LOCK_HANDLE = l.findVarHandle(DataSerializationContext.class, "inputStreamLock", int.class);
|
||||
OS_LOCK_HANDLE = l.findVarHandle(DataSerializationContext.class, "outputStreamLock", int.class);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new ExceptionInInitializerError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public final boolean aquireInputStream() {
|
||||
return (int) IS_LOCK_HANDLE.compareAndExchangeAcquire(this, 0, 1) == 0;
|
||||
}
|
||||
|
||||
public final void releaseInputStream() {
|
||||
IS_LOCK_HANDLE.setRelease(this, 0);
|
||||
}
|
||||
|
||||
public final boolean aquireOutputStream() {
|
||||
return (int) OS_LOCK_HANDLE.compareAndExchangeAcquire(this, 0, 1) == 0;
|
||||
}
|
||||
|
||||
public final void releaseOutputStream() {
|
||||
OS_LOCK_HANDLE.setRelease(this, 0);
|
||||
}
|
||||
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.skin_cache.ISkinCacheService;
|
||||
|
||||
class DeferredStartSkinCache implements ISkinCacheService {
|
||||
|
||||
private final List<Consumer<ISkinCacheService>> deferredTasks = new LinkedList<>();
|
||||
|
||||
private ISkinCacheService service;
|
||||
|
||||
void setDelegate(ISkinCacheService service) {
|
||||
this.service = service;
|
||||
if (service != null) {
|
||||
List<Consumer<ISkinCacheService>> lst;
|
||||
synchronized (deferredTasks) {
|
||||
lst = new ArrayList<>(deferredTasks);
|
||||
deferredTasks.clear();
|
||||
}
|
||||
if (!lst.isEmpty()) {
|
||||
for (Consumer<ISkinCacheService> consumer : lst) {
|
||||
consumer.accept(service);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resolveSkinByURL(String skinURL, Consumer<byte[]> callback) {
|
||||
ISkinCacheService svc = service;
|
||||
if (svc != null) {
|
||||
svc.resolveSkinByURL(skinURL, callback);
|
||||
} else {
|
||||
synchronized (deferredTasks) {
|
||||
deferredTasks.add((svc2) -> {
|
||||
svc2.resolveSkinByURL(skinURL, callback);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resolveCapeByURL(String capeURL, Consumer<byte[]> callback) {
|
||||
ISkinCacheService svc = service;
|
||||
if (svc != null) {
|
||||
svc.resolveCapeByURL(capeURL, callback);
|
||||
} else {
|
||||
synchronized (deferredTasks) {
|
||||
deferredTasks.add((svc2) -> {
|
||||
svc2.resolveCapeByURL(capeURL, callback);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tick() {
|
||||
ISkinCacheService svc = service;
|
||||
if (svc != null) {
|
||||
svc.tick();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTotalMemorySkins() {
|
||||
ISkinCacheService svc = service;
|
||||
if (svc != null) {
|
||||
return svc.getTotalMemorySkins();
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTotalMemoryCapes() {
|
||||
ISkinCacheService svc = service;
|
||||
if (svc != null) {
|
||||
return svc.getTotalMemoryCapes();
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTotalStoredSkins() {
|
||||
ISkinCacheService svc = service;
|
||||
if (svc != null) {
|
||||
return svc.getTotalStoredSkins();
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTotalStoredCapes() {
|
||||
ISkinCacheService svc = service;
|
||||
if (svc != null) {
|
||||
return svc.getTotalStoredCapes();
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.attribute.IAttributeHolder;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.attribute.IAttributeKey;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.attribute.IAttributeManager;
|
||||
|
||||
public class EaglerAttributeManager implements IAttributeManager {
|
||||
|
||||
private abstract class AttributeKeyBase<T> implements IAttributeKey<T> {
|
||||
|
||||
protected final Class<T> type;
|
||||
|
||||
protected AttributeKeyBase(Class<T> type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<T> getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
protected final void validate(EaglerAttributeManager mgr) {
|
||||
if (mgr != EaglerAttributeManager.this) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private class AttributeKeyGlobal<T> extends AttributeKeyBase<T> {
|
||||
|
||||
protected final String name;
|
||||
|
||||
protected AttributeKeyGlobal(Class<T> type, String name) {
|
||||
super(type);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGlobal() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "global:" + name;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private class AttributeKeyPrivate<T> extends AttributeKeyBase<T> {
|
||||
|
||||
protected final String name;
|
||||
|
||||
protected AttributeKeyPrivate(Class<T> type, String name) {
|
||||
super(type);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGlobal() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "private:" + name + "#" + Integer.toHexString(hashCode());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private final Map<String, IAttributeKey<?>> globals = new HashMap<>();
|
||||
|
||||
@Override
|
||||
public <T> IAttributeKey<T> initGlobalAttribute(String name, Class<T> type) {
|
||||
if (name == null) {
|
||||
throw new NullPointerException("name");
|
||||
}
|
||||
if (type == null) {
|
||||
throw new NullPointerException("type");
|
||||
}
|
||||
IAttributeKey<?> ret;
|
||||
synchronized (globals) {
|
||||
ret = globals.get(name);
|
||||
if (ret == null) {
|
||||
IAttributeKey<T> tmp;
|
||||
globals.put(name, tmp = new AttributeKeyGlobal<>(type, name));
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
if (ret.getType() != type) {
|
||||
throw new IllegalStateException("Attribute type conflict for \"" + name + "\": " + type.getName() + " != "
|
||||
+ ret.getType().getName());
|
||||
}
|
||||
return (IAttributeKey<T>) ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> IAttributeKey<T> initPrivateAttribute(String name, Class<T> type) {
|
||||
if (name == null) {
|
||||
throw new NullPointerException("name");
|
||||
}
|
||||
if (type == null) {
|
||||
throw new NullPointerException("type");
|
||||
}
|
||||
return new AttributeKeyPrivate<>(type, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> IAttributeKey<T> initPrivateAttribute(Class<T> type) {
|
||||
if (type == null) {
|
||||
throw new NullPointerException("type");
|
||||
}
|
||||
return new AttributeKeyPrivate<>(type, "unnamed");
|
||||
}
|
||||
|
||||
public class EaglerAttributeHolder implements IAttributeHolder {
|
||||
|
||||
private final ConcurrentMap<AttributeKeyBase<?>, Object> attribMap = new ConcurrentHashMap<>(4);
|
||||
|
||||
@Override
|
||||
public final <T> T get(IAttributeKey<T> key) {
|
||||
if (key == null) {
|
||||
throw new NullPointerException("key");
|
||||
}
|
||||
AttributeKeyBase<?> checkCast = (AttributeKeyBase<?>) key;
|
||||
checkCast.validate(EaglerAttributeManager.this);
|
||||
return (T) attribMap.get(checkCast);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final <T> void set(IAttributeKey<T> key, T value) {
|
||||
if (key == null) {
|
||||
throw new NullPointerException("key");
|
||||
}
|
||||
AttributeKeyBase<?> checkCast = (AttributeKeyBase<?>) key;
|
||||
checkCast.validate(EaglerAttributeManager.this);
|
||||
if (value != null) {
|
||||
attribMap.put(checkCast, value);
|
||||
} else {
|
||||
attribMap.remove(checkCast);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public IAttributeHolder createHolder() {
|
||||
return new EaglerAttributeHolder();
|
||||
}
|
||||
|
||||
public EaglerAttributeHolder createEaglerHolder() {
|
||||
return new EaglerAttributeHolder();
|
||||
}
|
||||
|
||||
}
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import javax.net.ssl.SSLException;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IEaglerXServerListener;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerListenerInfo;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.ITLSManager;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.attribute.IAttributeKey;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.EaglerAttributeManager.EaglerAttributeHolder;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.config.ConfigDataListener;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.pipeline.WebSocketEaglerInitialHandler;
|
||||
import net.lax1dude.eaglercraft.backend.server.util.RateLimiterExclusions;
|
||||
|
||||
public class EaglerListener implements IEaglerListenerInfo, IEaglerXServerListener {
|
||||
|
||||
private final EaglerXServer<?> server;
|
||||
private final SocketAddress address;
|
||||
private final ConfigDataListener listenerConf;
|
||||
private final EaglerAttributeHolder attrHolder;
|
||||
private final boolean sslPluginManaged;
|
||||
private final ISSLContextProvider sslContext;
|
||||
private final byte[] legacyRedirectAddressBuf;
|
||||
private byte[] cachedServerIcon;
|
||||
private List<String> cachedServerMOTD;
|
||||
private CompoundRateLimiterMap rateLimiter;
|
||||
|
||||
EaglerListener(EaglerXServer<?> server, ConfigDataListener listenerConf) throws SSLException, IOException {
|
||||
this(server, listenerConf.getInjectAddress(), listenerConf);
|
||||
}
|
||||
|
||||
EaglerListener(EaglerXServer<?> server, SocketAddress address, ConfigDataListener listenerConf)
|
||||
throws SSLException, IOException {
|
||||
this.server = server;
|
||||
this.address = address;
|
||||
this.listenerConf = listenerConf;
|
||||
this.attrHolder = server.getEaglerAttribManager().createEaglerHolder();
|
||||
if (listenerConf.isEnableTLS()) {
|
||||
this.sslPluginManaged = listenerConf.isTLSManagedByExternalPlugin();
|
||||
if (this.sslPluginManaged) {
|
||||
this.sslContext = new SSLContextHolderPlugin(this);
|
||||
} else {
|
||||
this.sslContext = server.getCertificateManager().createHolder(
|
||||
new File(listenerConf.getTLSPublicChainFile()), new File(listenerConf.getTLSPrivateKeyFile()),
|
||||
listenerConf.getTLSPrivateKeyPassword(), listenerConf.isTLSAutoRefreshCert());
|
||||
}
|
||||
} else {
|
||||
this.sslPluginManaged = false;
|
||||
this.sslContext = null;
|
||||
}
|
||||
if (listenerConf.getRedirectLegacyClientsTo() != null) {
|
||||
this.legacyRedirectAddressBuf = WebSocketEaglerInitialHandler
|
||||
.prepareRedirectAddr(listenerConf.getRedirectLegacyClientsTo());
|
||||
} else {
|
||||
this.legacyRedirectAddressBuf = null;
|
||||
}
|
||||
cachedServerMOTD = listenerConf.getServerMOTD();
|
||||
String iconName = listenerConf.getServerIcon();
|
||||
if (iconName != null && !iconName.isEmpty()) {
|
||||
try {
|
||||
cachedServerIcon = server.getServerIconLoader().loadServerIcon(new File(iconName));
|
||||
} catch (FileNotFoundException ex) {
|
||||
server.logger().error("Could not load server icon: " + iconName + " (not found)");
|
||||
cachedServerIcon = null;
|
||||
} catch (IOException ex) {
|
||||
server.logger().error("Could not load server icon: " + iconName, ex);
|
||||
cachedServerIcon = null;
|
||||
}
|
||||
} else {
|
||||
cachedServerIcon = null;
|
||||
}
|
||||
rateLimiter = CompoundRateLimiterMap.create(listenerConf.getLimitIP(), listenerConf.getLimitLogin(),
|
||||
listenerConf.getLimitMOTD(), listenerConf.getLimitQuery(), listenerConf.getLimitHTTP(),
|
||||
RateLimiterExclusions.create(listenerConf.getLimitExclusions(), server.logger()));
|
||||
}
|
||||
|
||||
public ISSLContextProvider getSSLContext() {
|
||||
return sslContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T get(IAttributeKey<T> key) {
|
||||
return attrHolder.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void set(IAttributeKey<T> key, T value) {
|
||||
attrHolder.set(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return listenerConf.getListenerName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDualStack() {
|
||||
return listenerConf.isDualStack();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTLSEnabled() {
|
||||
return listenerConf.isEnableTLS();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTLSRequired() {
|
||||
return listenerConf.isRequireTLS();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTLSManagedByPlugin() {
|
||||
return sslPluginManaged;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITLSManager getTLSManager() throws IllegalStateException {
|
||||
if (!listenerConf.isEnableTLS()) {
|
||||
throw new IllegalStateException("TLS is not enabled on this listener!");
|
||||
}
|
||||
if (!sslPluginManaged) {
|
||||
throw new IllegalStateException(
|
||||
"TLS manager is disabled for this listener! (Set 'tls_managed_by_external_plugin' to true)");
|
||||
}
|
||||
return (ITLSManager) sslContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getServerIcon() {
|
||||
return cachedServerIcon;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setServerIcon(byte[] pixels) {
|
||||
if (pixels != null && pixels.length != 16384) {
|
||||
throw new IllegalArgumentException("Server icon is the wrong length, should be 16384");
|
||||
}
|
||||
cachedServerIcon = pixels;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getServerMOTD() {
|
||||
return cachedServerMOTD;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setServerMOTD(List<String> motd) {
|
||||
if (motd == null || motd.size() == 0) {
|
||||
cachedServerMOTD = Collections.emptyList();
|
||||
} else if (motd.size() == 1) {
|
||||
cachedServerMOTD = ImmutableList.of(motd.get(0));
|
||||
} else {
|
||||
cachedServerMOTD = ImmutableList.of(motd.get(0), motd.get(1));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isForwardIP() {
|
||||
return listenerConf.isForwardIP();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matchListenerAddress(SocketAddress addr) {
|
||||
if (addr.equals(listenerConf.getInjectAddress())) {
|
||||
return true;
|
||||
} else if ((addr instanceof InetSocketAddress addr2)
|
||||
&& (listenerConf.getInjectAddress() instanceof InetSocketAddress addr3) && isAllZeros(addr2)
|
||||
&& isAllZeros(addr3)) {
|
||||
return addr2.getPort() == addr3.getPort();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isAllZeros(InetSocketAddress addr) {
|
||||
InetAddress addr2 = addr.getAddress();
|
||||
if (addr2 instanceof Inet4Address addr3) {
|
||||
byte[] octets = addr3.getAddress();
|
||||
return (octets[0] | octets[1] | octets[2] | octets[3]) == 0;
|
||||
} else if (addr2 instanceof Inet6Address addr3) {
|
||||
byte[] octets = addr3.getAddress();
|
||||
return (octets[0] | octets[1] | octets[2] | octets[3] | octets[4] | octets[5] | octets[6] | octets[7]
|
||||
| octets[8] | octets[9] | octets[10] | octets[11] | octets[12] | octets[13] | octets[14]
|
||||
| octets[15]) == 0;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCloneListenerEnabled() {
|
||||
return listenerConf.isCloneListenerEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getCloneListenerAddress() {
|
||||
return listenerConf.getInjectAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reportVelocityInjected(Channel channel) {
|
||||
server.logger().info("Listener \"" + listenerConf.getListenerName() + "\" injected into channel " + channel
|
||||
+ " successfully (Velocity method)");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reportPaperMCInjected() {
|
||||
server.logger().info("Default listener injected into server channel successfully (PaperMC method)");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reportNettyInjected(Channel channel) {
|
||||
server.logger().info("Listener \"" + listenerConf.getListenerName() + "\" injected into channel " + channel
|
||||
+ " successfully (Generic Netty method)");
|
||||
}
|
||||
|
||||
public byte[] getLegacyRedirectAddressBuf() {
|
||||
return legacyRedirectAddressBuf;
|
||||
}
|
||||
|
||||
public boolean isAllowMOTD() {
|
||||
return listenerConf.isAllowMOTD();
|
||||
}
|
||||
|
||||
public boolean isAllowQuery() {
|
||||
return listenerConf.isAllowQuery();
|
||||
}
|
||||
|
||||
public boolean isShowMOTDPlayerList() {
|
||||
return listenerConf.isShowMOTDPlayerList();
|
||||
}
|
||||
|
||||
public ConfigDataListener getConfigData() {
|
||||
return listenerConf;
|
||||
}
|
||||
|
||||
public CompoundRateLimiterMap getRateLimiter() {
|
||||
return rateLimiter;
|
||||
}
|
||||
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.EnumCapabilitySpec;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.EnumCapabilityType;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerLoginConnection;
|
||||
|
||||
public class EaglerLoginStateAdapter extends EaglerPendingStateAdapter implements IEaglerLoginConnection {
|
||||
|
||||
EaglerLoginStateAdapter(NettyPipelineData pipelineData) {
|
||||
super(pipelineData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerLoginConnection asEaglerPlayer() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getUniqueId() {
|
||||
return pipelineData.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return pipelineData.username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOnlineMode() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCookieSupported() {
|
||||
return pipelineData.cookieSupport;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCookieEnabled() {
|
||||
return pipelineData.cookieEnabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getCookieData() {
|
||||
return pipelineData.cookieData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasCapability(EnumCapabilitySpec capability) {
|
||||
return CapabilityBits.hasCapability(pipelineData.acceptedCapabilitiesMask,
|
||||
pipelineData.acceptedCapabilitiesVers, capability.getId(), capability.getVer());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCapability(EnumCapabilityType capability) {
|
||||
return CapabilityBits.getCapability(pipelineData.acceptedCapabilitiesMask,
|
||||
pipelineData.acceptedCapabilitiesVers, capability.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasExtendedCapability(UUID extendedCapability, int version) {
|
||||
if (extendedCapability == null) {
|
||||
throw new NullPointerException("extendedCapability");
|
||||
}
|
||||
Byte b = pipelineData.acceptedExtendedCapabilities.get(extendedCapability);
|
||||
return b != null && (b.byteValue() & 0xFF) >= version;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getExtendedCapability(UUID extendedCapability) {
|
||||
if (extendedCapability == null) {
|
||||
throw new NullPointerException("extendedCapability");
|
||||
}
|
||||
Byte b = pipelineData.acceptedExtendedCapabilities.get(extendedCapability);
|
||||
return b != null ? (b.byteValue() & 0xFF) : -1;
|
||||
}
|
||||
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.EnumWebSocketHeader;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerListenerInfo;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerPendingConnection;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.attribute.IAttributeKey;
|
||||
import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageProtocol;
|
||||
|
||||
public class EaglerPendingStateAdapter extends IIdentifiedConnection.Base implements IEaglerPendingConnection {
|
||||
|
||||
protected final NettyPipelineData pipelineData;
|
||||
|
||||
EaglerPendingStateAdapter(NettyPipelineData pipelineData) {
|
||||
this.pipelineData = pipelineData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerListenerInfo getListenerInfo() {
|
||||
return pipelineData.listenerInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getWebSocketHeader(EnumWebSocketHeader header) {
|
||||
return pipelineData.getWebSocketHeader(header);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getWebSocketPath() {
|
||||
return pipelineData.getWebSocketPath();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isWebSocketSecure() {
|
||||
return pipelineData.wss;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getSocketAddress() {
|
||||
return pipelineData.getSocketAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getPlayerAddress() {
|
||||
return pipelineData.getPlayerAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRealAddress() {
|
||||
return pipelineData.realAddress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConnected() {
|
||||
return pipelineData.isConnected();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnect() {
|
||||
pipelineData.disconnect();
|
||||
}
|
||||
|
||||
@Override
|
||||
public NettyUnsafe netty() {
|
||||
return pipelineData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getIdentityToken() {
|
||||
return pipelineData.getIdentityToken();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T get(IAttributeKey<T> key) {
|
||||
return pipelineData.attributeHolder.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void set(IAttributeKey<T> key, T value) {
|
||||
pipelineData.attributeHolder.set(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMinecraftProtocol() {
|
||||
return pipelineData.minecraftProtocol;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEaglerPlayer() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerPendingConnection asEaglerPlayer() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHandshakeAuthEnabled() {
|
||||
return pipelineData.handshakeAuthEnabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getAuthUsername() {
|
||||
byte[] b = pipelineData.handshakeAuthUsername;
|
||||
return b != null ? b.clone() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEaglerXRewindPlayer() {
|
||||
return pipelineData.rewindProtocol != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRewindProtocolVersion() {
|
||||
return pipelineData.rewindProtocolVersion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEaglerVersionString() {
|
||||
return pipelineData.eaglerVersionString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEaglerBrandString() {
|
||||
return pipelineData.eaglerBrandString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHandshakeEaglerProtocol() {
|
||||
return pipelineData.handshakeProtocol;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GamePluginMessageProtocol getEaglerProtocol() {
|
||||
return pipelineData.gameProtocol;
|
||||
}
|
||||
|
||||
}
|
||||
+513
@@ -0,0 +1,513 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.net.SocketAddress;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformPlayer;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformSubLogger;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.EnumCapabilitySpec;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.EnumCapabilityType;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.EnumWebSocketHeader;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerListenerInfo;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerPlayer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IUpdateCertificate;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.SHA1Sum;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.rewind.IEaglerXRewindProtocol;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.collect.ObjectHashSet;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.message.MessageController;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.message.RewindMessageControllerHandle;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.notifications.NotificationManagerPlayer;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.pause_menu.PauseMenuManager;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.rpc.EaglerPlayerRPCManager;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.skins.SkinManagerEagler;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.supervisor.ISupervisorResolverImpl;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.supervisor.ISupervisorServiceImpl;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.update.IUpdateCertificateImpl;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.voice.IVoiceManagerImpl;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.webview.WebViewManager;
|
||||
import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageProtocol;
|
||||
import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket;
|
||||
import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherPlayerClientUUIDV4EAG;
|
||||
import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketRedirectClientV4EAG;
|
||||
import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketSetServerCookieV4EAG;
|
||||
import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUpdateCertEAG;
|
||||
|
||||
public class EaglerPlayerInstance<PlayerObject> extends BasePlayerInstance<PlayerObject>
|
||||
implements IEaglerPlayer<PlayerObject> {
|
||||
|
||||
private final Channel channel;
|
||||
private final IEaglerListenerInfo listenerInfo;
|
||||
private final String eaglerBrandString;
|
||||
private final String eaglerVersionString;
|
||||
private final boolean wss;
|
||||
private final String headerHost;
|
||||
private final String headerOrigin;
|
||||
private final String headerUserAgent;
|
||||
private final String headerCookie;
|
||||
private final String headerAuthorization;
|
||||
private final String requestPath;
|
||||
private final String realAddress;
|
||||
private final int handshakeProtocol;
|
||||
private final GamePluginMessageProtocol gameProtocol;
|
||||
private final int minecraftProtocol;
|
||||
private final boolean handshakeAuthEnabled;
|
||||
private final byte[] handshakeAuthUsername;
|
||||
private final boolean cookieSupport;
|
||||
private final boolean cookieEnabled;
|
||||
private byte[] cookieData;
|
||||
private final Object rewindAttachment;
|
||||
private final IEaglerXRewindProtocol<?, ?> rewindProtocol;
|
||||
private final int rewindProtocolVersion;
|
||||
private final RewindMessageControllerHandle rewindMessageControllerHandle;
|
||||
private final int acceptedCapabilitiesMask;
|
||||
private final byte[] acceptedCapabilitiesVers;
|
||||
private final Map<UUID, Byte> acceptedExtendedCapabilities;
|
||||
private final IPlatformSubLogger playerLogger;
|
||||
private final ObjectHashSet<SHA1Sum> updateSent;
|
||||
private final boolean redirectSupport;
|
||||
private final boolean updateSupport;
|
||||
private final PlayerRateLimits rateLimits;
|
||||
private final UUID eaglerBrandUUID;
|
||||
MessageController messageController;
|
||||
IVoiceManagerImpl<PlayerObject> voiceManager;
|
||||
NotificationManagerPlayer<PlayerObject> notifManager;
|
||||
WebViewManager<PlayerObject> webViewManager;
|
||||
PauseMenuManager<PlayerObject> pauseMenuManager;
|
||||
IUpdateCertificateImpl updateCertificate;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public EaglerPlayerInstance(IPlatformPlayer<PlayerObject> player, NettyPipelineData pipelineData, UUID brandUUID) {
|
||||
super(player, pipelineData.attributeHolder, (EaglerXServer<PlayerObject>) pipelineData.server);
|
||||
channel = pipelineData.channel;
|
||||
listenerInfo = pipelineData.listenerInfo;
|
||||
eaglerBrandString = pipelineData.eaglerBrandString.intern();
|
||||
eaglerVersionString = pipelineData.eaglerVersionString.intern();
|
||||
wss = pipelineData.wss;
|
||||
headerHost = pipelineData.headerHost != null ? pipelineData.headerHost.intern() : null;
|
||||
headerOrigin = pipelineData.headerOrigin != null ? pipelineData.headerOrigin.intern() : null;
|
||||
headerUserAgent = pipelineData.headerUserAgent != null ? pipelineData.headerUserAgent.intern() : null;
|
||||
headerCookie = pipelineData.headerCookie;
|
||||
headerAuthorization = pipelineData.headerAuthorization;
|
||||
requestPath = pipelineData.requestPath != null ? pipelineData.requestPath.intern() : null;
|
||||
realAddress = pipelineData.realAddress;
|
||||
handshakeProtocol = pipelineData.handshakeProtocol;
|
||||
gameProtocol = pipelineData.gameProtocol;
|
||||
minecraftProtocol = pipelineData.minecraftProtocol;
|
||||
handshakeAuthEnabled = pipelineData.handshakeAuthEnabled;
|
||||
handshakeAuthUsername = pipelineData.handshakeAuthUsername;
|
||||
cookieSupport = pipelineData.cookieSupport;
|
||||
cookieEnabled = pipelineData.cookieEnabled;
|
||||
cookieData = pipelineData.cookieData;
|
||||
rewindAttachment = pipelineData.rewindAttachment;
|
||||
rewindProtocol = pipelineData.rewindProtocol;
|
||||
rewindProtocolVersion = pipelineData.rewindProtocolVersion;
|
||||
rewindMessageControllerHandle = pipelineData.rewindMessageControllerHandle;
|
||||
acceptedCapabilitiesMask = pipelineData.acceptedCapabilitiesMask;
|
||||
acceptedCapabilitiesVers = pipelineData.acceptedCapabilitiesVers;
|
||||
acceptedExtendedCapabilities = pipelineData.acceptedExtendedCapabilities;
|
||||
playerLogger = pipelineData.connectionLogger;
|
||||
redirectSupport = hasCapability(EnumCapabilitySpec.REDIRECT_V0);
|
||||
updateSupport = hasCapability(EnumCapabilitySpec.UPDATE_V0);
|
||||
rateLimits = new PlayerRateLimits(server.rateLimitParams());
|
||||
eaglerBrandUUID = server.intern(brandUUID);
|
||||
if (updateSupport && server.getUpdateService() != null) {
|
||||
updateSent = new ObjectHashSet<>(16);
|
||||
} else {
|
||||
updateSent = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getSocketAddress() {
|
||||
return channel.remoteAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMinecraftProtocol() {
|
||||
return minecraftProtocol;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasCapability(EnumCapabilitySpec capability) {
|
||||
return CapabilityBits.hasCapability(acceptedCapabilitiesMask, acceptedCapabilitiesVers, capability.getId(),
|
||||
capability.getVer());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCapability(EnumCapabilityType capability) {
|
||||
return CapabilityBits.getCapability(acceptedCapabilitiesMask, acceptedCapabilitiesVers, capability.getId());
|
||||
}
|
||||
|
||||
public int getCapabilityMask() {
|
||||
return acceptedCapabilitiesMask;
|
||||
}
|
||||
|
||||
public byte[] getCapabilityVers() {
|
||||
return acceptedCapabilitiesVers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasExtendedCapability(UUID extendedCapability, int version) {
|
||||
if (extendedCapability == null) {
|
||||
throw new NullPointerException("extendedCapability");
|
||||
}
|
||||
Byte b = acceptedExtendedCapabilities.get(extendedCapability);
|
||||
return b != null && (b.byteValue() & 0xFF) >= version;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getExtendedCapability(UUID extendedCapability) {
|
||||
if (extendedCapability == null) {
|
||||
throw new NullPointerException("extendedCapability");
|
||||
}
|
||||
Byte b = acceptedExtendedCapabilities.get(extendedCapability);
|
||||
return b != null ? (b.byteValue() & 0xFF) : -1;
|
||||
}
|
||||
|
||||
public Map<UUID, Byte> getExtCapabilities() {
|
||||
return acceptedExtendedCapabilities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHandshakeAuthEnabled() {
|
||||
return handshakeAuthEnabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getAuthUsername() {
|
||||
return handshakeAuthUsername != null ? handshakeAuthUsername.clone() : null;
|
||||
}
|
||||
|
||||
public byte[] getAuthUsernameUnsafe() {
|
||||
return handshakeAuthUsername;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerListenerInfo getListenerInfo() {
|
||||
return listenerInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRealAddress() {
|
||||
return realAddress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isWebSocketSecure() {
|
||||
return wss;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEaglerXRewindPlayer() {
|
||||
return rewindProtocol != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRewindProtocolVersion() {
|
||||
return rewindProtocolVersion;
|
||||
}
|
||||
|
||||
public IEaglerXRewindProtocol<?, ?> getRewindProtocol() {
|
||||
return rewindProtocol;
|
||||
}
|
||||
|
||||
public Object getRewindAttachment() {
|
||||
return rewindAttachment;
|
||||
}
|
||||
|
||||
public RewindMessageControllerHandle getRewindMessageControllerHandle() {
|
||||
return rewindMessageControllerHandle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getWebSocketHeader(EnumWebSocketHeader header) {
|
||||
if (header == null) {
|
||||
throw new NullPointerException("header");
|
||||
}
|
||||
return switch (header) {
|
||||
case HEADER_HOST -> headerHost;
|
||||
case HEADER_ORIGIN -> headerOrigin;
|
||||
case HEADER_USER_AGENT -> headerUserAgent;
|
||||
case HEADER_COOKIE -> headerCookie;
|
||||
case HEADER_AUTHORIZATION -> headerAuthorization;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getWebSocketPath() {
|
||||
return requestPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEaglerVersionString() {
|
||||
return eaglerVersionString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getEaglerBrandString() {
|
||||
return eaglerBrandString;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID getEaglerBrandUUID() {
|
||||
return eaglerBrandUUID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getHandshakeEaglerProtocol() {
|
||||
return handshakeProtocol;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GamePluginMessageProtocol getEaglerProtocol() {
|
||||
return gameProtocol;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEaglerPlayer() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EaglerPlayerInstance<PlayerObject> asEaglerPlayer() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendEaglerMessage(GameMessagePacket packet) {
|
||||
if (packet == null) {
|
||||
throw new NullPointerException("packet");
|
||||
}
|
||||
messageController.sendPacket(packet);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SkinManagerEagler<PlayerObject> getSkinManager() {
|
||||
return (SkinManagerEagler<PlayerObject>) skinManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRedirectPlayerSupported() {
|
||||
return redirectSupport;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void redirectPlayerToWebSocket(String webSocketURI) {
|
||||
if (webSocketURI == null) {
|
||||
throw new NullPointerException("webSocketURI");
|
||||
}
|
||||
if (redirectSupport) {
|
||||
sendEaglerMessage(new SPacketRedirectClientV4EAG(webSocketURI));
|
||||
} else {
|
||||
playerLogger.warn("Attempted to redirect player on an unsupported client");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVoiceCapable() {
|
||||
return hasCapability(EnumCapabilitySpec.VOICE_V0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasVoiceManager() {
|
||||
return voiceManager != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IVoiceManagerImpl<PlayerObject> getVoiceManager() {
|
||||
return voiceManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCookieSupported() {
|
||||
return cookieSupport;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCookieEnabled() {
|
||||
return cookieEnabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getCookieData() {
|
||||
return cookieData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCookieData(byte[] data, long expiresAfterSec, boolean revokeQuerySupported,
|
||||
boolean clientSaveCookieToDisk) {
|
||||
if (cookieEnabled) {
|
||||
cookieData = data;
|
||||
sendEaglerMessage(new SPacketSetServerCookieV4EAG(data, expiresAfterSec, revokeQuerySupported,
|
||||
clientSaveCookieToDisk));
|
||||
} else {
|
||||
playerLogger.warn("Attempted to set cookie while cookies are disabled");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isNotificationSupported() {
|
||||
return notifManager != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NotificationManagerPlayer<PlayerObject> getNotificationManager() {
|
||||
return notifManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPauseMenuSupported() {
|
||||
return pauseMenuManager != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PauseMenuManager<PlayerObject> getPauseMenuManager() {
|
||||
return pauseMenuManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isWebViewSupported() {
|
||||
return webViewManager != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebViewManager<PlayerObject> getWebViewManager() {
|
||||
return webViewManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUpdateSystemSupported() {
|
||||
return updateSupport;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IUpdateCertificateImpl getUpdateCertificate() {
|
||||
return updateCertificate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void offerUpdateCertificate(IUpdateCertificate cert) {
|
||||
if (!(cert instanceof IUpdateCertificateImpl impl)) {
|
||||
throw new UnsupportedOperationException("Unknown certificate: " + cert);
|
||||
}
|
||||
if (updateSent == null) {
|
||||
return;
|
||||
}
|
||||
if (impl == updateCertificate) {
|
||||
return;
|
||||
}
|
||||
SHA1Sum csum = impl.checkSum();
|
||||
boolean send;
|
||||
synchronized (updateSent) {
|
||||
send = updateSent.add(csum);
|
||||
if (send) {
|
||||
int s = updateSent.size();
|
||||
if (s > 256) {
|
||||
removeRandomCertToken();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (send) {
|
||||
SPacketUpdateCertEAG pkt = impl.packet();
|
||||
server.getUpdateService().getLoop()
|
||||
.pushRunnable(getEaglerProtocol() != GamePluginMessageProtocol.V4 ? () -> {
|
||||
sendEaglerMessage(pkt);
|
||||
return pkt.length();
|
||||
} : () -> {
|
||||
// v4 clients don't like receiving these in a multi-packet
|
||||
messageController.sendPacketImmediately(pkt);
|
||||
return pkt.length();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendUpdateCertificate(IUpdateCertificate cert) {
|
||||
if (!(cert instanceof IUpdateCertificateImpl c2)) {
|
||||
throw new UnsupportedOperationException("Unknown certificate: " + cert);
|
||||
}
|
||||
if (updateSupport) {
|
||||
if (getEaglerProtocol() != GamePluginMessageProtocol.V4) {
|
||||
sendEaglerMessage(c2.packet());
|
||||
} else {
|
||||
// v4 clients don't like receiving these in a multi-packet
|
||||
messageController.sendPacketImmediately(c2.packet());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void removeRandomCertToken() {
|
||||
// HPPC iteration order is randomized
|
||||
updateSent.indexRemove(updateSent.iterator().next().index);
|
||||
}
|
||||
|
||||
public IPlatformSubLogger logger() {
|
||||
return playerLogger;
|
||||
}
|
||||
|
||||
public PlayerRateLimits getRateLimits() {
|
||||
return rateLimits;
|
||||
}
|
||||
|
||||
public MessageController getMessageController() {
|
||||
return messageController;
|
||||
}
|
||||
|
||||
public void handlePacketGetOtherClientUUID(long playerUUIDMost, long playerUUIDLeast, int requestId) {
|
||||
if (!rateLimits.ratelimitBrand()) {
|
||||
return;
|
||||
}
|
||||
UUID uuid = new UUID(playerUUIDMost, playerUUIDLeast);
|
||||
BasePlayerInstance<PlayerObject> player = server.getPlayerByUUID(uuid);
|
||||
if (player != null) {
|
||||
UUID brandUUID = player.getEaglerBrandUUID();
|
||||
sendEaglerMessage(new SPacketOtherPlayerClientUUIDV4EAG(requestId, brandUUID.getMostSignificantBits(),
|
||||
brandUUID.getLeastSignificantBits()));
|
||||
} else {
|
||||
ISupervisorServiceImpl<PlayerObject> supervisorService = server.getSupervisorService();
|
||||
if (supervisorService.isSupervisorEnabled() && !supervisorService.shouldIgnoreUUID(uuid)) {
|
||||
if (!rateLimits.checkSvBrandAntagonist()) {
|
||||
return;
|
||||
}
|
||||
supervisorService.getRemoteOnlyResolver().resolvePlayerBrandKeyed(getUniqueId(), uuid, (res) -> {
|
||||
if (res != ISupervisorResolverImpl.UNAVAILABLE) {
|
||||
if (res != null) {
|
||||
sendEaglerMessage(new SPacketOtherPlayerClientUUIDV4EAG(requestId,
|
||||
res.getMostSignificantBits(), res.getLeastSignificantBits()));
|
||||
} else {
|
||||
rateLimits.ratelimitSvBrandAntagonist();
|
||||
sendEaglerMessage(new SPacketOtherPlayerClientUUIDV4EAG(requestId, 0l, 0l));
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
sendEaglerMessage(new SPacketOtherPlayerClientUUIDV4EAG(requestId, 0l, 0l));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public EaglerPlayerRPCManager<PlayerObject> getPlayerRPCManager() {
|
||||
return (EaglerPlayerRPCManager<PlayerObject>) backendRPCManager;
|
||||
}
|
||||
|
||||
}
|
||||
+1253
File diff suppressed because it is too large
Load Diff
+41
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IEaglerXServerJoinListener;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformPlayer;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformServer;
|
||||
|
||||
class EaglerXServerJoinListener<PlayerObject> implements IEaglerXServerJoinListener<PlayerObject> {
|
||||
|
||||
private final EaglerXServer<PlayerObject> server;
|
||||
|
||||
EaglerXServerJoinListener(EaglerXServer<PlayerObject> server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handlePreConnect(IPlatformPlayer<PlayerObject> player) {
|
||||
server.handleServerPreConnect(player.<BasePlayerInstance<PlayerObject>>getPlayerAttachment());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handlePostConnect(IPlatformPlayer<PlayerObject> player, IPlatformServer<PlayerObject> serverIn) {
|
||||
server.handleServerPostConnect(player.<BasePlayerInstance<PlayerObject>>getPlayerAttachment(), serverIn);
|
||||
}
|
||||
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IEaglerXServerLoginInitializer;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformLoginInitializer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.EnumPlatformType;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.skins.TexturesProperty;
|
||||
|
||||
class EaglerXServerLoginInitializer<PlayerObject>
|
||||
implements IEaglerXServerLoginInitializer<NettyPipelineData> {
|
||||
|
||||
private final EaglerXServer<PlayerObject> server;
|
||||
|
||||
EaglerXServerLoginInitializer(EaglerXServer<PlayerObject> server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initializeLogin(IPlatformLoginInitializer<NettyPipelineData> initializer) {
|
||||
NettyPipelineData nettyData = initializer.getPipelineAttachment();
|
||||
if (nettyData != null) {
|
||||
if (nettyData.isEaglerPlayer()) {
|
||||
if (server.isEaglerPlayerPropertyEnabled()) {
|
||||
initializer.setEaglerPlayerProperty(true);
|
||||
}
|
||||
TexturesProperty eaglerPlayersSkin = server.getEaglerPlayersVanillaSkin();
|
||||
if (eaglerPlayersSkin != null) {
|
||||
initializer.setTexturesProperty(eaglerPlayersSkin.getValue(), eaglerPlayersSkin.getSignature());
|
||||
}
|
||||
if (server.getPlatformType() != EnumPlatformType.BUKKIT) {
|
||||
initializer.setUniqueId(nettyData.uuid);
|
||||
}
|
||||
} else {
|
||||
if (server.isEaglerPlayerPropertyEnabled()) {
|
||||
initializer.setEaglerPlayerProperty(false);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (server.isEaglerPlayerPropertyEnabled()) {
|
||||
initializer.setEaglerPlayerProperty(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IEaglerXServerNettyPipelineInitializer;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformNettyPipelineInitializer;
|
||||
|
||||
class EaglerXServerNettyPipelineInitializer<PlayerObject>
|
||||
implements IEaglerXServerNettyPipelineInitializer<NettyPipelineData> {
|
||||
|
||||
private final EaglerXServer<PlayerObject> server;
|
||||
|
||||
EaglerXServerNettyPipelineInitializer(EaglerXServer<PlayerObject> server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize(IPlatformNettyPipelineInitializer<NettyPipelineData> initializer) {
|
||||
EaglerListener eagListener = (EaglerListener) initializer.getListener();
|
||||
if (server.getConfig().getSettings().isDebugLogNewChannels()) {
|
||||
server.logger().info("[" + eagListener.getName() + "]: New channel opened: " + initializer.getChannel());
|
||||
}
|
||||
Consumer<SocketAddress> realAddressHandle = null;
|
||||
CompoundRateLimiterMap.ICompoundRatelimits rateLimits = null;
|
||||
if (eagListener.isForwardIP()) {
|
||||
if (eagListener.getConfigData().isSpoofPlayerAddressForwarded()) {
|
||||
realAddressHandle = initializer.realAddressHandle();
|
||||
}
|
||||
} else {
|
||||
CompoundRateLimiterMap map = eagListener.getRateLimiter();
|
||||
if (map != null) {
|
||||
SocketAddress addr = initializer.getChannel().remoteAddress();
|
||||
if (addr instanceof InetSocketAddress inetAddr) {
|
||||
rateLimits = map.rateLimit(inetAddr.getAddress());
|
||||
if (rateLimits == null) {
|
||||
initializer.getChannel().close();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
server.logger().warn("Unable to ratelimit unknown address type: " + addr.getClass().getName()
|
||||
+ " - \"" + addr + "\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
NettyPipelineData attachment = new NettyPipelineData(initializer.getChannel(), server, eagListener,
|
||||
server.getEaglerAttribManager().createEaglerHolder(), realAddressHandle, rateLimits);
|
||||
initializer.setAttachment(attachment);
|
||||
if (eagListener.isDualStack()) {
|
||||
server.getPipelineTransformer().injectDualStack(initializer.getPipeline(), initializer.getChannel(),
|
||||
attachment);
|
||||
} else {
|
||||
server.getPipelineTransformer().injectSingleStack(initializer.getPipeline(), initializer.getChannel(),
|
||||
attachment);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IEaglerXServerPlayerInitializer;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformPlayer;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformPlayerInitializer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.brand.IBrandRegistry;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.supervisor.EnumAcceptPlayer;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.supervisor.ISupervisorServiceImpl;
|
||||
|
||||
class EaglerXServerPlayerInitializer<PlayerObject> implements
|
||||
IEaglerXServerPlayerInitializer<NettyPipelineData, BasePlayerInstance<PlayerObject>, PlayerObject> {
|
||||
|
||||
private final EaglerXServer<PlayerObject> server;
|
||||
|
||||
EaglerXServerPlayerInitializer(EaglerXServer<PlayerObject> server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initializePlayer(
|
||||
IPlatformPlayerInitializer<NettyPipelineData, BasePlayerInstance<PlayerObject>, PlayerObject> initializer) {
|
||||
NettyPipelineData pipelineData = initializer.getPipelineAttachment();
|
||||
NettyPipelineData.ProfileDataHolder profileData;
|
||||
if (pipelineData == null || !pipelineData.isEaglerPlayer()) {
|
||||
pipelineData = null;
|
||||
profileData = null;
|
||||
} else {
|
||||
profileData = pipelineData.profileDataHelper();
|
||||
}
|
||||
IPlatformPlayer<PlayerObject> platformPlayer = initializer.getPlayer();
|
||||
ISupervisorServiceImpl<PlayerObject> supervisor = server.getSupervisorService();
|
||||
if (supervisor.isSupervisorEnabled()) {
|
||||
supervisor.acceptPlayer(platformPlayer.getUniqueId(),
|
||||
pipelineData != null ? profileData.brandUUID : IBrandRegistry.BRAND_VANILLA,
|
||||
pipelineData != null ? pipelineData.minecraftProtocol
|
||||
: initializer.getPlayer().getMinecraftProtocol(),
|
||||
pipelineData != null ? pipelineData.handshakeProtocol : 0, platformPlayer.getUsername(), (res) -> {
|
||||
if (res == EnumAcceptPlayer.ACCEPT) {
|
||||
server.getPlatform().getScheduler().executeAsync(() -> {
|
||||
acceptPlayer(initializer, profileData);
|
||||
});
|
||||
} else {
|
||||
switch (res) {
|
||||
case REJECT_ALREADY_WAITING:
|
||||
case REJECT_DUPLICATE_USERNAME:
|
||||
case REJECT_DUPLICATE_UUID:
|
||||
try {
|
||||
platformPlayer.disconnect(server.componentHelper().getStandardKickAlreadyPlaying());
|
||||
} finally {
|
||||
initializer.cancel();
|
||||
}
|
||||
break;
|
||||
case REJECT_UNKNOWN:
|
||||
default:
|
||||
try {
|
||||
platformPlayer.disconnect(server.componentBuilder().buildTextComponent()
|
||||
.text("Internal Supervisor Error").end());
|
||||
} finally {
|
||||
initializer.cancel();
|
||||
}
|
||||
break;
|
||||
case SUPERVISOR_UNAVAILABLE:
|
||||
try {
|
||||
platformPlayer.disconnect(server.componentBuilder().buildTextComponent()
|
||||
.text(server.getConfig().getSupervisor().getSupervisorUnavailableMessage())
|
||||
.end());
|
||||
} finally {
|
||||
initializer.cancel();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
acceptPlayer(initializer, profileData);
|
||||
}
|
||||
}
|
||||
|
||||
private void acceptPlayer(
|
||||
IPlatformPlayerInitializer<NettyPipelineData, BasePlayerInstance<PlayerObject>, PlayerObject> initializer,
|
||||
NettyPipelineData.ProfileDataHolder profileData) {
|
||||
NettyPipelineData conn = initializer.getPipelineAttachment();
|
||||
if (conn != null && conn.isEaglerPlayer()) {
|
||||
EaglerPlayerInstance<PlayerObject> instance = new EaglerPlayerInstance<>(initializer.getPlayer(), conn,
|
||||
profileData.brandUUID);
|
||||
initializer.setPlayerAttachment(instance);
|
||||
try {
|
||||
server.registerEaglerPlayer(instance, profileData, () -> {
|
||||
initializer.complete();
|
||||
server.eventDispatcher().dispatchInitializePlayerEvent(instance, profileData.extraData, null);
|
||||
});
|
||||
} catch (EaglerXServer.RegistrationStateException ex) {
|
||||
try {
|
||||
server.getSupervisorService().dropOwnPlayer(initializer.getPlayer().getUniqueId());
|
||||
} finally {
|
||||
initializer.cancel();
|
||||
}
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
BasePlayerInstance<PlayerObject> instance = new BasePlayerInstance<>(initializer.getPlayer(),
|
||||
conn != null ? conn.attributeHolder : server.getEaglerAttribManager().createEaglerHolder(), server);
|
||||
initializer.setPlayerAttachment(instance);
|
||||
try {
|
||||
server.registerPlayer(instance);
|
||||
} catch (EaglerXServer.RegistrationStateException ex) {
|
||||
try {
|
||||
server.getSupervisorService().dropOwnPlayer(instance.getUniqueId());
|
||||
} finally {
|
||||
initializer.cancel();
|
||||
}
|
||||
return;
|
||||
}
|
||||
initializer.complete();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroyPlayer(IPlatformPlayer<PlayerObject> player) {
|
||||
BasePlayerInstance<PlayerObject> instance = player.getPlayerAttachment();
|
||||
if (instance != null) {
|
||||
try {
|
||||
if (instance.isEaglerPlayer()) {
|
||||
EaglerPlayerInstance<PlayerObject> eaglerInstance = (EaglerPlayerInstance<PlayerObject>) instance;
|
||||
try {
|
||||
server.unregisterEaglerPlayer(eaglerInstance);
|
||||
} catch (EaglerXServer.RegistrationStateException ex) {
|
||||
return;
|
||||
}
|
||||
server.eventDispatcher().dispatchDestroyPlayerEvent(eaglerInstance, null);
|
||||
} else {
|
||||
try {
|
||||
server.unregisterPlayer(instance);
|
||||
} catch (EaglerXServer.RegistrationStateException ex) {
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
server.getSupervisorService().dropOwnPlayer(player.getUniqueId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.util.SemanticVersion;
|
||||
|
||||
public class EaglerXServerVersion {
|
||||
|
||||
public static final String BRAND = "EaglercraftXServer";
|
||||
public static final String AUTHOR = "lax1dude";
|
||||
public static final String VERSION = "1.1.1";
|
||||
|
||||
public static final SemanticVersion UPDATE_VERSION = SemanticVersion.parse(VERSION);
|
||||
|
||||
public static final String UPDATE_CHECK = "https://lax1dude.net/eaglerxserver/version.txt";
|
||||
public static final String UPDATE_LINK = "https://lax1dude.net/eaglerxserver/";
|
||||
public static final String UPDATE_LINE = "-----------------------------------";
|
||||
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.ExtendedCapabilitySpec;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.ObjectIntMap;
|
||||
|
||||
public class ExtCapabilityMap {
|
||||
|
||||
private final ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
private final Map<Object, Set<ExtendedCapabilitySpec>> pluginCapabilities = new IdentityHashMap<>();
|
||||
|
||||
private ExtendedCapabilitySpec internUUIDs(ExtendedCapabilitySpec spec) { // TODO: sort the versions so they can be
|
||||
// matched faster
|
||||
ExtendedCapabilitySpec.Version[] vers = spec.getMajorVersions().clone();
|
||||
for (int i = 0; i < vers.length; ++i) {
|
||||
vers[i] = ExtendedCapabilitySpec.version(EaglerXServer.uuidInterner.intern(vers[i].getMajorVersion()),
|
||||
vers[i].getMinorVersions());
|
||||
}
|
||||
return ExtendedCapabilitySpec.create(vers);
|
||||
}
|
||||
|
||||
public void registerCapability(Object plugin, ExtendedCapabilitySpec capability) {
|
||||
capability = internUUIDs(capability);
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
Set<ExtendedCapabilitySpec> caps = pluginCapabilities.get(plugin);
|
||||
if (caps == null) {
|
||||
pluginCapabilities.put(capability, caps = new HashSet<>());
|
||||
}
|
||||
caps.add(capability);
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void unregisterCapability(Object plugin, ExtendedCapabilitySpec capability) {
|
||||
lock.writeLock().lock();
|
||||
try {
|
||||
Set<ExtendedCapabilitySpec> caps = pluginCapabilities.get(plugin);
|
||||
if (caps != null) {
|
||||
if (caps.remove(capability)) {
|
||||
if (caps.isEmpty()) {
|
||||
pluginCapabilities.remove(plugin);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
lock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public Map<UUID, Byte> acceptExtendedCapabilities(ObjectIntMap<UUID> extCapabilities) {
|
||||
Map<UUID, Byte> builder;
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
Collection<Set<ExtendedCapabilitySpec>> vals = pluginCapabilities.values();
|
||||
if (vals.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
builder = new HashMap<>(extCapabilities.size());
|
||||
for (Set<ExtendedCapabilitySpec> specs : vals) {
|
||||
for (ExtendedCapabilitySpec spec : specs) {
|
||||
ExtendedCapabilitySpec.Version[] vers = spec.getMajorVersions();
|
||||
eagler: for (int j = vers.length - 1; j >= 0; --j) {
|
||||
ExtendedCapabilitySpec.Version ver = vers[j];
|
||||
int bitFieldIndex = extCapabilities.indexOf(ver.getMajorVersion());
|
||||
if (bitFieldIndex >= 0) {
|
||||
int bits = extCapabilities.indexGet(bitFieldIndex);
|
||||
int maxVer = -1;
|
||||
for (int i : ver.getMinorVersions()) {
|
||||
if (i > maxVer && (bits & (1 << i)) != 0) {
|
||||
maxVer = i;
|
||||
}
|
||||
}
|
||||
if (maxVer != -1) {
|
||||
Byte b = builder.get(ver.getMajorVersion());
|
||||
if (b != null) {
|
||||
if ((b.byteValue() & 0xFF) < maxVer) {
|
||||
builder.put(ver.getMajorVersion(), (byte) maxVer);
|
||||
}
|
||||
} else {
|
||||
builder.put(ver.getMajorVersion(), (byte) maxVer);
|
||||
}
|
||||
break eagler;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
return ImmutableMap.copyOf(builder);
|
||||
}
|
||||
|
||||
public boolean isCapabilityRegistered(UUID capabilityUUID, int version) {
|
||||
lock.readLock().lock();
|
||||
try {
|
||||
Collection<Set<ExtendedCapabilitySpec>> vals = pluginCapabilities.values();
|
||||
if (vals.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (Set<ExtendedCapabilitySpec> specs : vals) {
|
||||
for (ExtendedCapabilitySpec spec : specs) {
|
||||
ExtendedCapabilitySpec.Version[] vers = spec.getMajorVersions();
|
||||
for (int i = 0; i < vers.length; ++i) {
|
||||
ExtendedCapabilitySpec.Version ver = vers[i];
|
||||
if (capabilityUUID.equals(ver.getMajorVersion())) {
|
||||
int[] minorVerss = ver.getMinorVersions();
|
||||
for (int j = 0, l = minorVerss.length; j < l; ++j) {
|
||||
if ((minorVerss[j] & 0xFF) > version) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
public interface IIdentifiedConnection {
|
||||
|
||||
Object getIdentityToken();
|
||||
|
||||
public abstract class Base implements IIdentifiedConnection {
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return System.identityHashCode(getIdentityToken());
|
||||
}
|
||||
|
||||
public boolean equals(Object o) {
|
||||
return this == o
|
||||
|| ((o instanceof IIdentifiedConnection o2) && getIdentityToken() == o2.getIdentityToken());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import io.netty.buffer.ByteBufAllocator;
|
||||
import io.netty.handler.ssl.SslHandler;
|
||||
|
||||
public interface ISSLContextProvider {
|
||||
|
||||
SslHandler newHandler(ByteBufAllocator alloc);
|
||||
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.ByteBufOutputStream;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformScheduler;
|
||||
import net.lax1dude.eaglercraft.backend.skin_cache.IHTTPClient;
|
||||
|
||||
public class LegacyInternalHTTPClient implements IHTTPClient {
|
||||
|
||||
private final IPlatformScheduler scheduler;
|
||||
private final String userAgent;
|
||||
|
||||
public LegacyInternalHTTPClient(IPlatformScheduler scheduler, String userAgent) {
|
||||
this.scheduler = scheduler;
|
||||
this.userAgent = userAgent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void asyncRequest(String method, URI uri, Consumer<Response> responseCallback) {
|
||||
String scheme = uri.getScheme();
|
||||
if (!scheme.equals("http") && !scheme.equals("https")) {
|
||||
responseCallback.accept(new Response(new UnsupportedOperationException("Unsupported scheme: " + scheme)));
|
||||
return;
|
||||
}
|
||||
URL url;
|
||||
try {
|
||||
url = uri.toURL();
|
||||
} catch (MalformedURLException ex) {
|
||||
responseCallback.accept(new Response(ex));
|
||||
return;
|
||||
}
|
||||
scheduler.executeAsync(() -> {
|
||||
Response res;
|
||||
try {
|
||||
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
||||
conn.addRequestProperty("user-agent", userAgent);
|
||||
conn.connect();
|
||||
ByteBuf buf = Unpooled.buffer(1024);
|
||||
try {
|
||||
try (InputStream is = conn.getInputStream()) {
|
||||
is.transferTo(new ByteBufOutputStream(buf));
|
||||
}
|
||||
int responseCode = conn.getResponseCode();
|
||||
res = new Response(responseCode, false, buf.retain());
|
||||
} finally {
|
||||
buf.release();
|
||||
conn.disconnect();
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
responseCallback.accept(new Response(ex));
|
||||
return;
|
||||
}
|
||||
responseCallback.accept(res);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IEaglerXServerMessageChannel;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IEaglerXServerMessageHandler;
|
||||
|
||||
public class MessageChannel<PlayerObject> implements IEaglerXServerMessageChannel<PlayerObject> {
|
||||
|
||||
private final String legacyName;
|
||||
private final String modernName;
|
||||
private final IEaglerXServerMessageHandler<PlayerObject> handler;
|
||||
|
||||
public MessageChannel(String legacyName, String modernName, IEaglerXServerMessageHandler<PlayerObject> handler) {
|
||||
this.legacyName = legacyName;
|
||||
this.modernName = modernName;
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getLegacyName() {
|
||||
return legacyName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getModernName() {
|
||||
return modernName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerXServerMessageHandler<PlayerObject> getHandler() {
|
||||
return handler;
|
||||
}
|
||||
|
||||
}
|
||||
+439
@@ -0,0 +1,439 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.SocketAddress;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.net.InetAddresses;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelFutureListener;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.handler.timeout.IdleStateHandler;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPipelineData;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformSubLogger;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformTask;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.EnumCapabilityType;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.EnumWebSocketHeader;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerConnection;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerListenerInfo;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerLoginConnection;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerPendingConnection;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.INettyChannel;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.attribute.IAttributeKey;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.rewind.IEaglerXRewindProtocol;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.message.RewindMessageControllerHandle;
|
||||
import net.lax1dude.eaglercraft.backend.server.util.EnumRateLimitState;
|
||||
import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageProtocol;
|
||||
|
||||
public class NettyPipelineData extends IIdentifiedConnection.Base
|
||||
implements IEaglerConnection, INettyChannel.NettyUnsafe, IPipelineData {
|
||||
|
||||
private static final VarHandle PLAY_STATE_REACHED_HANDLE;
|
||||
|
||||
static {
|
||||
try {
|
||||
MethodHandles.Lookup l = MethodHandles.lookup();
|
||||
PLAY_STATE_REACHED_HANDLE = l.findVarHandle(NettyPipelineData.class, "playStateReached", Runnable.class);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new ExceptionInInitializerError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ProfileDataHolder {
|
||||
|
||||
public final byte[] skinDataV1Init;
|
||||
public final byte[] skinDataV2Init;
|
||||
public final byte[] capeDataInit;
|
||||
public final byte[] updateCertInit;
|
||||
public final UUID brandUUID;
|
||||
public final Map<String, byte[]> extraData;
|
||||
|
||||
protected ProfileDataHolder(byte[] skinDataV1Init, byte[] skinDataV2Init, byte[] capeDataInit,
|
||||
byte[] updateCertInit, UUID brandUUID, Map<String, byte[]> extraData) {
|
||||
this.skinDataV1Init = skinDataV1Init;
|
||||
this.skinDataV2Init = skinDataV2Init;
|
||||
this.capeDataInit = capeDataInit;
|
||||
this.updateCertInit = updateCertInit;
|
||||
this.brandUUID = brandUUID;
|
||||
this.extraData = extraData;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final Set<String> profileDataStandard = ImmutableSet.of("skin_v1", "skin_v2", "cape_v1",
|
||||
"update_cert_v1", "brand_uuid_v1");
|
||||
|
||||
public final Channel channel;
|
||||
public final EaglerXServer<?> server;
|
||||
public final EaglerAttributeManager.EaglerAttributeHolder attributeHolder;
|
||||
public final Consumer<SocketAddress> realAddressHandle;
|
||||
public SocketAddress realSocketAddressInstance;
|
||||
public CompoundRateLimiterMap.ICompoundRatelimits rateLimits;
|
||||
public IdleStateHandler idleStateHandler;
|
||||
public boolean initStall;
|
||||
|
||||
public EaglerListener listenerInfo;
|
||||
public String eaglerBrandString;
|
||||
public String eaglerVersionString;
|
||||
|
||||
public boolean wss;
|
||||
public String headerHost;
|
||||
public String headerOrigin;
|
||||
public String headerUserAgent;
|
||||
public String headerCookie;
|
||||
public String headerAuthorization;
|
||||
public String requestPath;
|
||||
public String realAddress;
|
||||
public InetAddress realInetAddress;
|
||||
|
||||
public int handshakeProtocol;
|
||||
public GamePluginMessageProtocol gameProtocol;
|
||||
public int minecraftProtocol;
|
||||
public boolean handshakeAuthEnabled;
|
||||
public byte[] handshakeAuthUsername;
|
||||
|
||||
public String username;
|
||||
public UUID uuid;
|
||||
public String requestedServer;
|
||||
public boolean authEventEnabled;
|
||||
public byte authType;
|
||||
public String authMessage;
|
||||
public boolean nicknameSelectionEnabled;
|
||||
public byte[] authSalt;
|
||||
public boolean cookieSupport;
|
||||
public boolean cookieEnabled;
|
||||
public boolean cookieAuthEventEnabled;
|
||||
public byte[] cookieData;
|
||||
public Map<String, byte[]> profileDatas;
|
||||
public int acceptedCapabilitiesMask;
|
||||
public byte[] acceptedCapabilitiesVers;
|
||||
public Map<UUID, Byte> acceptedExtendedCapabilities;
|
||||
|
||||
public IPlatformSubLogger connectionLogger;
|
||||
|
||||
public Object rewindAttachment;
|
||||
public IEaglerXRewindProtocol<?, ?> rewindProtocol;
|
||||
public int rewindProtocolVersion = -1;
|
||||
public RewindMessageControllerHandle rewindMessageControllerHandle;
|
||||
|
||||
public EaglerPendingStateAdapter pendingConnection;
|
||||
public EaglerLoginStateAdapter loginConnection;
|
||||
|
||||
private IPlatformTask disconnectTask = null;
|
||||
|
||||
private static final Runnable REACHED = () -> {
|
||||
};
|
||||
|
||||
private Runnable playStateReached = null;
|
||||
|
||||
public NettyPipelineData(Channel channel, EaglerXServer<?> server, EaglerListener listenerInfo,
|
||||
EaglerAttributeManager.EaglerAttributeHolder attributeHolder, Consumer<SocketAddress> realAddressHandle,
|
||||
CompoundRateLimiterMap.ICompoundRatelimits rateLimits) {
|
||||
this.channel = channel;
|
||||
this.server = server;
|
||||
this.listenerInfo = listenerInfo;
|
||||
this.attributeHolder = attributeHolder;
|
||||
this.realAddressHandle = realAddressHandle;
|
||||
this.connectionLogger = server.logger().createSubLogger("" + channel.remoteAddress());
|
||||
this.rateLimits = rateLimits;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getSocketAddress() {
|
||||
return channel.remoteAddress();
|
||||
}
|
||||
|
||||
public SocketAddress getPlayerAddress() {
|
||||
return realSocketAddressInstance != null ? realSocketAddressInstance : channel.remoteAddress();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRealAddress() {
|
||||
return realAddress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEaglerPlayer() {
|
||||
return listenerInfo != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCompressionDisable() {
|
||||
return listenerInfo != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConnected() {
|
||||
return channel.isActive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnect() {
|
||||
channel.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getIdentityToken() {
|
||||
return attributeHolder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T get(IAttributeKey<T> key) {
|
||||
return attributeHolder.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> void set(IAttributeKey<T> key, T value) {
|
||||
attributeHolder.set(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerListenerInfo getListenerInfo() {
|
||||
return listenerInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isWebSocketSecure() {
|
||||
return wss;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getWebSocketHeader(EnumWebSocketHeader header) {
|
||||
if (header == null) {
|
||||
throw new NullPointerException("header");
|
||||
}
|
||||
return switch (header) {
|
||||
case HEADER_HOST -> headerHost;
|
||||
case HEADER_ORIGIN -> headerOrigin;
|
||||
case HEADER_USER_AGENT -> headerUserAgent;
|
||||
case HEADER_COOKIE -> headerCookie;
|
||||
case HEADER_AUTHORIZATION -> headerAuthorization;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getWebSocketPath() {
|
||||
return requestPath;
|
||||
}
|
||||
|
||||
public void scheduleLoginTimeoutHelper() {
|
||||
if (disconnectTask == null) {
|
||||
synchronized (this) {
|
||||
if (disconnectTask != null) {
|
||||
return;
|
||||
}
|
||||
disconnectTask = server.getPlatform().getScheduler().executeAsyncDelayedTask(() -> {
|
||||
channel.close();
|
||||
}, server.getConfig().getSettings().getEaglerLoginTimeout());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void cancelLoginTimeoutHelper() {
|
||||
if (disconnectTask != null) {
|
||||
IPlatformTask task;
|
||||
synchronized (this) {
|
||||
task = disconnectTask;
|
||||
if (task == null) {
|
||||
return;
|
||||
}
|
||||
disconnectTask = null;
|
||||
}
|
||||
task.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
public ProfileDataHolder profileDataHelper() {
|
||||
if (profileDatas != null) {
|
||||
byte[] skinV2 = profileDatas.get("skin_v2");
|
||||
byte[] skinV1 = skinV2 == null ? profileDatas.get("skin_v1") : null;
|
||||
byte[] cape = profileDatas.get("cape_v1");
|
||||
byte[] updateCert = profileDatas.get("update_cert_v1");
|
||||
byte[] uuid = profileDatas.get("brand_uuid_v1");
|
||||
UUID brandUUID = null;
|
||||
if (uuid != null && uuid.length == 16) {
|
||||
ByteBuf buf = Unpooled.wrappedBuffer(uuid);
|
||||
UUID ret = new UUID(buf.readLong(), buf.readLong());
|
||||
if (server.getBrandService().sanitizeUUID(ret)) {
|
||||
brandUUID = ret;
|
||||
}
|
||||
}
|
||||
if (brandUUID == null) {
|
||||
brandUUID = server.getBrandService().getBrandUUIDClientLegacy(eaglerBrandString);
|
||||
}
|
||||
ImmutableMap.Builder<String, byte[]> ret = null;
|
||||
if (profileDatas != null) {
|
||||
for (Entry<String, byte[]> extra : profileDatas.entrySet()) {
|
||||
if (!profileDataStandard.contains(extra.getKey())) {
|
||||
if (ret == null) {
|
||||
ret = ImmutableMap.builder();
|
||||
}
|
||||
ret.put(extra.getKey(), extra.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
return new ProfileDataHolder(skinV1, skinV2, cape, updateCert, brandUUID, ret != null ? ret.build() : null);
|
||||
} else {
|
||||
return new ProfileDataHolder(null, null, null, null,
|
||||
server.getBrandService().getBrandUUIDClientLegacy(eaglerBrandString), Collections.emptyMap());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public NettyUnsafe netty() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Channel getChannel() {
|
||||
return channel;
|
||||
}
|
||||
|
||||
public IEaglerPendingConnection asPendingConnection() {
|
||||
if (loginConnection != null) {
|
||||
return loginConnection;
|
||||
} else if (pendingConnection != null) {
|
||||
return pendingConnection;
|
||||
} else {
|
||||
return pendingConnection = new EaglerPendingStateAdapter(this);
|
||||
}
|
||||
}
|
||||
|
||||
public IEaglerLoginConnection asLoginConnection() {
|
||||
if (loginConnection != null) {
|
||||
return loginConnection;
|
||||
} else {
|
||||
loginConnection = new EaglerLoginStateAdapter(this);
|
||||
pendingConnection = null;
|
||||
return loginConnection;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean processRealAddress() {
|
||||
if (realAddress != null) {
|
||||
Consumer<SocketAddress> handle = realAddressHandle;
|
||||
if (handle != null) {
|
||||
InetAddress addr;
|
||||
if (realInetAddress != null) {
|
||||
addr = realInetAddress;
|
||||
} else {
|
||||
try {
|
||||
addr = InetAddresses.forString(realAddress);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
connectionLogger.error("Connected with an invalid \""
|
||||
+ listenerInfo.getConfigData().getForwardIPHeader() + "\" header, disconnecting...",
|
||||
ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
int port = 65535;
|
||||
SocketAddress addr2 = channel.remoteAddress();
|
||||
if ((addr2 instanceof InetSocketAddress inetAddr)) {
|
||||
port = inetAddr.getPort();
|
||||
}
|
||||
handle.accept(realSocketAddressInstance = new InetSocketAddress(addr, port));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean processLoginRatelimit(ChannelHandlerContext ctx) {
|
||||
if (rateLimits != null) {
|
||||
EnumRateLimitState state = rateLimits.rateLimitLogin();
|
||||
if (!state.isOk()) {
|
||||
switch (state) {
|
||||
case BLOCKED:
|
||||
ctx.writeAndFlush(RateLimitMessage.getBlockedLoginMessage())
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
break;
|
||||
case BLOCKED_LOCKED:
|
||||
ctx.writeAndFlush(RateLimitMessage.getLockedLoginMessage())
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
break;
|
||||
default:
|
||||
ctx.close();
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean processQueryRatelimit(ChannelHandlerContext ctx) {
|
||||
if (rateLimits != null) {
|
||||
EnumRateLimitState state = rateLimits.rateLimitQuery();
|
||||
if (!state.isOk()) {
|
||||
switch (state) {
|
||||
case BLOCKED:
|
||||
ctx.writeAndFlush(RateLimitMessage.getBlockedQueryMessage())
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
break;
|
||||
case BLOCKED_LOCKED:
|
||||
ctx.writeAndFlush(RateLimitMessage.getLockedQueryMessage())
|
||||
.addListener(ChannelFutureListener.CLOSE);
|
||||
break;
|
||||
default:
|
||||
ctx.close();
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean hasLoginStateRedirectCap() {
|
||||
return gameProtocol.ver >= 5 && CapabilityBits.hasCapability(acceptedCapabilitiesMask, acceptedCapabilitiesVers,
|
||||
EnumCapabilityType.REDIRECT.getId(), 0);
|
||||
}
|
||||
|
||||
public void signalPlayState() {
|
||||
Runnable runnable = (Runnable) PLAY_STATE_REACHED_HANDLE.getAndSet(this, REACHED);
|
||||
if (runnable != null) {
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void awaitPlayState(Runnable continueHandler) {
|
||||
if (listenerInfo != null) {
|
||||
if (!PLAY_STATE_REACHED_HANDLE.compareAndSet(this, null, continueHandler)) {
|
||||
continueHandler.run();
|
||||
}
|
||||
} else {
|
||||
continueHandler.run();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IPacketImageLoader;
|
||||
import net.lax1dude.eaglercraft.v1_8.socket.protocol.util.PacketImageData;
|
||||
|
||||
public class PacketImageLoader {
|
||||
|
||||
public static final IPacketImageLoader INSTANCE = new IPacketImageLoader() {
|
||||
@Override
|
||||
public PacketImageData loadPacketImageData(int[] pixelsARGB8, int width, int height) {
|
||||
return PacketImageLoader.loadPacketImageData(pixelsARGB8, width, height);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketImageData loadPacketImageData(BufferedImage bufferedImage, int maxWidth, int maxHeight) {
|
||||
return PacketImageLoader.loadPacketImageData(bufferedImage, maxWidth, maxHeight);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketImageData loadPacketImageData(InputStream inputStream, int maxWidth, int maxHeight)
|
||||
throws IOException {
|
||||
return PacketImageLoader.loadPacketImageData(inputStream, maxWidth, maxHeight);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PacketImageData loadPacketImageData(File imageFile, int maxWidth, int maxHeight) throws IOException {
|
||||
return PacketImageLoader.loadPacketImageData(imageFile, maxWidth, maxHeight);
|
||||
}
|
||||
};
|
||||
|
||||
public static PacketImageData loadPacketImageData(int[] pixelsARGB8, int width, int height) {
|
||||
checkSize(width, height);
|
||||
if (pixelsARGB8 == null) {
|
||||
throw new NullPointerException("pixelsARGB8");
|
||||
}
|
||||
return new PacketImageData(width, height, pixelsARGB8);
|
||||
}
|
||||
|
||||
public static PacketImageData loadPacketImageData(BufferedImage img, int maxWidth, int maxHeight) {
|
||||
checkSize(maxWidth, maxHeight);
|
||||
int w = img.getWidth();
|
||||
int h = img.getHeight();
|
||||
if (w > maxWidth || h > maxHeight) {
|
||||
float aspectRatio = (float) w / (float) h;
|
||||
int nw, nh;
|
||||
if (aspectRatio >= 1.0f) {
|
||||
nw = (int) (maxWidth / aspectRatio);
|
||||
nh = maxHeight;
|
||||
} else {
|
||||
nw = maxWidth;
|
||||
nh = (int) (maxHeight * aspectRatio);
|
||||
}
|
||||
BufferedImage resized = new BufferedImage(nw, nh, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g = (Graphics2D) resized.getGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
|
||||
g.setBackground(new Color(0, true));
|
||||
g.clearRect(0, 0, nw, nh);
|
||||
g.drawImage(img, 0, 0, nw, nh, 0, 0, w, h, null);
|
||||
g.dispose();
|
||||
img = resized;
|
||||
}
|
||||
int[] pixels = new int[w * h];
|
||||
img.getRGB(0, 0, w, h, pixels, 0, w);
|
||||
return new PacketImageData(w, h, pixels);
|
||||
}
|
||||
|
||||
public static PacketImageData loadPacketImageData(InputStream inputStream, int maxWidth, int maxHeight)
|
||||
throws IOException {
|
||||
checkSize(maxWidth, maxHeight);
|
||||
return loadPacketImageData(ImageIO.read(inputStream), maxWidth, maxHeight);
|
||||
}
|
||||
|
||||
public static PacketImageData loadPacketImageData(File imageFile, int maxWidth, int maxHeight) throws IOException {
|
||||
checkSize(maxWidth, maxHeight);
|
||||
return loadPacketImageData(ImageIO.read(imageFile), maxWidth, maxHeight);
|
||||
}
|
||||
|
||||
private static void checkSize(int w, int h) {
|
||||
if (w < 0 || h < 0) {
|
||||
throw new IllegalArgumentException("Size is negative");
|
||||
}
|
||||
if (w > 255) {
|
||||
throw new IllegalArgumentException("Width is greater than 255");
|
||||
}
|
||||
if (h > 255) {
|
||||
throw new IllegalArgumentException("Height is greater than 255");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.util.RateLimiterBasic;
|
||||
|
||||
public class PlayerRateLimits {
|
||||
|
||||
public static class RateLimitParams {
|
||||
|
||||
public final int limitSkin;
|
||||
public final int limitCape;
|
||||
public final int limitVoiceCon;
|
||||
public final int limitVoiceReq;
|
||||
public final int limitVoiceICE;
|
||||
public final int limitBrand;
|
||||
public final int limitWebViewData;
|
||||
public final int limitWebViewMsg;
|
||||
public final int limitSkinAntagonist;
|
||||
public final int limitSvSkinAntagonist;
|
||||
public final int limitSvBrandAntagonist;
|
||||
|
||||
public RateLimitParams(int limitSkin, int limitCape, int limitVoiceCon, int limitVoiceReq, int limitVoiceICE,
|
||||
int limitBrand, int limitWebViewData, int limitWebViewMsg, int limitSkinAntagonist,
|
||||
int limitSvSkinAntagonist, int limitSvBrandAntagonist) {
|
||||
this.limitSkin = limitSkin;
|
||||
this.limitCape = limitCape;
|
||||
this.limitVoiceCon = limitVoiceCon;
|
||||
this.limitVoiceReq = limitVoiceReq;
|
||||
this.limitVoiceICE = limitVoiceICE;
|
||||
this.limitBrand = limitBrand;
|
||||
this.limitWebViewData = limitWebViewData;
|
||||
this.limitWebViewMsg = limitWebViewMsg;
|
||||
this.limitSkinAntagonist = limitSkinAntagonist;
|
||||
this.limitSvSkinAntagonist = limitSvSkinAntagonist;
|
||||
this.limitSvBrandAntagonist = limitSvBrandAntagonist;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private final RateLimitParams params;
|
||||
|
||||
private RateLimiterBasic ratelimitSkin;
|
||||
private RateLimiterBasic ratelimitCape;
|
||||
private RateLimiterBasic ratelimitVoiceCon;
|
||||
private RateLimiterBasic ratelimitVoiceReq;
|
||||
private RateLimiterBasic ratelimitVoiceICE;
|
||||
private RateLimiterBasic ratelimitBrand;
|
||||
private RateLimiterBasic ratelimitWebViewData;
|
||||
private RateLimiterBasic ratelimitWebViewMsg;
|
||||
private RateLimiterBasic skinAntagonistTracker;
|
||||
private RateLimiterBasic svSkinAntagonistTracker;
|
||||
private RateLimiterBasic svBrandAntagonistTracker;
|
||||
|
||||
public PlayerRateLimits(RateLimitParams params) {
|
||||
this.params = params;
|
||||
}
|
||||
|
||||
// Note that the below functions will cause a data race initializing
|
||||
// in multi-threaded environments, but java is memory-safe so fuck it
|
||||
|
||||
public boolean ratelimitSkin() {
|
||||
RateLimiterBasic limiter = ratelimitSkin;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitSkin = new RateLimiterBasic();
|
||||
}
|
||||
return limiter.rateLimit(params.limitSkin);
|
||||
}
|
||||
|
||||
public boolean ratelimitCape() {
|
||||
RateLimiterBasic limiter = ratelimitCape;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitCape = new RateLimiterBasic();
|
||||
}
|
||||
return limiter.rateLimit(params.limitCape);
|
||||
}
|
||||
|
||||
public boolean ratelimitVoiceCon() {
|
||||
RateLimiterBasic limiter = ratelimitVoiceCon;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitVoiceCon = new RateLimiterBasic();
|
||||
}
|
||||
return limiter.rateLimit(params.limitVoiceCon);
|
||||
}
|
||||
|
||||
public boolean ratelimitVoiceReq() {
|
||||
RateLimiterBasic limiter = ratelimitVoiceReq;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitVoiceReq = new RateLimiterBasic();
|
||||
}
|
||||
return limiter.rateLimit(params.limitVoiceReq);
|
||||
}
|
||||
|
||||
public boolean ratelimitVoiceICE() {
|
||||
RateLimiterBasic limiter = ratelimitVoiceICE;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitVoiceICE = new RateLimiterBasic();
|
||||
}
|
||||
return limiter.rateLimit(params.limitVoiceICE);
|
||||
}
|
||||
|
||||
public boolean ratelimitBrand() {
|
||||
RateLimiterBasic limiter = ratelimitBrand;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitBrand = new RateLimiterBasic();
|
||||
}
|
||||
return limiter.rateLimit(params.limitBrand);
|
||||
}
|
||||
|
||||
public boolean ratelimitWebViewData() {
|
||||
RateLimiterBasic limiter = ratelimitWebViewData;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitWebViewData = new RateLimiterBasic();
|
||||
}
|
||||
return limiter.rateLimit(params.limitWebViewData);
|
||||
}
|
||||
|
||||
public boolean ratelimitWebViewMsg() {
|
||||
RateLimiterBasic limiter = ratelimitWebViewMsg;
|
||||
if (limiter == null) {
|
||||
limiter = ratelimitWebViewMsg = new RateLimiterBasic();
|
||||
}
|
||||
return limiter.rateLimit(params.limitWebViewMsg);
|
||||
}
|
||||
|
||||
public boolean checkSkinAntagonist() {
|
||||
RateLimiterBasic limiter = skinAntagonistTracker;
|
||||
return limiter == null || limiter.checkState(params.limitSkinAntagonist);
|
||||
}
|
||||
|
||||
public boolean ratelimitSkinAntagonist() {
|
||||
RateLimiterBasic limiter = skinAntagonistTracker;
|
||||
if (limiter == null) {
|
||||
limiter = skinAntagonistTracker = new RateLimiterBasic();
|
||||
}
|
||||
return limiter.rateLimit(params.limitSkinAntagonist);
|
||||
}
|
||||
|
||||
public boolean checkSvSkinAntagonist() {
|
||||
RateLimiterBasic limiter = svSkinAntagonistTracker;
|
||||
return limiter == null || limiter.checkState(params.limitSvSkinAntagonist);
|
||||
}
|
||||
|
||||
public boolean ratelimitSvSkinAntagonist() {
|
||||
RateLimiterBasic limiter = svSkinAntagonistTracker;
|
||||
if (limiter == null) {
|
||||
limiter = svSkinAntagonistTracker = new RateLimiterBasic();
|
||||
}
|
||||
return limiter.rateLimit(params.limitSvSkinAntagonist);
|
||||
}
|
||||
|
||||
public boolean checkSvBrandAntagonist() {
|
||||
RateLimiterBasic limiter = svBrandAntagonistTracker;
|
||||
return limiter == null || limiter.checkState(params.limitSvBrandAntagonist);
|
||||
}
|
||||
|
||||
public boolean ratelimitSvBrandAntagonist() {
|
||||
RateLimiterBasic limiter = svBrandAntagonistTracker;
|
||||
if (limiter == null) {
|
||||
limiter = svBrandAntagonistTracker = new RateLimiterBasic();
|
||||
}
|
||||
return limiter.rateLimit(params.limitSvBrandAntagonist);
|
||||
}
|
||||
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
|
||||
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.handshake.HandshakePacketTypes;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.pipeline.BufferUtils;
|
||||
|
||||
class RateLimitMessage {
|
||||
|
||||
private static final ByteBuf blockedLogin = generateLoginKick(HandshakePacketTypes.SERVER_ERROR_RATELIMIT_BLOCKED,
|
||||
"Too many logins!");
|
||||
private static final ByteBuf lockedLogin = generateLoginKick(HandshakePacketTypes.SERVER_ERROR_RATELIMIT_LOCKED,
|
||||
"Too many logins!");
|
||||
|
||||
private static ByteBuf generateLoginKick(int code, String msg) {
|
||||
ByteBuf buf = Unpooled.buffer();
|
||||
try {
|
||||
buf.writeByte(HandshakePacketTypes.PROTOCOL_SERVER_ERROR);
|
||||
buf.writeByte(code);
|
||||
buf.writeByte(msg.length());
|
||||
BufferUtils.writeCharSequence(buf, msg, StandardCharsets.US_ASCII);
|
||||
return buf.retain();
|
||||
} finally {
|
||||
buf.release();
|
||||
}
|
||||
}
|
||||
|
||||
static BinaryWebSocketFrame getBlockedLoginMessage() {
|
||||
return new BinaryWebSocketFrame(Unpooled.wrappedBuffer(blockedLogin));
|
||||
}
|
||||
|
||||
static BinaryWebSocketFrame getLockedLoginMessage() {
|
||||
return new BinaryWebSocketFrame(Unpooled.wrappedBuffer(lockedLogin));
|
||||
}
|
||||
|
||||
static TextWebSocketFrame getBlockedQueryMessage() {
|
||||
return new TextWebSocketFrame("{\"type\":\"blocked\"}");
|
||||
}
|
||||
|
||||
static TextWebSocketFrame getLockedQueryMessage() {
|
||||
return new TextWebSocketFrame("{\"type\":\"locked\"}");
|
||||
}
|
||||
|
||||
}
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelHandler;
|
||||
import io.netty.channel.ChannelInboundHandler;
|
||||
import io.netty.channel.ChannelOutboundHandler;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerConnection;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.rewind.IEaglerXRewindInitializer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.rewind.IMessageController;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.rewind.IOutboundInjector;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.rewind.IPacket2ClientProtocol;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.message.RewindMessageControllerHandle;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.message.RewindMessageInjector;
|
||||
|
||||
public abstract class RewindInitializer<Attachment>
|
||||
implements IEaglerXRewindInitializer<Attachment>, IEaglerXRewindInitializer.NettyUnsafe {
|
||||
|
||||
private static class Packet2ClientProtocol implements IPacket2ClientProtocol {
|
||||
|
||||
private final int protocolVersion;
|
||||
private final String username;
|
||||
private final String serverHost;
|
||||
private final int serverPort;
|
||||
|
||||
protected Packet2ClientProtocol(int protocolVersion, String username, String serverHost, int serverPort) {
|
||||
this.protocolVersion = protocolVersion;
|
||||
this.username = username;
|
||||
this.serverHost = serverHost;
|
||||
this.serverPort = serverPort;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getProtocolVersion() {
|
||||
return protocolVersion;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getServerHost() {
|
||||
return serverHost;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getServerPort() {
|
||||
return serverPort;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected final Channel channel;
|
||||
private final NettyPipelineData pipelineData;
|
||||
private final int protocolVersion;
|
||||
private final String username;
|
||||
private final String serverHost;
|
||||
private final int serverPort;
|
||||
|
||||
private Packet2ClientProtocol packetAdapter;
|
||||
private boolean injected;
|
||||
private boolean handshake;
|
||||
private boolean canceled;
|
||||
|
||||
private int eaglerProtocol;
|
||||
private int minecraftProtocol;
|
||||
private String eaglerClientBrand;
|
||||
private String eaglerClientVersion;
|
||||
private boolean authEnabled;
|
||||
private byte[] authUsername;
|
||||
|
||||
private RewindMessageControllerHandle messageController;
|
||||
private RewindMessageInjector messageInjector;
|
||||
|
||||
public RewindInitializer(Channel channel, NettyPipelineData pipelineData, int protocolVersion, String username,
|
||||
String serverHost, int serverPort) {
|
||||
this.channel = channel;
|
||||
this.pipelineData = pipelineData;
|
||||
this.protocolVersion = protocolVersion;
|
||||
this.username = username;
|
||||
this.serverHost = serverHost;
|
||||
this.serverPort = serverPort;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerConnection getConnection() {
|
||||
return pipelineData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAttachment(Attachment obj) {
|
||||
pipelineData.rewindAttachment = obj;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPacket2ClientProtocol getLegacyHandshake() {
|
||||
if (packetAdapter == null) {
|
||||
packetAdapter = new Packet2ClientProtocol(protocolVersion, username, serverHost, serverPort);
|
||||
}
|
||||
return packetAdapter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rewriteInitialHandshakeV1(int eaglerProtocol, int minecraftProtocol, String eaglerClientBrand,
|
||||
String eaglerClientVersion) {
|
||||
if (eaglerProtocol != 1) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid eagler protocol " + eaglerProtocol + " for V1 handshake, must be 1");
|
||||
}
|
||||
if (minecraftProtocol < 0 || minecraftProtocol > 255) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid minecraft protocol " + minecraftProtocol + " for V1 handshake, must be between 0 and 255");
|
||||
}
|
||||
if (eaglerClientBrand == null) {
|
||||
throw new NullPointerException("eaglerClientBrand");
|
||||
}
|
||||
if (eaglerClientVersion == null) {
|
||||
throw new NullPointerException("eaglerClientVersion");
|
||||
}
|
||||
if (handshake) {
|
||||
throw new IllegalStateException("Handshake has already been injected");
|
||||
}
|
||||
handshake = true;
|
||||
this.eaglerProtocol = eaglerProtocol;
|
||||
this.minecraftProtocol = minecraftProtocol;
|
||||
this.eaglerClientBrand = eaglerClientBrand;
|
||||
this.eaglerClientVersion = eaglerClientVersion;
|
||||
this.authEnabled = false;
|
||||
this.authUsername = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rewriteInitialHandshakeV2(int eaglerProtocol, int minecraftProtocol, String eaglerClientBrand,
|
||||
String eaglerClientVersion, boolean authEnabled, byte[] authUsername) {
|
||||
if (eaglerProtocol <= 1) {
|
||||
throw new IllegalArgumentException("Invalid eagler protocol for V2+ handshake: " + eaglerProtocol);
|
||||
}
|
||||
if ((authEnabled || eaglerProtocol >= 5) && authUsername == null) {
|
||||
throw new NullPointerException("Auth username is null");
|
||||
}
|
||||
if (eaglerClientBrand == null) {
|
||||
throw new NullPointerException("eaglerClientBrand");
|
||||
}
|
||||
if (eaglerClientVersion == null) {
|
||||
throw new NullPointerException("eaglerClientVersion");
|
||||
}
|
||||
if (handshake) {
|
||||
throw new IllegalStateException("Handshake has already been injected");
|
||||
}
|
||||
handshake = true;
|
||||
this.eaglerProtocol = eaglerProtocol;
|
||||
this.minecraftProtocol = minecraftProtocol;
|
||||
this.eaglerClientBrand = eaglerClientBrand;
|
||||
this.eaglerClientVersion = eaglerClientVersion;
|
||||
this.authEnabled = authEnabled;
|
||||
this.authUsername = authUsername;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelDisconnect() {
|
||||
canceled = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NettyUnsafe netty() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Channel getChannel() {
|
||||
return channel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void injectNettyHandlers(ChannelOutboundHandler nettyEncoder, ChannelInboundHandler nettyDecoder) {
|
||||
if (nettyEncoder == null) {
|
||||
throw new NullPointerException("nettyEncoder");
|
||||
}
|
||||
if (nettyDecoder == null) {
|
||||
throw new NullPointerException("nettyDecoder");
|
||||
}
|
||||
if (injected) {
|
||||
throw new IllegalStateException("Handlers have already been injected");
|
||||
}
|
||||
injected = true;
|
||||
injectNettyHandlers0(nettyEncoder, nettyDecoder);
|
||||
}
|
||||
|
||||
protected abstract void injectNettyHandlers0(ChannelOutboundHandler nettyEncoder,
|
||||
ChannelInboundHandler nettyDecoder);
|
||||
|
||||
@Override
|
||||
public void injectNettyHandlers(ChannelHandler nettyCodec) {
|
||||
if (nettyCodec == null) {
|
||||
throw new NullPointerException("nettyCodec");
|
||||
}
|
||||
if (injected) {
|
||||
throw new IllegalStateException("Handlers have already been injected");
|
||||
}
|
||||
injected = true;
|
||||
injectNettyHandlers0(nettyCodec);
|
||||
}
|
||||
|
||||
protected abstract void injectNettyHandlers0(ChannelHandler nettyCodec);
|
||||
|
||||
@Override
|
||||
public IMessageController requestMessageController() {
|
||||
if (messageController != null) {
|
||||
throw new IllegalStateException("Message controller handle has already been created");
|
||||
}
|
||||
return messageController = new RewindMessageControllerHandle(pipelineData.connectionLogger);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IOutboundInjector requestOutboundInjector() {
|
||||
if (messageInjector != null) {
|
||||
throw new IllegalStateException("Message injector has already been created");
|
||||
}
|
||||
return messageInjector = new RewindMessageInjector(channel);
|
||||
}
|
||||
|
||||
public boolean isCanceled() {
|
||||
return canceled;
|
||||
}
|
||||
|
||||
public boolean isInjected() {
|
||||
return injected;
|
||||
}
|
||||
|
||||
public boolean isHandshake() {
|
||||
return handshake;
|
||||
}
|
||||
|
||||
public int getEaglerProtocol() {
|
||||
return eaglerProtocol;
|
||||
}
|
||||
|
||||
public int getMinecraftProtocol() {
|
||||
return minecraftProtocol;
|
||||
}
|
||||
|
||||
public String getEaglerClientBrand() {
|
||||
return eaglerClientBrand;
|
||||
}
|
||||
|
||||
public String getEaglerClientVersion() {
|
||||
return eaglerClientVersion;
|
||||
}
|
||||
|
||||
public boolean isAuthEnabled() {
|
||||
return authEnabled;
|
||||
}
|
||||
|
||||
public byte[] getAuthUsername() {
|
||||
return authUsername;
|
||||
}
|
||||
|
||||
public RewindMessageControllerHandle getMessageControllerHandle() {
|
||||
return messageController;
|
||||
}
|
||||
|
||||
public RewindMessageInjector getMessageInjector() {
|
||||
return messageInjector;
|
||||
}
|
||||
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerXServerAPI;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.rewind.IEaglerXRewindProtocol;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.rewind.IEaglerXRewindService;
|
||||
|
||||
public class RewindService<PlayerObject> implements IEaglerXRewindService<PlayerObject> {
|
||||
|
||||
private final EaglerXServer<PlayerObject> server;
|
||||
private final boolean enabled;
|
||||
|
||||
private final ReadWriteLock registerLock;
|
||||
private final Map<IEaglerXRewindProtocol<PlayerObject, ?>, int[]> registeredProtocols;
|
||||
private final IEaglerXRewindProtocol<PlayerObject, ?>[] protocolIds;
|
||||
|
||||
public RewindService(EaglerXServer<PlayerObject> server) {
|
||||
this.server = server;
|
||||
this.enabled = server.getConfig().getSettings().getProtocols().isEaglerXRewindAllowed();
|
||||
this.registerLock = enabled ? new ReentrantReadWriteLock() : null;
|
||||
this.registeredProtocols = enabled ? new IdentityHashMap<>() : null;
|
||||
this.protocolIds = enabled ? new IEaglerXRewindProtocol[256] : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerXServerAPI<PlayerObject> getServerAPI() {
|
||||
return server;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isActive() {
|
||||
if (!enabled) {
|
||||
return false;
|
||||
}
|
||||
registerLock.readLock().lock();
|
||||
try {
|
||||
return !registeredProtocols.isEmpty();
|
||||
} finally {
|
||||
registerLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerLegacyProtocol(IEaglerXRewindProtocol<PlayerObject, ?> protocolHandler) {
|
||||
if (!enabled) {
|
||||
throw new UnsupportedOperationException("EaglerXRewind is not enabled on this server");
|
||||
}
|
||||
if (protocolHandler == null) {
|
||||
throw new NullPointerException("protocolHandler");
|
||||
}
|
||||
int handshakeProtocol = protocolHandler.getEmulatedEaglerHandshake();
|
||||
if (!server.isEaglerHandshakeSupported(handshakeProtocol)) {
|
||||
throw new UnsupportedOperationException("Unsupported handshake protocol version: " + handshakeProtocol);
|
||||
}
|
||||
int[] protocols = protocolHandler.getLegacyProtocols();
|
||||
if (protocols == null || protocols.length == 0) {
|
||||
return;
|
||||
}
|
||||
protocols = protocols.clone();
|
||||
for (int i = 0; i < protocols.length; ++i) {
|
||||
int j = protocols[i];
|
||||
if (j < 0 && j > 255) {
|
||||
throw new UnsupportedOperationException("Invalid legacy protocol version: " + j);
|
||||
}
|
||||
}
|
||||
registerLock.writeLock().lock();
|
||||
try {
|
||||
if (registeredProtocols.putIfAbsent(protocolHandler, protocols) == null) {
|
||||
for (int i = 0; i < protocols.length; ++i) {
|
||||
protocolIds[protocols[i]] = protocolHandler;
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
} finally {
|
||||
registerLock.writeLock().unlock();
|
||||
}
|
||||
protocolHandler.handleRegistered(server);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregisterLegacyProtocol(IEaglerXRewindProtocol<PlayerObject, ?> protocolHandler) {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
if (protocolHandler == null) {
|
||||
throw new NullPointerException("protocolHandler");
|
||||
}
|
||||
registerLock.writeLock().lock();
|
||||
try {
|
||||
int[] protocols = registeredProtocols.remove(protocolHandler);
|
||||
if (protocols != null) {
|
||||
for (int i = 0; i < protocols.length; ++i) {
|
||||
protocolIds[protocols[i]] = null;
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
} finally {
|
||||
registerLock.writeLock().unlock();
|
||||
}
|
||||
protocolHandler.handleUnregistered(server);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasLegacyProtocol(int protocolVersion) {
|
||||
if (!enabled || protocolVersion < 0 || protocolVersion > 255) {
|
||||
return false;
|
||||
}
|
||||
registerLock.readLock().lock();
|
||||
try {
|
||||
return protocolIds[protocolVersion] != null;
|
||||
} finally {
|
||||
registerLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public IEaglerXRewindProtocol<PlayerObject, ?> getProtocol(int protocolVersion) {
|
||||
if (!enabled || protocolVersion < 0 || protocolVersion > 255) {
|
||||
return null;
|
||||
}
|
||||
registerLock.readLock().lock();
|
||||
try {
|
||||
return protocolIds[protocolVersion];
|
||||
} finally {
|
||||
registerLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.net.ssl.SSLException;
|
||||
|
||||
import com.google.common.collect.BiMap;
|
||||
import com.google.common.collect.HashBiMap;
|
||||
import com.google.common.collect.HashMultiset;
|
||||
import com.google.common.collect.Multiset;
|
||||
import com.google.common.io.ByteStreams;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformLogger;
|
||||
import net.lax1dude.eaglercraft.backend.server.util.HashPair;
|
||||
|
||||
public class SSLCertificateManager {
|
||||
|
||||
private final BiMap<HashPair<File, File>, SSLContextHolderBuiltin> pairs = HashBiMap.create();
|
||||
private final Multiset<File> filesRefreshable = HashMultiset.create();
|
||||
private final Map<File, RefreshWatcher> refreshableFiles = new HashMap<>();
|
||||
private final IPlatformLogger logger;
|
||||
|
||||
private static class RefreshWatcher {
|
||||
|
||||
protected final File file;
|
||||
protected byte[] data;
|
||||
protected long lastModified;
|
||||
protected final Set<SSLContextHolderBuiltin> childrenA = new HashSet<>();
|
||||
protected final Set<SSLContextHolderBuiltin> childrenB = new HashSet<>();
|
||||
|
||||
protected RefreshWatcher(File file) throws SSLException {
|
||||
this.file = file;
|
||||
try {
|
||||
this.data = readFileBytes(file);
|
||||
} catch (IOException ex) {
|
||||
throw new SSLException("Could not load certificate file: " + file.getAbsolutePath(), ex);
|
||||
}
|
||||
this.lastModified = file.lastModified();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public SSLCertificateManager(IPlatformLogger logger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public synchronized SSLContextHolderBuiltin createHolder(File publicChain, File privateKey,
|
||||
String privateKeyPassword, boolean autoRefresh) throws SSLException {
|
||||
publicChain = publicChain.getAbsoluteFile();
|
||||
privateKey = privateKey.getAbsoluteFile();
|
||||
if (publicChain.equals(privateKey)) {
|
||||
throw new IllegalArgumentException("Public and private key are the same file");
|
||||
}
|
||||
HashPair<File, File> pair = new HashPair<>(publicChain, privateKey);
|
||||
SSLContextHolderBuiltin ret = pairs.get(pair);
|
||||
if (ret != null) {
|
||||
return ret;
|
||||
}
|
||||
ret = new SSLContextHolderBuiltin(createName(publicChain, privateKey), privateKeyPassword);
|
||||
RefreshWatcher pub = getOrCreateRefresher(publicChain);
|
||||
RefreshWatcher priv = getOrCreateRefresher(privateKey);
|
||||
ret.pubKey = pub.data;
|
||||
ret.privKey = priv.data;
|
||||
ret.refresh();
|
||||
if (autoRefresh) {
|
||||
pairs.put(pair, ret);
|
||||
filesRefreshable.add(publicChain);
|
||||
refreshableFiles.put(publicChain, pub);
|
||||
filesRefreshable.add(privateKey);
|
||||
refreshableFiles.put(privateKey, priv);
|
||||
pub.childrenA.add(ret);
|
||||
priv.childrenB.add(ret);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
public synchronized void releaseHolder(SSLContextHolderBuiltin holder) {
|
||||
HashPair<File, File> pair = pairs.inverse().remove(holder);
|
||||
if (pair != null) {
|
||||
filesRefreshable.remove(pair.valueA);
|
||||
filesRefreshable.remove(pair.valueB);
|
||||
if (!filesRefreshable.contains(pair.valueA)) {
|
||||
refreshableFiles.remove(pair.valueA);
|
||||
} else {
|
||||
RefreshWatcher w = refreshableFiles.get(pair.valueA);
|
||||
if (w != null) {
|
||||
w.childrenA.remove(holder);
|
||||
}
|
||||
}
|
||||
if (!filesRefreshable.contains(pair.valueB)) {
|
||||
refreshableFiles.remove(pair.valueB);
|
||||
} else {
|
||||
RefreshWatcher w = refreshableFiles.get(pair.valueB);
|
||||
if (w != null) {
|
||||
w.childrenB.remove(holder);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized boolean hasRefreshableFiles() {
|
||||
return !refreshableFiles.isEmpty();
|
||||
}
|
||||
|
||||
public synchronized void update() {
|
||||
if (refreshableFiles.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Set<SSLContextHolderBuiltin> holdersThatNeedRefresh = null;
|
||||
for (RefreshWatcher w : refreshableFiles.values()) {
|
||||
long l = w.file.lastModified();
|
||||
if (l != w.lastModified) {
|
||||
byte[] newData;
|
||||
try {
|
||||
newData = readFileBytes(w.file);
|
||||
} catch (IOException e) {
|
||||
logger.error("Could not read certificate: " + w.file.getAbsolutePath(), e);
|
||||
continue;
|
||||
}
|
||||
w.lastModified = l;
|
||||
if (!Arrays.equals(w.data, newData)) {
|
||||
logger.info("TLS certificate was modified: " + w.file.getAbsolutePath());
|
||||
w.data = newData;
|
||||
for (SSLContextHolderBuiltin a : w.childrenA) {
|
||||
a.pubKey = newData;
|
||||
if (holdersThatNeedRefresh == null) {
|
||||
holdersThatNeedRefresh = new HashSet<>();
|
||||
}
|
||||
holdersThatNeedRefresh.add(a);
|
||||
}
|
||||
for (SSLContextHolderBuiltin b : w.childrenB) {
|
||||
b.privKey = newData;
|
||||
if (holdersThatNeedRefresh == null) {
|
||||
holdersThatNeedRefresh = new HashSet<>();
|
||||
}
|
||||
holdersThatNeedRefresh.add(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (holdersThatNeedRefresh != null) {
|
||||
boolean err = false;
|
||||
for (SSLContextHolderBuiltin ctx : holdersThatNeedRefresh) {
|
||||
try {
|
||||
ctx.refresh();
|
||||
} catch (SSLException ex) {
|
||||
logger.error("Could not refresh TLS certificate pair " + ctx.name + "!", ex);
|
||||
err = true;
|
||||
}
|
||||
}
|
||||
if (!err) {
|
||||
logger.info("Refreshed TLS context caches");
|
||||
} else {
|
||||
logger.error("One or more TLS contexts could not be reloaded");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private RefreshWatcher getOrCreateRefresher(File file) throws SSLException {
|
||||
RefreshWatcher ret = refreshableFiles.get(file);
|
||||
if (ret != null) {
|
||||
return ret;
|
||||
} else {
|
||||
return new RefreshWatcher(file);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] readFileBytes(File file) throws IOException {
|
||||
try (InputStream is = new FileInputStream(file)) {
|
||||
return ByteStreams.toByteArray(is);
|
||||
}
|
||||
}
|
||||
|
||||
private static String createName(File pubFile, File privFile) {
|
||||
return "{pub = " + pubFile.getName() + ", priv = " + privFile.getName() + "}";
|
||||
}
|
||||
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
|
||||
import javax.net.ssl.SSLException;
|
||||
|
||||
import io.netty.buffer.ByteBufAllocator;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
import io.netty.handler.ssl.SslContextBuilder;
|
||||
import io.netty.handler.ssl.SslHandler;
|
||||
|
||||
public class SSLContextHolderBuiltin implements ISSLContextProvider {
|
||||
|
||||
protected final String name;
|
||||
protected final String password;
|
||||
protected byte[] pubKey;
|
||||
protected byte[] privKey;
|
||||
protected SslContext ctx;
|
||||
|
||||
protected SSLContextHolderBuiltin(String name, String password) {
|
||||
this.name = name;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SslHandler newHandler(ByteBufAllocator alloc) {
|
||||
return ctx.newHandler(alloc);
|
||||
}
|
||||
|
||||
protected void refresh() throws SSLException {
|
||||
ctx = SslContextBuilder.forServer(new ByteArrayInputStream(pubKey), new ByteArrayInputStream(privKey), password)
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import io.netty.buffer.ByteBufAllocator;
|
||||
import io.netty.handler.ssl.SslContext;
|
||||
import io.netty.handler.ssl.SslContextBuilder;
|
||||
import io.netty.handler.ssl.SslHandler;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IEaglerListenerInfo;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.ITLSManager;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.TLSManagerException;
|
||||
|
||||
public class SSLContextHolderPlugin implements ISSLContextProvider, ITLSManager {
|
||||
|
||||
private final EaglerListener listener;
|
||||
private SslContext ctx;
|
||||
|
||||
public SSLContextHolderPlugin(EaglerListener listener) {
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEaglerListenerInfo getListener() {
|
||||
return listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCertificate(File fullChain, File privateKey, String privateKeyPassword) throws TLSManagerException {
|
||||
try {
|
||||
ctx = SslContextBuilder.forServer(fullChain, privateKey, privateKeyPassword).build();
|
||||
} catch (Exception ex) {
|
||||
throw propigateTLSManagerException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCertificate(InputStream fullChain, InputStream privateKey, String privateKeyPassword)
|
||||
throws TLSManagerException {
|
||||
try {
|
||||
ctx = SslContextBuilder.forServer(fullChain, privateKey, privateKeyPassword).build();
|
||||
} catch (Exception ex) {
|
||||
throw propigateTLSManagerException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCertificate(byte[] fullChain, byte[] privateKey, String privateKeyPassword)
|
||||
throws TLSManagerException {
|
||||
try {
|
||||
ctx = SslContextBuilder.forServer(new ByteArrayInputStream(fullChain), new ByteArrayInputStream(privateKey),
|
||||
privateKeyPassword).build();
|
||||
} catch (Exception ex) {
|
||||
throw propigateTLSManagerException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCertificate(X509Certificate[] fullChain, PrivateKey privateKey, String privateKeyPassword)
|
||||
throws TLSManagerException {
|
||||
try {
|
||||
ctx = SslContextBuilder.forServer(privateKey, privateKeyPassword, fullChain).build();
|
||||
} catch (Exception ex) {
|
||||
throw propigateTLSManagerException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private TLSManagerException propigateTLSManagerException(Exception ex) {
|
||||
if ((ex instanceof IllegalArgumentException) || (ex instanceof CertificateException)) {
|
||||
return new TLSManagerException(ex.getMessage(), ex.getCause());
|
||||
} else {
|
||||
return new TLSManagerException("Uncaught exception creating TLS context!", ex.getCause());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public SslHandler newHandler(ByteBufAllocator alloc) {
|
||||
return ctx != null ? ctx.newHandler(alloc) : null;
|
||||
}
|
||||
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.IServerIconLoader;
|
||||
|
||||
public class ServerIconLoader {
|
||||
|
||||
public static final IServerIconLoader INSTANCE = new IServerIconLoader() {
|
||||
@Override
|
||||
public byte[] loadServerIcon(int[] pixelsIn, int width, int height) {
|
||||
return ServerIconLoader.loadServerIcon(pixelsIn, width, height);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] loadServerIcon(BufferedImage image) {
|
||||
return ServerIconLoader.loadServerIcon(image);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] loadServerIcon(InputStream stream) throws IOException {
|
||||
return ServerIconLoader.loadServerIcon(stream);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] loadServerIcon(File file) throws IOException {
|
||||
return ServerIconLoader.loadServerIcon(file);
|
||||
}
|
||||
};
|
||||
|
||||
public static byte[] loadServerIcon(int[] pixelsIn, int width, int height) {
|
||||
if (pixelsIn == null) {
|
||||
throw new NullPointerException("pixelsIn");
|
||||
}
|
||||
if (width == 64 && height == 64) {
|
||||
return toBytes(pixelsIn);
|
||||
} else {
|
||||
BufferedImage tmp = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
|
||||
tmp.setRGB(0, 0, width, height, pixelsIn, 0, width);
|
||||
return loadServerIcon(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] loadServerIcon(BufferedImage image) {
|
||||
BufferedImage icon = image;
|
||||
boolean gotScaled = false;
|
||||
if (icon.getWidth() != 64 || icon.getHeight() != 64) {
|
||||
icon = new BufferedImage(64, 64, image.getType());
|
||||
Graphics2D g = (Graphics2D) icon.getGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
|
||||
(image.getWidth() < 64 || image.getHeight() < 64)
|
||||
? RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR
|
||||
: RenderingHints.VALUE_INTERPOLATION_BICUBIC);
|
||||
g.setBackground(new Color(0, true));
|
||||
g.clearRect(0, 0, 64, 64);
|
||||
int ow = image.getWidth();
|
||||
int oh = image.getHeight();
|
||||
int nw, nh;
|
||||
float aspectRatio = (float) oh / (float) ow;
|
||||
if (aspectRatio >= 1.0f) {
|
||||
nw = (int) (64 / aspectRatio);
|
||||
nh = 64;
|
||||
} else {
|
||||
nw = 64;
|
||||
nh = (int) (64 * aspectRatio);
|
||||
}
|
||||
g.drawImage(image, (64 - nw) / 2, (64 - nh) / 2, (64 - nw) / 2 + nw, (64 - nh) / 2 + nh, 0, 0,
|
||||
image.getWidth(), image.getHeight(), null);
|
||||
g.dispose();
|
||||
gotScaled = true;
|
||||
}
|
||||
int[] pxls = icon.getRGB(0, 0, 64, 64, new int[4096], 0, 64);
|
||||
if (gotScaled) {
|
||||
for (int i = 0; i < pxls.length; ++i) {
|
||||
if ((pxls[i] & 0xFFFFFF) == 0) {
|
||||
pxls[i] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return toBytes(pxls);
|
||||
}
|
||||
|
||||
public static byte[] loadServerIcon(InputStream stream) throws IOException {
|
||||
return loadServerIcon(ImageIO.read(stream));
|
||||
}
|
||||
|
||||
public static byte[] loadServerIcon(File file) throws IOException {
|
||||
return loadServerIcon(ImageIO.read(file));
|
||||
}
|
||||
|
||||
private static byte[] toBytes(int[] pixels) {
|
||||
byte[] iconPixels = new byte[16384];
|
||||
for (int i = 0, j, k; i < 4096; ++i) {
|
||||
j = i << 2;
|
||||
k = pixels[i];
|
||||
iconPixels[j] = (byte) (k >>> 16);
|
||||
iconPixels[j + 1] = (byte) (k >>> 8);
|
||||
iconPixels[j + 2] = (byte) k;
|
||||
iconPixels[j + 3] = (byte) (k >>> 24);
|
||||
}
|
||||
return iconPixels;
|
||||
}
|
||||
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformComponentBuilder.EnumChatColor;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformComponentBuilder.EnumClickAction;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformPlayer;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformTask;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.config.ConfigDataSettings.ConfigDataUpdateChecker;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.pipeline.BufferUtils;
|
||||
import net.lax1dude.eaglercraft.backend.server.util.SemanticVersion;
|
||||
|
||||
public class UpdateChecker {
|
||||
|
||||
private static final VarHandle AVAILABLE_HANDLE;
|
||||
|
||||
static {
|
||||
try {
|
||||
AVAILABLE_HANDLE = MethodHandles.lookup().findVarHandle(UpdateChecker.class, "available", String.class);
|
||||
} catch (ReflectiveOperationException ex) {
|
||||
throw new ExceptionInInitializerError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private final EaglerXServer<?> server;
|
||||
private final ConfigDataUpdateChecker config;
|
||||
private volatile String available;
|
||||
private IPlatformTask checkTask;
|
||||
|
||||
public UpdateChecker(EaglerXServer<?> server, ConfigDataUpdateChecker config) {
|
||||
this.server = server;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public void handleEnable() {
|
||||
if (EaglerXServerVersion.UPDATE_CHECK != null && config.isEnableUpdateChecker()) {
|
||||
check();
|
||||
int period = config.getCheckForServerUpdateEvery();
|
||||
if (period > 0) {
|
||||
checkTask = server.getPlatform().getScheduler().executeAsyncRepeatingTask(this::check, period * 1000l,
|
||||
period * 1000l);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void handleDisable() {
|
||||
if (EaglerXServerVersion.UPDATE_CHECK != null && config.isEnableUpdateChecker()) {
|
||||
if (checkTask != null) {
|
||||
checkTask.cancel();
|
||||
checkTask = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void check() {
|
||||
server.getInternalHTTPClient().asyncRequest("GET", URI.create(EaglerXServerVersion.UPDATE_CHECK), (res) -> {
|
||||
try {
|
||||
if (res.exception != null) {
|
||||
server.logger().error("Could not check for server updates: " + res.exception.toString());
|
||||
} else if (res.code != 200) {
|
||||
server.logger().error("Could not check for server updates, response code " + res.code);
|
||||
} else if (res.data == null || res.data.readableBytes() == 0) {
|
||||
server.logger().error("Could not check for server updates, received empty response");
|
||||
} else {
|
||||
String str = BufferUtils.readCharSequence(res.data, res.data.readableBytes(),
|
||||
StandardCharsets.UTF_8).toString().trim();
|
||||
SemanticVersion ver;
|
||||
try {
|
||||
ver = SemanticVersion.parse(str);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
server.logger().error("Could not check for server updates, response invalid");
|
||||
return;
|
||||
}
|
||||
if (ver.greaterThan(EaglerXServerVersion.UPDATE_VERSION)) {
|
||||
AVAILABLE_HANDLE.setRelease(this, ver.toString());
|
||||
server.logger().warn("=============================================");
|
||||
server.logger().warn("=============================================");
|
||||
server.logger().warn("");
|
||||
server.logger().warn(" Updates are available for EaglerXServer");
|
||||
server.logger().warn(" ---------------------------------------");
|
||||
server.logger().warn("");
|
||||
server.logger().warn(" :< Active: " + EaglerXServerVersion.UPDATE_VERSION);
|
||||
server.logger().warn("");
|
||||
server.logger().warn(" :> Latest: " + ver);
|
||||
server.logger().warn("");
|
||||
server.logger().warn(" " + EaglerXServerVersion.UPDATE_LINK);
|
||||
server.logger().warn(" " + EaglerXServerVersion.UPDATE_LINE);
|
||||
server.logger().warn("");
|
||||
server.logger().warn("=============================================");
|
||||
server.logger().warn("=============================================");
|
||||
} else {
|
||||
AVAILABLE_HANDLE.setRelease(this, null);
|
||||
server.logger().info("You are running the latest version of EaglerXServer");
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (res.data != null) {
|
||||
res.data.release();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void sendUpdateMessage(IPlatformPlayer<?> playerObj) {
|
||||
if (EaglerXServerVersion.UPDATE_CHECK != null && config.isUpdateChatMessages()) {
|
||||
String avail = (String) AVAILABLE_HANDLE.getAcquire(this);
|
||||
if (avail != null) {
|
||||
server.getPlatform().getScheduler().executeAsyncDelayed(() -> {
|
||||
if (playerObj.isConnected()) {
|
||||
playerObj.sendMessage(server.componentBuilder().buildTextComponent().beginStyle()
|
||||
.color(EnumChatColor.GOLD).end().text("[EaglerXServer]").appendTextComponent()
|
||||
.beginStyle().color(EnumChatColor.AQUA).end().text(" An updated version is available: ")
|
||||
.end().appendTextComponent().beginStyle().color(EnumChatColor.YELLOW).underline(true)
|
||||
.end().beginClickEvent().clickAction(EnumClickAction.OPEN_URL)
|
||||
.clickValue(EaglerXServerVersion.UPDATE_LINK).end().text(avail).end().end());
|
||||
}
|
||||
}, 2000l);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.*;
|
||||
|
||||
/** Common superclass for collections. */
|
||||
abstract class AbstractIntCollection implements IntCollection {
|
||||
/** Default implementation uses a predicate for removal. */
|
||||
@Override
|
||||
public int removeAll(final IntLookupContainer c) {
|
||||
return this.removeAll(c::contains);
|
||||
}
|
||||
|
||||
/** Default implementation uses a predicate for retaining. */
|
||||
@Override
|
||||
public int retainAll(final IntLookupContainer c) {
|
||||
// We know c holds sub-types of int and we're not modifying c, so go unchecked.
|
||||
return this.removeAll(k -> !c.contains(k));
|
||||
}
|
||||
|
||||
/**
|
||||
* Default implementation redirects to {@link #removeAll(IntPredicate)} and
|
||||
* negates the predicate.
|
||||
*/
|
||||
@Override
|
||||
public int retainAll(final IntPredicate predicate) {
|
||||
return removeAll(value -> !predicate.apply(value));
|
||||
}
|
||||
|
||||
/** Default implementation of copying to an array. */
|
||||
@Override
|
||||
public int[] toArray() {
|
||||
|
||||
int[] array = (new int[size()]);
|
||||
int i = 0;
|
||||
for (IntCursor c : this) {
|
||||
array[i++] = c.value;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
/** Convert the contents of this container to a human-friendly string. */
|
||||
@Override
|
||||
public String toString() {
|
||||
return Arrays.toString(this.toArray());
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* Simplifies the implementation of iterators a bit. Modeled loosely after
|
||||
* Google Guava's API.
|
||||
*/
|
||||
public abstract class AbstractIterator<E> implements Iterator<E> {
|
||||
private static final int NOT_CACHED = 0;
|
||||
private static final int CACHED = 1;
|
||||
private static final int AT_END = 2;
|
||||
|
||||
/** Current iterator state. */
|
||||
private int state = NOT_CACHED;
|
||||
|
||||
/** The next element to be returned from {@link #next()} if fetched. */
|
||||
private E nextElement;
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
if (state == NOT_CACHED) {
|
||||
state = CACHED;
|
||||
nextElement = fetch();
|
||||
}
|
||||
return state == CACHED;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public E next() {
|
||||
if (!hasNext()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
|
||||
state = NOT_CACHED;
|
||||
return nextElement;
|
||||
}
|
||||
|
||||
/** Default implementation throws {@link UnsupportedOperationException}. */
|
||||
@Override
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch next element. The implementation must return {@link #done()} when all
|
||||
* elements have been fetched.
|
||||
*
|
||||
* @return Returns the next value for the iterator or chain-calls
|
||||
* {@link #done()}.
|
||||
*/
|
||||
protected abstract E fetch();
|
||||
|
||||
/**
|
||||
* Call when done.
|
||||
*
|
||||
* @return Returns a unique sentinel value to indicate end-of-iteration.
|
||||
*/
|
||||
protected final E done() {
|
||||
state = AT_END;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.*;
|
||||
|
||||
/** Common superclass for collections. */
|
||||
@SuppressWarnings("unchecked")
|
||||
abstract class AbstractObjectCollection<KType> implements ObjectCollection<KType> {
|
||||
/** Default implementation uses a predicate for removal. */
|
||||
@Override
|
||||
public int removeAll(final ObjectLookupContainer<? super KType> c) {
|
||||
return this.removeAll(c::contains);
|
||||
}
|
||||
|
||||
/** Default implementation uses a predicate for retaining. */
|
||||
@Override
|
||||
public int retainAll(final ObjectLookupContainer<? super KType> c) {
|
||||
// We know c holds sub-types of Object and we're not modifying c, so go
|
||||
// unchecked.
|
||||
return this.removeAll(k -> !c.contains(k));
|
||||
}
|
||||
|
||||
/**
|
||||
* Default implementation redirects to {@link #removeAll(ObjectPredicate)} and
|
||||
* negates the predicate.
|
||||
*/
|
||||
@Override
|
||||
public int retainAll(final ObjectPredicate<? super KType> predicate) {
|
||||
return removeAll(value -> !predicate.apply(value));
|
||||
}
|
||||
|
||||
/** Default implementation of copying to an array. */
|
||||
@Override
|
||||
public Object[] toArray() {
|
||||
|
||||
KType[] array = ((KType[]) new Object[size()]);
|
||||
int i = 0;
|
||||
for (ObjectCursor<KType> c : this) {
|
||||
array[i++] = c.value;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
public <T> T[] toArray(Class<T> componentClass) {
|
||||
final int size = size();
|
||||
final T[] array = (T[]) java.lang.reflect.Array.newInstance(componentClass, size);
|
||||
int i = 0;
|
||||
for (ObjectCursor<KType> c : this) {
|
||||
array[i++] = (T) c.value;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
/** Convert the contents of this container to a human-friendly string. */
|
||||
@Override
|
||||
public String toString() {
|
||||
return Arrays.toString(this.toArray());
|
||||
}
|
||||
|
||||
protected boolean equals(Object v1, Object v2) {
|
||||
return (v1 == v2) || (v1 != null && v1.equals(v2));
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.Accountable;
|
||||
|
||||
/** Resizing (growth) strategy for array-backed buffers. */
|
||||
public interface ArraySizingStrategy extends Accountable {
|
||||
/**
|
||||
* @param currentBufferLength Current size of the array (buffer). This number
|
||||
* should comply with the strategy's policies (it is
|
||||
* a result of initial rounding or further
|
||||
* growCalls). It can also be zero, indicating the
|
||||
* growth from an empty buffer.
|
||||
* @param elementsCount Number of elements stored in the buffer.
|
||||
* @param expectedAdditions Expected number of additions (resize hint).
|
||||
* @return Must return a new size at least as big as to hold <code>
|
||||
* elementsCount + expectedAdditions</code>.
|
||||
* @throws BufferAllocationException If the sizing strategy cannot grow the
|
||||
* buffer (for example due to constraints or
|
||||
* memory limits).
|
||||
*/
|
||||
int grow(int currentBufferLength, int elementsCount, int expectedAdditions) throws BufferAllocationException;
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
/**
|
||||
* Bit mixing utilities. The purpose of these methods is to evenly distribute
|
||||
* key space over int32 range.
|
||||
*/
|
||||
public final class BitMixer {
|
||||
|
||||
// Don't bother mixing very small key domains much.
|
||||
public static int mix(byte key) {
|
||||
return key * PHI_C32;
|
||||
}
|
||||
|
||||
public static int mix(short key) {
|
||||
return mixPhi(key);
|
||||
}
|
||||
|
||||
public static int mix(char key) {
|
||||
return mixPhi(key);
|
||||
}
|
||||
|
||||
// Better mix for larger key domains.
|
||||
public static int mix(int key) {
|
||||
return mix32(key);
|
||||
}
|
||||
|
||||
public static int mix(float key) {
|
||||
return mix32(Float.floatToIntBits(key));
|
||||
}
|
||||
|
||||
public static int mix(double key) {
|
||||
return (int) mix64(Double.doubleToLongBits(key));
|
||||
}
|
||||
|
||||
public static int mix(long key) {
|
||||
return (int) mix64(key);
|
||||
}
|
||||
|
||||
public static int mix(Object key) {
|
||||
return key == null ? 0 : mix32(key.hashCode());
|
||||
}
|
||||
|
||||
/** MH3's plain finalization step. */
|
||||
public static int mix32(int k) {
|
||||
k = (k ^ (k >>> 16)) * 0x85ebca6b;
|
||||
k = (k ^ (k >>> 13)) * 0xc2b2ae35;
|
||||
return k ^ (k >>> 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes David Stafford variant 9 of 64bit mix function (MH3 finalization
|
||||
* step, with different shifts and constants).
|
||||
*
|
||||
* <p>
|
||||
* Variant 9 is picked because it contains two 32-bit shifts which could be
|
||||
* possibly optimized into better machine code.
|
||||
*
|
||||
* @see "http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html"
|
||||
*/
|
||||
public static long mix64(long z) {
|
||||
z = (z ^ (z >>> 32)) * 0x4cd6944c5cc20b6dL;
|
||||
z = (z ^ (z >>> 29)) * 0xfc12c5b19d3259e9L;
|
||||
return z ^ (z >>> 32);
|
||||
}
|
||||
|
||||
/*
|
||||
* Golden ratio bit mixers.
|
||||
*/
|
||||
|
||||
private static final int PHI_C32 = 0x9e3779b9;
|
||||
private static final long PHI_C64 = 0x9e3779b97f4a7c15L;
|
||||
|
||||
public static int mixPhi(byte k) {
|
||||
final int h = k * PHI_C32;
|
||||
return h ^ (h >>> 16);
|
||||
}
|
||||
|
||||
public static int mixPhi(char k) {
|
||||
final int h = k * PHI_C32;
|
||||
return h ^ (h >>> 16);
|
||||
}
|
||||
|
||||
public static int mixPhi(short k) {
|
||||
final int h = k * PHI_C32;
|
||||
return h ^ (h >>> 16);
|
||||
}
|
||||
|
||||
public static int mixPhi(int k) {
|
||||
final int h = k * PHI_C32;
|
||||
return h ^ (h >>> 16);
|
||||
}
|
||||
|
||||
public static int mixPhi(float k) {
|
||||
final int h = Float.floatToIntBits(k) * PHI_C32;
|
||||
return h ^ (h >>> 16);
|
||||
}
|
||||
|
||||
public static int mixPhi(double k) {
|
||||
final long h = Double.doubleToLongBits(k) * PHI_C64;
|
||||
return (int) (h ^ (h >>> 32));
|
||||
}
|
||||
|
||||
public static int mixPhi(long k) {
|
||||
final long h = k * PHI_C64;
|
||||
return (int) (h ^ (h >>> 32));
|
||||
}
|
||||
|
||||
public static int mixPhi(Object k) {
|
||||
final int h = (k == null ? 0 : k.hashCode() * PHI_C32);
|
||||
return h ^ (h >>> 16);
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
/** A variety of high efficiency bit twiddling routines. */
|
||||
final class BitUtil {
|
||||
private BitUtil() {
|
||||
} // no instance
|
||||
|
||||
// The pop methods used to rely on bit-manipulation tricks for speed but it
|
||||
// turns out that it is faster to use the Long.bitCount method (which is an
|
||||
// intrinsic since Java 6u18) in a naive loop, see LUCENE-2221
|
||||
|
||||
/** Returns the number of set bits in an array of longs. */
|
||||
public static long pop_array(long[] arr, int wordOffset, int numWords) {
|
||||
long popCount = 0;
|
||||
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
|
||||
popCount += Long.bitCount(arr[i]);
|
||||
}
|
||||
return popCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the popcount or cardinality of the two sets after an intersection.
|
||||
* Neither array is modified.
|
||||
*/
|
||||
public static long pop_intersect(long[] arr1, long[] arr2, int wordOffset, int numWords) {
|
||||
long popCount = 0;
|
||||
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
|
||||
popCount += Long.bitCount(arr1[i] & arr2[i]);
|
||||
}
|
||||
return popCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the popcount or cardinality of the union of two sets. Neither array
|
||||
* is modified.
|
||||
*/
|
||||
public static long pop_union(long[] arr1, long[] arr2, int wordOffset, int numWords) {
|
||||
long popCount = 0;
|
||||
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
|
||||
popCount += Long.bitCount(arr1[i] | arr2[i]);
|
||||
}
|
||||
return popCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the popcount or cardinality of A & ~B. Neither array is modified.
|
||||
*/
|
||||
public static long pop_andnot(long[] arr1, long[] arr2, int wordOffset, int numWords) {
|
||||
long popCount = 0;
|
||||
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
|
||||
popCount += Long.bitCount(arr1[i] & ~arr2[i]);
|
||||
}
|
||||
return popCount;
|
||||
}
|
||||
|
||||
/** Returns the popcount or cardinality of A ^ B Neither array is modified. */
|
||||
public static long pop_xor(long[] arr1, long[] arr2, int wordOffset, int numWords) {
|
||||
long popCount = 0;
|
||||
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
|
||||
popCount += Long.bitCount(arr1[i] ^ arr2[i]);
|
||||
}
|
||||
return popCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the next highest power of two, or the current value if it's already a
|
||||
* power of two or zero
|
||||
*/
|
||||
public static int nextHighestPowerOfTwo(int v) {
|
||||
v--;
|
||||
v |= v >> 1;
|
||||
v |= v >> 2;
|
||||
v |= v >> 4;
|
||||
v |= v >> 8;
|
||||
v |= v >> 16;
|
||||
v++;
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the next highest power of two, or the current value if it's already a
|
||||
* power of two or zero
|
||||
*/
|
||||
public static long nextHighestPowerOfTwo(long v) {
|
||||
v--;
|
||||
v |= v >> 1;
|
||||
v |= v >> 2;
|
||||
v |= v >> 4;
|
||||
v |= v >> 8;
|
||||
v |= v >> 16;
|
||||
v |= v >> 32;
|
||||
v++;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* Array resizing proportional to the current buffer size, optionally kept
|
||||
* within the given minimum and maximum growth limits. Java's {@link ArrayList}
|
||||
* uses:
|
||||
*
|
||||
* <pre>
|
||||
* minGrow = 1
|
||||
* maxGrow = Integer.MAX_VALUE (unbounded)
|
||||
* growRatio = 1.5f
|
||||
* </pre>
|
||||
*/
|
||||
public final class BoundedProportionalArraySizingStrategy implements ArraySizingStrategy {
|
||||
|
||||
/**
|
||||
* Instance of {@link BoundedProportionalArraySizingStrategy} with default
|
||||
* values.
|
||||
*/
|
||||
public static final BoundedProportionalArraySizingStrategy DEFAULT_INSTANCE = new BoundedProportionalArraySizingStrategy();
|
||||
|
||||
/**
|
||||
* Maximum allocable array length (approximately the largest positive integer
|
||||
* decreased by the array's object header).
|
||||
*/
|
||||
public static final int MAX_ARRAY_LENGTH = Integer.MAX_VALUE - /* aligned array header + slack */ 32;
|
||||
|
||||
/** Minimum grow count. */
|
||||
public static final int DEFAULT_MIN_GROW_COUNT = 10;
|
||||
|
||||
/** Maximum grow count (unbounded). */
|
||||
public static final int DEFAULT_MAX_GROW_COUNT = MAX_ARRAY_LENGTH;
|
||||
|
||||
/** Default resize is by half the current buffer's size. */
|
||||
public static final float DEFAULT_GROW_RATIO = 1.5f;
|
||||
|
||||
/** Minimum number of elements to grow, if limit exceeded. */
|
||||
public final int minGrowCount;
|
||||
|
||||
/** Maximum number of elements to grow, if limit exceeded. */
|
||||
public final int maxGrowCount;
|
||||
|
||||
/**
|
||||
* The current buffer length is multiplied by this ratio to get the first
|
||||
* estimate for the new size. To double the size of the current buffer, for
|
||||
* example, set to <code>2</code>.
|
||||
*/
|
||||
public final float growRatio;
|
||||
|
||||
/** Create the default sizing strategy. */
|
||||
public BoundedProportionalArraySizingStrategy() {
|
||||
this(DEFAULT_MIN_GROW_COUNT, DEFAULT_MAX_GROW_COUNT, DEFAULT_GROW_RATIO);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the sizing strategy with custom policies.
|
||||
*
|
||||
* @param minGrow Minimum number of elements to grow by when expanding.
|
||||
* @param maxGrow Maximum number of elements to grow by when expanding.
|
||||
* @param ratio The ratio of expansion compared to the previous buffer size.
|
||||
*/
|
||||
public BoundedProportionalArraySizingStrategy(int minGrow, int maxGrow, float ratio) {
|
||||
assert minGrow >= 1 : "Min grow must be >= 1.";
|
||||
assert maxGrow >= minGrow : "Max grow must be >= min grow.";
|
||||
assert ratio >= 1f : "Growth ratio must be >= 1 (was " + ratio + ").";
|
||||
|
||||
this.minGrowCount = minGrow;
|
||||
this.maxGrowCount = maxGrow;
|
||||
this.growRatio = ratio - 1.0f;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grow according to {@link #growRatio}, {@link #minGrowCount} and
|
||||
* {@link #maxGrowCount}.
|
||||
*
|
||||
* @param currentBufferLength The current length of the buffer.
|
||||
* @param elementsCount The number of elements stored in the buffer.
|
||||
* @param expectedAdditions The number of expected additions to the buffer.
|
||||
* @return New buffer size.
|
||||
*/
|
||||
public int grow(int currentBufferLength, int elementsCount, int expectedAdditions) {
|
||||
long growBy = (long) ((long) currentBufferLength * growRatio);
|
||||
growBy = Math.max(growBy, minGrowCount);
|
||||
growBy = Math.min(growBy, maxGrowCount);
|
||||
long growTo = Math.min(MAX_ARRAY_LENGTH, growBy + currentBufferLength);
|
||||
long newSize = Math.max((long) elementsCount + expectedAdditions, growTo);
|
||||
|
||||
if (newSize > MAX_ARRAY_LENGTH) {
|
||||
throw new BufferAllocationException(
|
||||
"Java array size exceeded (current length: %d, elements: %d, expected additions: %d)",
|
||||
currentBufferLength, elementsCount, expectedAdditions);
|
||||
}
|
||||
|
||||
return (int) newSize;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long ramBytesAllocated() {
|
||||
// int: minGrowCount, maxGrowCount
|
||||
// float: growRatio
|
||||
return RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + Integer.BYTES * 2 + Float.BYTES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long ramBytesUsed() {
|
||||
return ramBytesAllocated();
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import java.util.IllegalFormatException;
|
||||
import java.util.Locale;
|
||||
|
||||
public class BufferAllocationException extends RuntimeException {
|
||||
public BufferAllocationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public BufferAllocationException(String message, Object... args) {
|
||||
this(message, null, args);
|
||||
}
|
||||
|
||||
public BufferAllocationException(String message, Throwable t, Object... args) {
|
||||
super(formatMessage(message, t, args), t);
|
||||
}
|
||||
|
||||
private static String formatMessage(String message, Throwable t, Object... args) {
|
||||
try {
|
||||
return String.format(Locale.ROOT, message, args);
|
||||
} catch (IllegalFormatException e) {
|
||||
BufferAllocationException substitute = new BufferAllocationException(
|
||||
message + " [ILLEGAL FORMAT, ARGS SUPPRESSED]");
|
||||
if (t != null) {
|
||||
substitute.addSuppressed(t);
|
||||
}
|
||||
substitute.addSuppressed(e);
|
||||
throw substitute;
|
||||
}
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
/**
|
||||
* Constants used as defaults in containers.
|
||||
*
|
||||
* @see HashContainers
|
||||
*/
|
||||
public final class Containers {
|
||||
/** The default number of expected elements for containers. */
|
||||
public static final int DEFAULT_EXPECTED_ELEMENTS = 4;
|
||||
|
||||
/**
|
||||
* External initial seed value. We do not care about multiple assignments so not
|
||||
* volatile.
|
||||
*
|
||||
* @see #randomSeed64()
|
||||
*/
|
||||
private static String testsSeedProperty;
|
||||
|
||||
/** Unique marker for {@link #testsSeedProperty}. */
|
||||
private static final String NOT_AVAILABLE = new String();
|
||||
|
||||
private Containers() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides a (possibly) random initial seed for randomized stuff.
|
||||
*
|
||||
* <p>
|
||||
* If <code>tests.seed</code> property is available and accessible, the returned
|
||||
* value will be derived from the value of that property and will be constant to
|
||||
* ensure reproducibility in presence of the randomized testing package.
|
||||
*
|
||||
* @see "https://github.com/carrotsearch/randomizedtesting"
|
||||
*/
|
||||
public static long randomSeed64() {
|
||||
if (testsSeedProperty == null) {
|
||||
testsSeedProperty = System.getProperty("tests.seed", NOT_AVAILABLE);
|
||||
}
|
||||
|
||||
long initialSeed;
|
||||
if (testsSeedProperty != NOT_AVAILABLE) {
|
||||
initialSeed = testsSeedProperty.hashCode();
|
||||
} else {
|
||||
// Mix something that is changing over time (nanoTime)
|
||||
// ... with something that is thread-local and relatively unique
|
||||
// even for very short time-spans (new Object's address from a TLAB).
|
||||
initialSeed = System.nanoTime() ^ System.identityHashCode(new Object());
|
||||
}
|
||||
return BitMixer.mix64(initialSeed);
|
||||
}
|
||||
|
||||
/** Reset state for tests. */
|
||||
static void test$reset() {
|
||||
testsSeedProperty = null;
|
||||
}
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.HPPC;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.IntContainer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.IntIndexedContainer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.IntIntAssociativeContainer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.IntIntMap;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.IntObjectAssociativeContainer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.IntObjectMap;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.IntSet;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.ObjectContainer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.ObjectIndexedContainer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.ObjectIntAssociativeContainer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.ObjectIntMap;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.ObjectObjectAssociativeContainer;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.ObjectObjectMap;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.ObjectSet;
|
||||
|
||||
public final class HPPCFactory implements HPPC {
|
||||
|
||||
public static final HPPCFactory INSTANCE = new HPPCFactory();
|
||||
|
||||
private HPPCFactory() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getDefaultExpectedElements() {
|
||||
return Containers.DEFAULT_EXPECTED_ELEMENTS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntIndexedContainer createIntArrayList() {
|
||||
return new IntArrayList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntIndexedContainer createIntArrayList(int expectedElements) {
|
||||
return new IntArrayList(expectedElements);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntIndexedContainer createIntArrayList(IntContainer source) {
|
||||
return new IntArrayList(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntSet createIntHashSet() {
|
||||
return new IntHashSet();
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntSet createIntHashSet(int expectedElements) {
|
||||
return new IntHashSet(expectedElements);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntSet createIntHashSet(IntContainer source) {
|
||||
return new IntHashSet(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ObjectIndexedContainer<T> createObjectArrayList() {
|
||||
return new ObjectArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ObjectIndexedContainer<T> createObjectArrayList(int expectedElements) {
|
||||
return new ObjectArrayList<>(expectedElements);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ObjectIndexedContainer<T> createObjectArrayList(ObjectContainer<? extends T> source) {
|
||||
return new ObjectArrayList<>(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ObjectSet<T> createObjectHashSet() {
|
||||
return new ObjectHashSet<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ObjectSet<T> createObjectHashSet(int expectedElements) {
|
||||
return new ObjectHashSet<>(expectedElements);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ObjectSet<T> createObjectHashSet(ObjectContainer<? extends T> source) {
|
||||
return new ObjectHashSet<>(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ObjectSet<T> createObjectIdentityHashSet() {
|
||||
return new ObjectIdentityHashSet<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ObjectSet<T> createObjectIdentityHashSet(int expectedElements) {
|
||||
return new ObjectIdentityHashSet<>(expectedElements);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> ObjectSet<T> createObjectIdentityHashSet(ObjectContainer<? extends T> source) {
|
||||
return new ObjectIdentityHashSet<>(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> IntObjectMap<V> createIntObjectHashMap() {
|
||||
return new IntObjectHashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> IntObjectMap<V> createIntObjectHashMap(int expectedElements) {
|
||||
return new IntObjectHashMap<>(expectedElements);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> IntObjectMap<V> createIntObjectHashMap(IntObjectAssociativeContainer<? extends V> source) {
|
||||
return new IntObjectHashMap<>(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K> ObjectIntMap<K> createObjectIntHashMap() {
|
||||
return new ObjectIntHashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K> ObjectIntMap<K> createObjectIntHashMap(int expectedElements) {
|
||||
return new ObjectIntHashMap<>(expectedElements);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K> ObjectIntMap<K> createObjectIntHashMap(ObjectIntAssociativeContainer<? extends K> source) {
|
||||
return new ObjectIntHashMap<>(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K> ObjectIntMap<K> createObjectIntIdentityHashMap() {
|
||||
return new ObjectIntIdentityHashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K> ObjectIntMap<K> createObjectIntIdentityHashMap(int expectedElements) {
|
||||
return new ObjectIntIdentityHashMap<>(expectedElements);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K> ObjectIntMap<K> createObjectIntIdentityHashMap(ObjectIntAssociativeContainer<? extends K> source) {
|
||||
return new ObjectIntIdentityHashMap<>(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntIntMap createIntIntHashMap() {
|
||||
return new IntIntHashMap();
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntIntMap createIntIntHashMap(int expectedElements) {
|
||||
return new IntIntHashMap(expectedElements);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntIntMap createIntIntHashMap(IntIntAssociativeContainer source) {
|
||||
return new IntIntHashMap(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K, V> ObjectObjectMap<K, V> createObjectObjectHashMap() {
|
||||
return new ObjectObjectHashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K, V> ObjectObjectMap<K, V> createObjectObjectHashMap(int expectedElements) {
|
||||
return new ObjectObjectHashMap<>(expectedElements);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K, V> ObjectObjectMap<K, V> createObjectObjectHashMap(
|
||||
ObjectObjectAssociativeContainer<? extends K, ? extends V> source) {
|
||||
return new ObjectObjectHashMap<>(source);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K, V> ObjectObjectMap<K, V> createObjectObjectIdentityHashMap() {
|
||||
return new ObjectObjectIdentityHashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K, V> ObjectObjectMap<K, V> createObjectObjectIdentityHashMap(int expectedElements) {
|
||||
return new ObjectObjectIdentityHashMap<>(expectedElements);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <K, V> ObjectObjectMap<K, V> createObjectObjectIdentityHashMap(
|
||||
ObjectObjectAssociativeContainer<? extends K, ? extends V> source) {
|
||||
return new ObjectObjectIdentityHashMap<>(source);
|
||||
}
|
||||
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public final class HashContainers {
|
||||
/**
|
||||
* Maximum array size for hash containers (power-of-two and still allocable in
|
||||
* Java, not a negative int).
|
||||
*/
|
||||
public static final int MAX_HASH_ARRAY_LENGTH = 0x80000000 >>> 1;
|
||||
|
||||
/** Minimum hash buffer size. */
|
||||
public static final int MIN_HASH_ARRAY_LENGTH = 4;
|
||||
|
||||
/** Default load factor. */
|
||||
public static final float DEFAULT_LOAD_FACTOR = 0.75f;
|
||||
|
||||
/** Minimal sane load factor (99 empty slots per 100). */
|
||||
public static final float MIN_LOAD_FACTOR = 1 / 100.0f;
|
||||
|
||||
/** Maximum sane load factor (1 empty slot per 100). */
|
||||
public static final float MAX_LOAD_FACTOR = 99 / 100.0f;
|
||||
|
||||
private static final AtomicInteger ITERATION_SEED = new AtomicInteger();
|
||||
|
||||
/**
|
||||
* Compute and return the maximum number of elements (inclusive) that can be
|
||||
* stored in a hash container for a given load factor.
|
||||
*/
|
||||
public static int maxElements(double loadFactor) {
|
||||
checkLoadFactor(loadFactor, 0, 1);
|
||||
return expandAtCount(MAX_HASH_ARRAY_LENGTH, loadFactor) - 1;
|
||||
}
|
||||
|
||||
/** */
|
||||
static int minBufferSize(int elements, double loadFactor) {
|
||||
if (elements < 0) {
|
||||
throw new IllegalArgumentException("Number of elements must be >= 0: " + elements);
|
||||
}
|
||||
|
||||
long length = (long) Math.ceil(elements / loadFactor);
|
||||
if (length == elements) {
|
||||
length++;
|
||||
}
|
||||
length = Math.max(MIN_HASH_ARRAY_LENGTH, BitUtil.nextHighestPowerOfTwo(length));
|
||||
|
||||
if (length > MAX_HASH_ARRAY_LENGTH) {
|
||||
throw new BufferAllocationException(
|
||||
"Maximum array size exceeded for this load factor (elements: %d, load factor: %f)", elements,
|
||||
loadFactor);
|
||||
}
|
||||
|
||||
return (int) length;
|
||||
}
|
||||
|
||||
/** */
|
||||
static int nextBufferSize(int arraySize, int elements, double loadFactor) {
|
||||
assert checkPowerOfTwo(arraySize);
|
||||
if (arraySize == MAX_HASH_ARRAY_LENGTH) {
|
||||
throw new BufferAllocationException(
|
||||
"Maximum array size exceeded for this load factor (elements: %d, load factor: %f)", elements,
|
||||
loadFactor);
|
||||
}
|
||||
|
||||
return (int) arraySize << 1;
|
||||
}
|
||||
|
||||
/** */
|
||||
static int expandAtCount(int arraySize, double loadFactor) {
|
||||
assert checkPowerOfTwo(arraySize);
|
||||
// Take care of hash container invariant (there has to be at least one empty
|
||||
// slot to ensure
|
||||
// the lookup loop finds either the element or an empty slot).
|
||||
return Math.min(arraySize - 1, (int) Math.ceil(arraySize * loadFactor));
|
||||
}
|
||||
|
||||
/** */
|
||||
static void checkLoadFactor(double loadFactor, double minAllowedInclusive, double maxAllowedInclusive) {
|
||||
if (loadFactor < minAllowedInclusive || loadFactor > maxAllowedInclusive) {
|
||||
throw new BufferAllocationException("The load factor should be in range [%.2f, %.2f]: %f",
|
||||
minAllowedInclusive, maxAllowedInclusive, loadFactor);
|
||||
}
|
||||
}
|
||||
|
||||
/** */
|
||||
static boolean checkPowerOfTwo(int arraySize) {
|
||||
// These are internals, we can just assert without retrying.
|
||||
assert arraySize > 1;
|
||||
assert BitUtil.nextHighestPowerOfTwo(arraySize) == arraySize;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides the next hash iteration order seed. It is simply an incrementing
|
||||
* atomic counter.
|
||||
*/
|
||||
static int nextIterationSeed() {
|
||||
return ITERATION_SEED.incrementAndGet();
|
||||
}
|
||||
|
||||
/** Computes a hash iteration order increment based on the provided seed. */
|
||||
static int iterationIncrement(int seed) {
|
||||
return 29 + ((seed & 7) << 1); // Small odd integer.
|
||||
}
|
||||
}
|
||||
+597
@@ -0,0 +1,597 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.*;
|
||||
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.Containers.*;
|
||||
|
||||
/** An array-backed list of ints. */
|
||||
public class IntArrayList extends AbstractIntCollection
|
||||
implements IntIndexedContainer, Preallocable, Cloneable, Accountable {
|
||||
/** An immutable empty buffer (array). */
|
||||
public static final int[] EMPTY_ARRAY = new int[0];
|
||||
|
||||
;
|
||||
|
||||
/** Reuse the same strategy instance. */
|
||||
private static final BoundedProportionalArraySizingStrategy DEFAULT_SIZING_STRATEGY = BoundedProportionalArraySizingStrategy.DEFAULT_INSTANCE;
|
||||
|
||||
/**
|
||||
* Internal array for storing the list. The array may be larger than the current
|
||||
* size ({@link #size()}).
|
||||
*/
|
||||
public int[] buffer = EMPTY_ARRAY;
|
||||
|
||||
/** Current number of elements stored in {@link #buffer}. */
|
||||
public int elementsCount;
|
||||
|
||||
/** Buffer resizing strategy. */
|
||||
protected final ArraySizingStrategy resizer;
|
||||
|
||||
/** New instance with sane defaults. */
|
||||
public IntArrayList() {
|
||||
this(DEFAULT_EXPECTED_ELEMENTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with sane defaults.
|
||||
*
|
||||
* @param expectedElements The expected number of elements guaranteed not to
|
||||
* cause buffer expansion (inclusive).
|
||||
*/
|
||||
public IntArrayList(int expectedElements) {
|
||||
this(expectedElements, DEFAULT_SIZING_STRATEGY);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with sane defaults.
|
||||
*
|
||||
* @param expectedElements The expected number of elements guaranteed not to
|
||||
* cause buffer expansion (inclusive).
|
||||
* @param resizer Underlying buffer sizing strategy.
|
||||
*/
|
||||
public IntArrayList(int expectedElements, ArraySizingStrategy resizer) {
|
||||
assert resizer != null;
|
||||
this.resizer = resizer;
|
||||
buffer = Arrays.copyOf(buffer, expectedElements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new list from the elements of another container in its iteration
|
||||
* order.
|
||||
*/
|
||||
public IntArrayList(IntContainer container) {
|
||||
this(container.size());
|
||||
addAll(container);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void add(int e1) {
|
||||
ensureBufferSpace(1);
|
||||
buffer[elementsCount++] = e1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends two elements at the end of the list. To add more than two elements,
|
||||
* use <code>add
|
||||
* </code> (vararg-version) or access the buffer directly (tight loop).
|
||||
*/
|
||||
public void add(int e1, int e2) {
|
||||
ensureBufferSpace(2);
|
||||
buffer[elementsCount++] = e1;
|
||||
buffer[elementsCount++] = e2;
|
||||
}
|
||||
|
||||
/** Add all elements from a range of given array to the list. */
|
||||
public void add(int[] elements, int start, int length) {
|
||||
assert length >= 0 : "Length must be >= 0";
|
||||
|
||||
ensureBufferSpace(length);
|
||||
System.arraycopy(elements, start, buffer, elementsCount, length);
|
||||
elementsCount += length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vararg-signature method for adding elements at the end of the list.
|
||||
*
|
||||
* <p>
|
||||
* <b>This method is handy, but costly if used in tight loops (anonymous array
|
||||
* passing)</b>
|
||||
*/
|
||||
public final void add(int... elements) {
|
||||
add(elements, 0, elements.length);
|
||||
}
|
||||
|
||||
/** Adds all elements from another container. */
|
||||
public int addAll(IntContainer container) {
|
||||
final int size = container.size();
|
||||
ensureBufferSpace(size);
|
||||
|
||||
for (IntCursor cursor : container) {
|
||||
add(cursor.value);
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
/** Adds all elements from another iterable. */
|
||||
public int addAll(Iterable<? extends IntCursor> iterable) {
|
||||
int size = 0;
|
||||
for (IntCursor cursor : iterable) {
|
||||
add(cursor.value);
|
||||
size++;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void insert(int index, int e1) {
|
||||
assert (index >= 0 && index <= size()) : "Index " + index + " out of bounds [" + 0 + ", " + size() + "].";
|
||||
|
||||
ensureBufferSpace(1);
|
||||
System.arraycopy(buffer, index, buffer, index + 1, elementsCount - index);
|
||||
buffer[index] = e1;
|
||||
elementsCount++;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int get(int index) {
|
||||
assert (index >= 0 && index < size()) : "Index " + index + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
|
||||
return buffer[index];
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int set(int index, int e1) {
|
||||
assert (index >= 0 && index < size()) : "Index " + index + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
|
||||
final int v = buffer[index];
|
||||
buffer[index] = e1;
|
||||
return v;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeAt(int index) {
|
||||
assert (index >= 0 && index < size()) : "Index " + index + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
|
||||
final int v = buffer[index];
|
||||
System.arraycopy(buffer, index + 1, buffer, index, --elementsCount - index);
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeLast() {
|
||||
assert elementsCount > 0;
|
||||
|
||||
final int v = buffer[--elementsCount];
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void removeRange(int fromIndex, int toIndex) {
|
||||
assert (fromIndex >= 0 && fromIndex <= size())
|
||||
: "Index " + fromIndex + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
assert (toIndex >= 0 && toIndex <= size()) : "Index " + toIndex + " out of bounds [" + 0 + ", " + size() + "].";
|
||||
assert fromIndex <= toIndex : "fromIndex must be <= toIndex: " + fromIndex + ", " + toIndex;
|
||||
|
||||
System.arraycopy(buffer, toIndex, buffer, fromIndex, elementsCount - toIndex);
|
||||
final int count = toIndex - fromIndex;
|
||||
elementsCount -= count;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean removeElement(int e1) {
|
||||
return removeFirst(e1) != -1;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeFirst(int e1) {
|
||||
final int index = indexOf(e1);
|
||||
if (index >= 0)
|
||||
removeAt(index);
|
||||
return index;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeLast(int e1) {
|
||||
final int index = lastIndexOf(e1);
|
||||
if (index >= 0)
|
||||
removeAt(index);
|
||||
return index;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeAll(int e1) {
|
||||
int to = 0;
|
||||
for (int from = 0; from < elementsCount; from++) {
|
||||
if (((e1) == (buffer[from]))) {
|
||||
continue;
|
||||
}
|
||||
if (to != from) {
|
||||
buffer[to] = buffer[from];
|
||||
}
|
||||
to++;
|
||||
}
|
||||
final int deleted = elementsCount - to;
|
||||
this.elementsCount = to;
|
||||
|
||||
return deleted;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean contains(int e1) {
|
||||
return indexOf(e1) >= 0;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int indexOf(int e1) {
|
||||
for (int i = 0; i < elementsCount; i++) {
|
||||
if (((e1) == (buffer[i]))) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int lastIndexOf(int e1) {
|
||||
for (int i = elementsCount - 1; i >= 0; i--) {
|
||||
if (((e1) == (buffer[i]))) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return elementsCount == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure this container can hold at least the given number of elements without
|
||||
* resizing its buffers.
|
||||
*
|
||||
* @param expectedElements The total number of elements, inclusive.
|
||||
*/
|
||||
@Override
|
||||
public void ensureCapacity(int expectedElements) {
|
||||
final int bufferLen = (buffer == null ? 0 : buffer.length);
|
||||
if (expectedElements > bufferLen) {
|
||||
ensureBufferSpace(expectedElements - size());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the internal buffer has enough free slots to store
|
||||
* <code>expectedAdditions</code>. Increases internal buffer size if needed.
|
||||
*/
|
||||
protected void ensureBufferSpace(int expectedAdditions) {
|
||||
final int bufferLen = (buffer == null ? 0 : buffer.length);
|
||||
if (elementsCount + expectedAdditions > bufferLen) {
|
||||
final int newSize = resizer.grow(bufferLen, elementsCount, expectedAdditions);
|
||||
assert newSize >= elementsCount + expectedAdditions : "Resizer failed to" + " return sensible new size: "
|
||||
+ newSize + " <= " + (elementsCount + expectedAdditions);
|
||||
|
||||
this.buffer = Arrays.copyOf(buffer, newSize);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncate or expand the list to the new size. If the list is truncated, the
|
||||
* buffer will not be reallocated (use {@link #trimToSize()} if you need a
|
||||
* truncated buffer), but the truncated values will be reset to the default
|
||||
* value (zero). If the list is expanded, the elements beyond the current size
|
||||
* are initialized with JVM-defaults (zero or <code>null</code> values).
|
||||
*/
|
||||
public void resize(int newSize) {
|
||||
if (newSize <= buffer.length) {
|
||||
if (newSize < elementsCount) {
|
||||
Arrays.fill(buffer, newSize, elementsCount, 0);
|
||||
} else {
|
||||
Arrays.fill(buffer, elementsCount, newSize, 0);
|
||||
}
|
||||
} else {
|
||||
ensureCapacity(newSize);
|
||||
}
|
||||
this.elementsCount = newSize;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int size() {
|
||||
return elementsCount;
|
||||
}
|
||||
|
||||
/** Trim the internal buffer to the current size. */
|
||||
public void trimToSize() {
|
||||
if (size() != this.buffer.length) {
|
||||
this.buffer = toArray();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the number of stored elements to zero. Releases and initializes the
|
||||
* internal storage array to default values. To clear the list without cleaning
|
||||
* the buffer, simply set the {@link #elementsCount} field to zero.
|
||||
*/
|
||||
@Override
|
||||
public void clear() {
|
||||
Arrays.fill(buffer, 0, elementsCount, 0);
|
||||
this.elementsCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the number of stored elements to zero and releases the internal storage
|
||||
* array.
|
||||
*/
|
||||
@Override
|
||||
public void release() {
|
||||
this.buffer = EMPTY_ARRAY;
|
||||
this.elementsCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* <p>
|
||||
* The returned array is sized to match exactly the number of elements of the
|
||||
* stack.
|
||||
*/
|
||||
@Override
|
||||
public int[] toArray() {
|
||||
|
||||
return Arrays.copyOf(buffer, elementsCount);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntStream stream() {
|
||||
|
||||
return Arrays.stream(buffer, 0, size());
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public IntIndexedContainer sort() {
|
||||
Arrays.sort(buffer, 0, elementsCount);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public IntIndexedContainer reverse() {
|
||||
for (int i = 0, mid = elementsCount >> 1, j = elementsCount - 1; i < mid; i++, j--) {
|
||||
int tmp = buffer[i];
|
||||
buffer[i] = buffer[j];
|
||||
buffer[j] = tmp;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone this object. The returned clone will reuse the same hash function and
|
||||
* array resizing strategy.
|
||||
*/
|
||||
@Override
|
||||
public IntArrayList clone() {
|
||||
try {
|
||||
|
||||
final IntArrayList cloned = (IntArrayList) super.clone();
|
||||
cloned.buffer = buffer.clone();
|
||||
return cloned;
|
||||
} catch (CloneNotSupportedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int h = 1, max = elementsCount;
|
||||
for (int i = 0; i < max; i++) {
|
||||
h = 31 * h + BitMixer.mix(this.buffer[i]);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns <code>true</code> only if the other object is an instance of the same
|
||||
* class and with the same elements.
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return (this == obj) || (obj != null && getClass() == obj.getClass() && equalElements(getClass().cast(obj)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare index-aligned elements against another {@link IntIndexedContainer}.
|
||||
*/
|
||||
protected boolean equalElements(IntArrayList other) {
|
||||
int max = size();
|
||||
if (other.size() != max) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < max; i++) {
|
||||
if (!((get(i)) == (other.get(i)))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long ramBytesAllocated() {
|
||||
// int: elementsCount
|
||||
return RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + Integer.BYTES + resizer.ramBytesAllocated()
|
||||
+ RamUsageEstimator.shallowSizeOfArray(buffer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long ramBytesUsed() {
|
||||
// int: elementsCount
|
||||
return RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + Integer.BYTES + resizer.ramBytesUsed()
|
||||
+ RamUsageEstimator.shallowUsedSizeOfArray(buffer, elementsCount);
|
||||
}
|
||||
|
||||
/** An iterator implementation for {@link IntArrayList#iterator}. */
|
||||
static final class ValueIterator extends AbstractIterator<IntCursor> {
|
||||
private final IntCursor cursor;
|
||||
|
||||
private final int[] buffer;
|
||||
private final int size;
|
||||
|
||||
public ValueIterator(int[] buffer, int size) {
|
||||
this.cursor = new IntCursor();
|
||||
this.cursor.index = -1;
|
||||
this.size = size;
|
||||
this.buffer = buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IntCursor fetch() {
|
||||
if (cursor.index + 1 == size)
|
||||
return done();
|
||||
|
||||
cursor.value = buffer[++cursor.index];
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public Iterator<IntCursor> iterator() {
|
||||
return new ValueIterator(buffer, size());
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public <T extends IntProcedure> T forEach(T procedure) {
|
||||
return forEach(procedure, 0, size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies <code>procedure</code> to a slice of the list,
|
||||
* <code>fromIndex</code>, inclusive, to <code>toIndex</code>, exclusive.
|
||||
*/
|
||||
public <T extends IntProcedure> T forEach(T procedure, int fromIndex, final int toIndex) {
|
||||
assert (fromIndex >= 0 && fromIndex <= size())
|
||||
: "Index " + fromIndex + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
|
||||
assert (toIndex >= 0 && toIndex <= size()) : "Index " + toIndex + " out of bounds [" + 0 + ", " + size() + "].";
|
||||
|
||||
assert fromIndex <= toIndex : "fromIndex must be <= toIndex: " + fromIndex + ", " + toIndex;
|
||||
|
||||
final int[] buffer = this.buffer;
|
||||
for (int i = fromIndex; i < toIndex; i++) {
|
||||
procedure.apply(buffer[i]);
|
||||
}
|
||||
|
||||
return procedure;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeAll(IntPredicate predicate) {
|
||||
final int[] buffer = this.buffer;
|
||||
final int elementsCount = this.elementsCount;
|
||||
int to = 0;
|
||||
int from = 0;
|
||||
try {
|
||||
for (; from < elementsCount; from++) {
|
||||
if (predicate.apply(buffer[from])) {
|
||||
buffer[from] = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (to != from) {
|
||||
buffer[to] = buffer[from];
|
||||
buffer[from] = 0;
|
||||
}
|
||||
to++;
|
||||
}
|
||||
} finally {
|
||||
// Keep the list in a consistent state, even if the predicate throws an
|
||||
// exception.
|
||||
for (; from < elementsCount; from++) {
|
||||
if (to != from) {
|
||||
buffer[to] = buffer[from];
|
||||
buffer[from] = 0;
|
||||
}
|
||||
to++;
|
||||
}
|
||||
|
||||
this.elementsCount = to;
|
||||
}
|
||||
|
||||
return elementsCount - to;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public <T extends IntPredicate> T forEach(T predicate) {
|
||||
return forEach(predicate, 0, size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies <code>predicate</code> to a slice of the list,
|
||||
* <code>fromIndex</code>, inclusive, to <code>toIndex</code>, exclusive, or
|
||||
* until predicate returns <code>false</code>.
|
||||
*/
|
||||
public <T extends IntPredicate> T forEach(T predicate, int fromIndex, final int toIndex) {
|
||||
assert (fromIndex >= 0 && fromIndex <= size())
|
||||
: "Index " + fromIndex + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
assert (toIndex >= 0 && toIndex <= size()) : "Index " + toIndex + " out of bounds [" + 0 + ", " + size() + "].";
|
||||
assert fromIndex <= toIndex : "fromIndex must be <= toIndex: " + fromIndex + ", " + toIndex;
|
||||
|
||||
final int[] buffer = this.buffer;
|
||||
for (int i = fromIndex; i < toIndex; i++) {
|
||||
if (!predicate.apply(buffer[i]))
|
||||
break;
|
||||
}
|
||||
|
||||
return predicate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a list from a variable number of arguments or an array of
|
||||
* <code>int</code>. The elements are copied from the argument to the internal
|
||||
* buffer.
|
||||
*/
|
||||
public static IntArrayList from(int... elements) {
|
||||
final IntArrayList list = new IntArrayList(elements.length);
|
||||
list.add(elements);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
/**
|
||||
* Reused buffer visualization routines.
|
||||
*
|
||||
* @see IntSet#visualizeKeyDistribution(int)
|
||||
* @see IntVTypeMap#visualizeKeyDistribution(int)
|
||||
*/
|
||||
class IntBufferVisualizer {
|
||||
static String visualizeKeyDistribution(int[] buffer, int max, int characters) {
|
||||
final StringBuilder b = new StringBuilder();
|
||||
final char[] chars = ".123456789X".toCharArray();
|
||||
for (int i = 1, start = -1; i <= characters; i++) {
|
||||
int end = (int) ((long) i * max / characters);
|
||||
|
||||
if (start + 1 <= end) {
|
||||
int taken = 0;
|
||||
int slots = 0;
|
||||
for (int slot = start + 1; slot <= end; slot++, slots++) {
|
||||
if (!((buffer[slot]) == 0)) {
|
||||
taken++;
|
||||
}
|
||||
}
|
||||
b.append(chars[Math.min(chars.length - 1, taken * chars.length / slots)]);
|
||||
start = end;
|
||||
}
|
||||
}
|
||||
while (b.length() < characters) {
|
||||
b.append(' ');
|
||||
}
|
||||
return b.toString();
|
||||
}
|
||||
}
|
||||
+803
@@ -0,0 +1,803 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.*;
|
||||
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.Containers.*;
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.HashContainers.*;
|
||||
|
||||
/**
|
||||
* A hash set of <code>int</code>s, implemented using open addressing with
|
||||
* linear probing for collision resolution.
|
||||
*
|
||||
* @see <a href="{@docRoot}/overview-summary.html#interfaces">HPPC interfaces
|
||||
* diagram</a>
|
||||
*/
|
||||
public class IntHashSet extends AbstractIntCollection
|
||||
implements IntLookupContainer, IntSet, Preallocable, Cloneable, Accountable {
|
||||
/** The hash array holding keys. */
|
||||
public int[] keys;
|
||||
|
||||
/**
|
||||
* The number of stored keys (assigned key slots), excluding the special "empty"
|
||||
* key, if any.
|
||||
*
|
||||
* @see #size()
|
||||
* @see #hasEmptyKey
|
||||
*/
|
||||
protected int assigned;
|
||||
|
||||
/** Mask for slot scans in {@link #keys}. */
|
||||
protected int mask;
|
||||
|
||||
/** Expand (rehash) {@link #keys} when {@link #assigned} hits this value. */
|
||||
protected int resizeAt;
|
||||
|
||||
/** Special treatment for the "empty slot" key marker. */
|
||||
protected boolean hasEmptyKey;
|
||||
|
||||
/** The load factor for {@link #keys}. */
|
||||
protected double loadFactor;
|
||||
|
||||
/**
|
||||
* Seed used to ensure the hash iteration order is different from an iteration
|
||||
* to another.
|
||||
*/
|
||||
protected int iterationSeed;
|
||||
|
||||
/**
|
||||
* New instance with sane defaults.
|
||||
*
|
||||
* @see #IntHashSet(int, double)
|
||||
*/
|
||||
public IntHashSet() {
|
||||
this(DEFAULT_EXPECTED_ELEMENTS, DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with sane defaults.
|
||||
*
|
||||
* @see #IntHashSet(int, double)
|
||||
*/
|
||||
public IntHashSet(int expectedElements) {
|
||||
this(expectedElements, DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with the provided defaults.
|
||||
*
|
||||
* @param expectedElements The expected number of elements guaranteed not to
|
||||
* cause a rehash (inclusive).
|
||||
* @param loadFactor The load factor for internal buffers. Insane load
|
||||
* factors (zero, full capacity) are rejected by
|
||||
* {@link #verifyLoadFactor(double)}.
|
||||
*/
|
||||
public IntHashSet(int expectedElements, double loadFactor) {
|
||||
this.loadFactor = verifyLoadFactor(loadFactor);
|
||||
iterationSeed = HashContainers.nextIterationSeed();
|
||||
ensureCapacity(expectedElements);
|
||||
}
|
||||
|
||||
/** New instance copying elements from another {@link IntContainer}. */
|
||||
public IntHashSet(IntContainer container) {
|
||||
this(container.size());
|
||||
addAll(container);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean add(int key) {
|
||||
if (((key) == 0)) {
|
||||
assert ((keys[mask + 1]) == 0);
|
||||
boolean added = !hasEmptyKey;
|
||||
hasEmptyKey = true;
|
||||
return added;
|
||||
} else {
|
||||
final int[] keys = this.keys;
|
||||
final int mask = this.mask;
|
||||
int slot = hashKey(key) & mask;
|
||||
|
||||
int existing;
|
||||
while (!((existing = keys[slot]) == 0)) {
|
||||
if (((key) == (existing))) {
|
||||
return false;
|
||||
}
|
||||
slot = (slot + 1) & mask;
|
||||
}
|
||||
|
||||
if (assigned == resizeAt) {
|
||||
allocateThenInsertThenRehash(slot, key);
|
||||
} else {
|
||||
keys[slot] = key;
|
||||
}
|
||||
|
||||
assigned++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds all elements from the given list (vararg) to this set.
|
||||
*
|
||||
* @return Returns the number of elements actually added as a result of this
|
||||
* call (not previously present in the set).
|
||||
*/
|
||||
public final int addAll(int... elements) {
|
||||
ensureCapacity(elements.length);
|
||||
int count = 0;
|
||||
for (int e : elements) {
|
||||
if (add(e)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds all elements from the given {@link IntContainer} to this set.
|
||||
*
|
||||
* @return Returns the number of elements actually added as a result of this
|
||||
* call (not previously present in the set).
|
||||
*/
|
||||
public int addAll(IntContainer container) {
|
||||
ensureCapacity(container.size());
|
||||
return addAll((Iterable<? extends IntCursor>) container);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds all elements from the given iterable to this set.
|
||||
*
|
||||
* @return Returns the number of elements actually added as a result of this
|
||||
* call (not previously present in the set).
|
||||
*/
|
||||
public int addAll(Iterable<? extends IntCursor> iterable) {
|
||||
int count = 0;
|
||||
for (IntCursor cursor : iterable) {
|
||||
if (add(cursor.value)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int[] toArray() {
|
||||
|
||||
final int[] cloned = (new int[size()]);
|
||||
int j = 0;
|
||||
if (hasEmptyKey) {
|
||||
cloned[j++] = 0;
|
||||
}
|
||||
|
||||
final int[] keys = this.keys;
|
||||
int seed = nextIterationSeed();
|
||||
int inc = iterationIncrement(seed);
|
||||
for (int i = 0, mask = this.mask, slot = seed & mask; i <= mask; i++, slot = (slot + inc) & mask) {
|
||||
int existing;
|
||||
if (!((existing = keys[slot]) == 0)) {
|
||||
cloned[j++] = existing;
|
||||
}
|
||||
}
|
||||
|
||||
return cloned;
|
||||
}
|
||||
|
||||
/** An alias for the (preferred) {@link #removeAll}. */
|
||||
public boolean remove(int key) {
|
||||
if (((key) == 0)) {
|
||||
boolean hadEmptyKey = hasEmptyKey;
|
||||
hasEmptyKey = false;
|
||||
return hadEmptyKey;
|
||||
} else {
|
||||
final int[] keys = this.keys;
|
||||
final int mask = this.mask;
|
||||
int slot = hashKey(key) & mask;
|
||||
|
||||
int existing;
|
||||
while (!((existing = keys[slot]) == 0)) {
|
||||
if (((key) == (existing))) {
|
||||
shiftConflictingKeys(slot);
|
||||
return true;
|
||||
}
|
||||
slot = (slot + 1) & mask;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeAll(int key) {
|
||||
return remove(key) ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all keys present in a given container.
|
||||
*
|
||||
* @return Returns the number of elements actually removed as a result of this
|
||||
* call.
|
||||
*/
|
||||
public int removeAll(IntContainer other) {
|
||||
final int before = size();
|
||||
|
||||
// Try to iterate over the smaller set or over the container that isn't
|
||||
// implementing
|
||||
// efficient contains() lookup.
|
||||
|
||||
if (other.size() >= size() && other instanceof IntLookupContainer) {
|
||||
if (hasEmptyKey && other.contains(0)) {
|
||||
hasEmptyKey = false;
|
||||
}
|
||||
|
||||
final int[] keys = this.keys;
|
||||
for (int slot = 0, max = this.mask; slot <= max;) {
|
||||
int existing;
|
||||
if (!((existing = keys[slot]) == 0) && other.contains(existing)) {
|
||||
// Shift, do not increment slot.
|
||||
shiftConflictingKeys(slot);
|
||||
} else {
|
||||
slot++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (IntCursor c : other) {
|
||||
remove(c.value);
|
||||
}
|
||||
}
|
||||
|
||||
return before - size();
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeAll(IntPredicate predicate) {
|
||||
int before = size();
|
||||
|
||||
if (hasEmptyKey) {
|
||||
if (predicate.apply(0)) {
|
||||
hasEmptyKey = false;
|
||||
}
|
||||
}
|
||||
|
||||
final int[] keys = this.keys;
|
||||
for (int slot = 0, max = this.mask; slot <= max;) {
|
||||
int existing;
|
||||
if (!((existing = keys[slot]) == 0)) {
|
||||
if (predicate.apply(existing)) {
|
||||
shiftConflictingKeys(slot);
|
||||
continue; // Repeat the check for the same slot i (shifted).
|
||||
}
|
||||
}
|
||||
slot++;
|
||||
}
|
||||
|
||||
return before - size();
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean contains(int key) {
|
||||
if (((key) == 0)) {
|
||||
return hasEmptyKey;
|
||||
} else {
|
||||
final int[] keys = this.keys;
|
||||
final int mask = this.mask;
|
||||
int slot = hashKey(key) & mask;
|
||||
int existing;
|
||||
while (!((existing = keys[slot]) == 0)) {
|
||||
if (((key) == (existing))) {
|
||||
return true;
|
||||
}
|
||||
slot = (slot + 1) & mask;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void clear() {
|
||||
assigned = 0;
|
||||
hasEmptyKey = false;
|
||||
Arrays.fill(keys, 0);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void release() {
|
||||
assigned = 0;
|
||||
hasEmptyKey = false;
|
||||
keys = null;
|
||||
ensureCapacity(Containers.DEFAULT_EXPECTED_ELEMENTS);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure this container can hold at least the given number of elements without
|
||||
* resizing its buffers.
|
||||
*
|
||||
* @param expectedElements The total number of elements, inclusive.
|
||||
*/
|
||||
@Override
|
||||
public void ensureCapacity(int expectedElements) {
|
||||
if (expectedElements > resizeAt || keys == null) {
|
||||
final int[] prevKeys = this.keys;
|
||||
allocateBuffers(minBufferSize(expectedElements, loadFactor));
|
||||
if (prevKeys != null && !isEmpty()) {
|
||||
rehash(prevKeys);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int size() {
|
||||
return assigned + (hasEmptyKey ? 1 : 0);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int h = hasEmptyKey ? 0xDEADBEEF : 0;
|
||||
final int[] keys = this.keys;
|
||||
for (int slot = mask; slot >= 0; slot--) {
|
||||
int existing;
|
||||
if (!((existing = keys[slot]) == 0)) {
|
||||
h += BitMixer.mix(existing);
|
||||
}
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return (this == obj) || (obj != null && getClass() == obj.getClass() && sameKeys(getClass().cast(obj)));
|
||||
}
|
||||
|
||||
/** Return true if all keys of some other container exist in this container. */
|
||||
private boolean sameKeys(IntSet other) {
|
||||
if (other.size() != size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (IntCursor c : other) {
|
||||
if (!contains(c.value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public IntHashSet clone() {
|
||||
try {
|
||||
|
||||
IntHashSet cloned = (IntHashSet) super.clone();
|
||||
cloned.keys = keys.clone();
|
||||
cloned.hasEmptyKey = hasEmptyKey;
|
||||
cloned.iterationSeed = HashContainers.nextIterationSeed();
|
||||
return cloned;
|
||||
} catch (CloneNotSupportedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public Iterator<IntCursor> iterator() {
|
||||
return new EntryIterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long ramBytesAllocated() {
|
||||
// int: assigned, mask, keyMixer, resizeAt
|
||||
// double: loadFactor
|
||||
// boolean: hasEmptyKey
|
||||
return RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + 4 * Integer.BYTES + Double.BYTES + 1
|
||||
+ RamUsageEstimator.shallowSizeOfArray(keys);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long ramBytesUsed() {
|
||||
// int: assigned, mask, keyMixer, resizeAt
|
||||
// double: loadFactor
|
||||
// boolean: hasEmptyKey
|
||||
return RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + 4 * Integer.BYTES + Double.BYTES + 1
|
||||
+ RamUsageEstimator.shallowUsedSizeOfArray(keys, size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides the next iteration seed used to build the iteration starting slot
|
||||
* and offset increment. This method does not need to be synchronized, what
|
||||
* matters is that each thread gets a sequence of varying seeds.
|
||||
*/
|
||||
protected int nextIterationSeed() {
|
||||
return iterationSeed = BitMixer.mixPhi(iterationSeed);
|
||||
}
|
||||
|
||||
/** An iterator implementation for {@link #iterator}. */
|
||||
protected final class EntryIterator extends AbstractIterator<IntCursor> {
|
||||
private final IntCursor cursor;
|
||||
private final int increment;
|
||||
private int index;
|
||||
private int slot;
|
||||
|
||||
public EntryIterator() {
|
||||
cursor = new IntCursor();
|
||||
int seed = nextIterationSeed();
|
||||
increment = iterationIncrement(seed);
|
||||
slot = seed & mask;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IntCursor fetch() {
|
||||
final int mask = IntHashSet.this.mask;
|
||||
while (index <= mask) {
|
||||
int existing;
|
||||
index++;
|
||||
slot = (slot + increment) & mask;
|
||||
if (!((existing = keys[slot]) == 0)) {
|
||||
cursor.index = slot;
|
||||
cursor.value = existing;
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
|
||||
if (index == mask + 1 && hasEmptyKey) {
|
||||
cursor.index = index++;
|
||||
cursor.value = 0;
|
||||
return cursor;
|
||||
}
|
||||
|
||||
return done();
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public <T extends IntProcedure> T forEach(T procedure) {
|
||||
if (hasEmptyKey) {
|
||||
procedure.apply(0);
|
||||
}
|
||||
|
||||
final int[] keys = this.keys;
|
||||
int seed = nextIterationSeed();
|
||||
int inc = iterationIncrement(seed);
|
||||
for (int i = 0, mask = this.mask, slot = seed & mask; i <= mask; i++, slot = (slot + inc) & mask) {
|
||||
int existing;
|
||||
if (!((existing = keys[slot]) == 0)) {
|
||||
procedure.apply(existing);
|
||||
}
|
||||
}
|
||||
|
||||
return procedure;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public <T extends IntPredicate> T forEach(T predicate) {
|
||||
if (hasEmptyKey) {
|
||||
if (!predicate.apply(0)) {
|
||||
return predicate;
|
||||
}
|
||||
}
|
||||
|
||||
final int[] keys = this.keys;
|
||||
int seed = nextIterationSeed();
|
||||
int inc = iterationIncrement(seed);
|
||||
for (int i = 0, mask = this.mask, slot = seed & mask; i <= mask; i++, slot = (slot + inc) & mask) {
|
||||
int existing;
|
||||
if (!((existing = keys[slot]) == 0)) {
|
||||
if (!predicate.apply(existing)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return predicate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a set from a variable number of arguments or an array of
|
||||
* <code>int</code>. The elements are copied from the argument to the internal
|
||||
* buffer.
|
||||
*/
|
||||
public static IntHashSet from(int... elements) {
|
||||
final IntHashSet set = new IntHashSet(elements.length);
|
||||
set.addAll(elements);
|
||||
return set;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a hash code for the given key.
|
||||
*
|
||||
* <p>
|
||||
* The output from this function should evenly distribute keys across the entire
|
||||
* integer range.
|
||||
*/
|
||||
protected int hashKey(int key) {
|
||||
assert !((key) == 0); // Handled as a special case (empty slot marker).
|
||||
return BitMixer.mixPhi(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a logical "index" of a given key that can be used to speed up
|
||||
* follow-up logic in certain scenarios (conditional logic).
|
||||
*
|
||||
* <p>
|
||||
* The semantics of "indexes" are not strictly defined. Indexes may (and
|
||||
* typically won't be) contiguous.
|
||||
*
|
||||
* <p>
|
||||
* The index is valid only between modifications (it will not be affected by
|
||||
* read-only operations).
|
||||
*
|
||||
* @see #indexExists
|
||||
* @see #indexGet
|
||||
* @see #indexInsert
|
||||
* @see #indexReplace
|
||||
* @param key The key to locate in the set.
|
||||
* @return A non-negative value of the logical "index" of the key in the set or
|
||||
* a negative value if the key did not exist.
|
||||
*/
|
||||
public int indexOf(int key) {
|
||||
final int mask = this.mask;
|
||||
if (((key) == 0)) {
|
||||
return hasEmptyKey ? mask + 1 : ~(mask + 1);
|
||||
} else {
|
||||
final int[] keys = this.keys;
|
||||
int slot = hashKey(key) & mask;
|
||||
|
||||
int existing;
|
||||
while (!((existing = keys[slot]) == 0)) {
|
||||
if (((key) == (existing))) {
|
||||
return slot;
|
||||
}
|
||||
slot = (slot + 1) & mask;
|
||||
}
|
||||
|
||||
return ~slot;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #indexOf
|
||||
* @param index The index of a given key, as returned from {@link #indexOf}.
|
||||
* @return Returns <code>true</code> if the index corresponds to an existing key
|
||||
* or false otherwise. This is equivalent to checking whether the index
|
||||
* is a positive value (existing keys) or a negative value (non-existing
|
||||
* keys).
|
||||
*/
|
||||
public boolean indexExists(int index) {
|
||||
assert index < 0 || index <= mask || (index == mask + 1 && hasEmptyKey);
|
||||
|
||||
return index >= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the exact value of the existing key. This method makes sense for sets
|
||||
* of objects which define custom key-equality relationship.
|
||||
*
|
||||
* @see #indexOf
|
||||
* @param index The index of an existing key.
|
||||
* @return Returns the equivalent key currently stored in the set.
|
||||
* @throws AssertionError If assertions are enabled and the index does not
|
||||
* correspond to an existing key.
|
||||
*/
|
||||
public int indexGet(int index) {
|
||||
assert index >= 0 : "The index must point at an existing key.";
|
||||
assert index <= mask || (index == mask + 1 && hasEmptyKey);
|
||||
|
||||
return keys[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the existing equivalent key with the given one and returns any
|
||||
* previous value stored for that key.
|
||||
*
|
||||
* @see #indexOf
|
||||
* @param index The index of an existing key.
|
||||
* @param equivalentKey The key to put in the set as a replacement. Must be
|
||||
* equivalent to the key currently stored at the provided
|
||||
* index.
|
||||
* @return Returns the previous key stored in the set.
|
||||
* @throws AssertionError If assertions are enabled and the index does not
|
||||
* correspond to an existing key.
|
||||
*/
|
||||
public int indexReplace(int index, int equivalentKey) {
|
||||
assert index >= 0 : "The index must point at an existing key.";
|
||||
assert index <= mask || (index == mask + 1 && hasEmptyKey);
|
||||
assert ((keys[index]) == (equivalentKey));
|
||||
|
||||
int previousValue = keys[index];
|
||||
keys[index] = equivalentKey;
|
||||
return previousValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts a key for an index that is not present in the set. This method may
|
||||
* help in avoiding double recalculation of the key's hash.
|
||||
*
|
||||
* @see #indexOf
|
||||
* @param index The index of a previously non-existing key, as returned from
|
||||
* {@link #indexOf}.
|
||||
* @throws AssertionError If assertions are enabled and the index does not
|
||||
* correspond to an existing key.
|
||||
*/
|
||||
public void indexInsert(int index, int key) {
|
||||
assert index < 0 : "The index must not point at an existing key.";
|
||||
|
||||
index = ~index;
|
||||
if (((key) == 0)) {
|
||||
assert index == mask + 1;
|
||||
assert ((keys[index]) == 0);
|
||||
hasEmptyKey = true;
|
||||
} else {
|
||||
assert ((keys[index]) == 0);
|
||||
|
||||
if (assigned == resizeAt) {
|
||||
allocateThenInsertThenRehash(index, key);
|
||||
} else {
|
||||
keys[index] = key;
|
||||
}
|
||||
|
||||
assigned++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a key at an index previously acquired from {@link #indexOf}.
|
||||
*
|
||||
* @see #indexOf
|
||||
* @param index The index of the key to remove, as returned from
|
||||
* {@link #indexOf}.
|
||||
* @throws AssertionError If assertions are enabled and the index does not
|
||||
* correspond to an existing key.
|
||||
*/
|
||||
public void indexRemove(int index) {
|
||||
assert index >= 0 : "The index must point at an existing key.";
|
||||
assert index <= mask || (index == mask + 1 && hasEmptyKey);
|
||||
|
||||
if (index > mask) {
|
||||
hasEmptyKey = false;
|
||||
} else {
|
||||
shiftConflictingKeys(index);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String visualizeKeyDistribution(int characters) {
|
||||
return IntBufferVisualizer.visualizeKeyDistribution(keys, mask, characters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate load factor range and return it. Override and suppress if you need
|
||||
* insane load factors.
|
||||
*/
|
||||
protected double verifyLoadFactor(double loadFactor) {
|
||||
checkLoadFactor(loadFactor, MIN_LOAD_FACTOR, MAX_LOAD_FACTOR);
|
||||
return loadFactor;
|
||||
}
|
||||
|
||||
/** Rehash from old buffers to new buffers. */
|
||||
protected void rehash(int[] fromKeys) {
|
||||
assert HashContainers.checkPowerOfTwo(fromKeys.length - 1);
|
||||
|
||||
// Rehash all stored keys into the new buffers.
|
||||
final int[] keys = this.keys;
|
||||
final int mask = this.mask;
|
||||
int existing;
|
||||
for (int i = fromKeys.length - 1; --i >= 0;) {
|
||||
if (!((existing = fromKeys[i]) == 0)) {
|
||||
int slot = hashKey(existing) & mask;
|
||||
while (!((keys[slot]) == 0)) {
|
||||
slot = (slot + 1) & mask;
|
||||
}
|
||||
keys[slot] = existing;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Allocate new internal buffers. This method attempts to allocate and assign
|
||||
* internal buffers atomically (either allocations succeed or not).
|
||||
*/
|
||||
protected void allocateBuffers(int arraySize) {
|
||||
assert Integer.bitCount(arraySize) == 1;
|
||||
|
||||
// Ensure no change is done if we hit an OOM.
|
||||
int[] prevKeys = this.keys;
|
||||
try {
|
||||
int emptyElementSlot = 1;
|
||||
this.keys = (new int[arraySize + emptyElementSlot]);
|
||||
} catch (OutOfMemoryError e) {
|
||||
this.keys = prevKeys;
|
||||
throw new BufferAllocationException("Not enough memory to allocate buffers for rehashing: %,d -> %,d", e,
|
||||
this.keys == null ? 0 : size(), arraySize);
|
||||
}
|
||||
|
||||
this.resizeAt = expandAtCount(arraySize, loadFactor);
|
||||
this.mask = arraySize - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is invoked when there is a new key to be inserted into the buffer
|
||||
* but there is not enough empty slots to do so.
|
||||
*
|
||||
* <p>
|
||||
* New buffers are allocated. If this succeeds, we know we can proceed with
|
||||
* rehashing so we assign the pending element to the previous buffer (possibly
|
||||
* violating the invariant of having at least one empty slot) and rehash all
|
||||
* keys, substituting new buffers at the end.
|
||||
*/
|
||||
protected void allocateThenInsertThenRehash(int slot, int pendingKey) {
|
||||
assert assigned == resizeAt && ((keys[slot]) == 0) && !((pendingKey) == 0);
|
||||
|
||||
// Try to allocate new buffers first. If we OOM, we leave in a consistent state.
|
||||
final int[] prevKeys = this.keys;
|
||||
allocateBuffers(nextBufferSize(mask + 1, size(), loadFactor));
|
||||
assert this.keys.length > prevKeys.length;
|
||||
|
||||
// We have succeeded at allocating new data so insert the pending key/value at
|
||||
// the free slot in the old arrays before rehashing.
|
||||
prevKeys[slot] = pendingKey;
|
||||
|
||||
// Rehash old keys, including the pending key.
|
||||
rehash(prevKeys);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shift all the slot-conflicting keys allocated to (and including)
|
||||
* <code>slot</code>.
|
||||
*/
|
||||
protected void shiftConflictingKeys(int gapSlot) {
|
||||
final int[] keys = this.keys;
|
||||
final int mask = this.mask;
|
||||
|
||||
// Perform shifts of conflicting keys to fill in the gap.
|
||||
int distance = 0;
|
||||
while (true) {
|
||||
final int slot = (gapSlot + (++distance)) & mask;
|
||||
final int existing = keys[slot];
|
||||
if (((existing) == 0)) {
|
||||
break;
|
||||
}
|
||||
|
||||
final int idealSlot = hashKey(existing);
|
||||
final int shift = (slot - idealSlot) & mask;
|
||||
if (shift >= distance) {
|
||||
// Entry at this position was originally at or before the gap slot.
|
||||
// Move the conflict-shifted entry to the gap's position and repeat the
|
||||
// procedure
|
||||
// for any entries to the right of the current position, treating it
|
||||
// as the new gap.
|
||||
keys[gapSlot] = existing;
|
||||
gapSlot = slot;
|
||||
distance = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Mark the last found gap slot without a conflict as empty.
|
||||
keys[gapSlot] = 0;
|
||||
assigned--;
|
||||
}
|
||||
}
|
||||
+1085
File diff suppressed because it is too large
Load Diff
+1050
File diff suppressed because it is too large
Load Diff
+612
@@ -0,0 +1,612 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.*;
|
||||
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.Containers.*;
|
||||
|
||||
/** An array-backed list of Objects. */
|
||||
@SuppressWarnings("unchecked")
|
||||
public class ObjectArrayList<KType> extends AbstractObjectCollection<KType>
|
||||
implements ObjectIndexedContainer<KType>, Preallocable, Cloneable, Accountable {
|
||||
/** An immutable empty buffer (array). */
|
||||
public static final Object[] EMPTY_ARRAY = new Object[0];
|
||||
|
||||
;
|
||||
|
||||
/** Reuse the same strategy instance. */
|
||||
private static final BoundedProportionalArraySizingStrategy DEFAULT_SIZING_STRATEGY = BoundedProportionalArraySizingStrategy.DEFAULT_INSTANCE;
|
||||
|
||||
/**
|
||||
* Internal array for storing the list. The array may be larger than the current
|
||||
* size ({@link #size()}).
|
||||
*/
|
||||
public Object[] buffer = EMPTY_ARRAY;
|
||||
|
||||
/** Current number of elements stored in {@link #buffer}. */
|
||||
public int elementsCount;
|
||||
|
||||
/** Buffer resizing strategy. */
|
||||
protected final ArraySizingStrategy resizer;
|
||||
|
||||
/** New instance with sane defaults. */
|
||||
public ObjectArrayList() {
|
||||
this(DEFAULT_EXPECTED_ELEMENTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with sane defaults.
|
||||
*
|
||||
* @param expectedElements The expected number of elements guaranteed not to
|
||||
* cause buffer expansion (inclusive).
|
||||
*/
|
||||
public ObjectArrayList(int expectedElements) {
|
||||
this(expectedElements, DEFAULT_SIZING_STRATEGY);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with sane defaults.
|
||||
*
|
||||
* @param expectedElements The expected number of elements guaranteed not to
|
||||
* cause buffer expansion (inclusive).
|
||||
* @param resizer Underlying buffer sizing strategy.
|
||||
*/
|
||||
public ObjectArrayList(int expectedElements, ArraySizingStrategy resizer) {
|
||||
assert resizer != null;
|
||||
this.resizer = resizer;
|
||||
buffer = Arrays.copyOf(buffer, expectedElements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new list from the elements of another container in its iteration
|
||||
* order.
|
||||
*/
|
||||
public ObjectArrayList(ObjectContainer<? extends KType> container) {
|
||||
this(container.size());
|
||||
addAll(container);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void add(KType e1) {
|
||||
ensureBufferSpace(1);
|
||||
buffer[elementsCount++] = e1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends two elements at the end of the list. To add more than two elements,
|
||||
* use <code>add
|
||||
* </code> (vararg-version) or access the buffer directly (tight loop).
|
||||
*/
|
||||
public void add(KType e1, KType e2) {
|
||||
ensureBufferSpace(2);
|
||||
buffer[elementsCount++] = e1;
|
||||
buffer[elementsCount++] = e2;
|
||||
}
|
||||
|
||||
/** Add all elements from a range of given array to the list. */
|
||||
public void add(KType[] elements, int start, int length) {
|
||||
assert length >= 0 : "Length must be >= 0";
|
||||
|
||||
ensureBufferSpace(length);
|
||||
System.arraycopy(elements, start, buffer, elementsCount, length);
|
||||
elementsCount += length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vararg-signature method for adding elements at the end of the list.
|
||||
*
|
||||
* <p>
|
||||
* <b>This method is handy, but costly if used in tight loops (anonymous array
|
||||
* passing)</b>
|
||||
*/
|
||||
@SafeVarargs
|
||||
public final void add(KType... elements) {
|
||||
add(elements, 0, elements.length);
|
||||
}
|
||||
|
||||
/** Adds all elements from another container. */
|
||||
public int addAll(ObjectContainer<? extends KType> container) {
|
||||
final int size = container.size();
|
||||
ensureBufferSpace(size);
|
||||
|
||||
for (ObjectCursor<? extends KType> cursor : container) {
|
||||
add(cursor.value);
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
/** Adds all elements from another iterable. */
|
||||
public int addAll(Iterable<? extends ObjectCursor<? extends KType>> iterable) {
|
||||
int size = 0;
|
||||
for (ObjectCursor<? extends KType> cursor : iterable) {
|
||||
add(cursor.value);
|
||||
size++;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void insert(int index, KType e1) {
|
||||
assert (index >= 0 && index <= size()) : "Index " + index + " out of bounds [" + 0 + ", " + size() + "].";
|
||||
|
||||
ensureBufferSpace(1);
|
||||
System.arraycopy(buffer, index, buffer, index + 1, elementsCount - index);
|
||||
buffer[index] = e1;
|
||||
elementsCount++;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public KType get(int index) {
|
||||
assert (index >= 0 && index < size()) : "Index " + index + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
|
||||
return (KType) buffer[index];
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public KType set(int index, KType e1) {
|
||||
assert (index >= 0 && index < size()) : "Index " + index + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
|
||||
final KType v = (KType) buffer[index];
|
||||
buffer[index] = e1;
|
||||
return v;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public KType removeAt(int index) {
|
||||
assert (index >= 0 && index < size()) : "Index " + index + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
|
||||
final KType v = (KType) buffer[index];
|
||||
System.arraycopy(buffer, index + 1, buffer, index, --elementsCount - index);
|
||||
|
||||
buffer[elementsCount] = null;
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public KType removeLast() {
|
||||
assert elementsCount > 0;
|
||||
|
||||
final KType v = (KType) buffer[--elementsCount];
|
||||
|
||||
buffer[elementsCount] = null;
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void removeRange(int fromIndex, int toIndex) {
|
||||
assert (fromIndex >= 0 && fromIndex <= size())
|
||||
: "Index " + fromIndex + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
assert (toIndex >= 0 && toIndex <= size()) : "Index " + toIndex + " out of bounds [" + 0 + ", " + size() + "].";
|
||||
assert fromIndex <= toIndex : "fromIndex must be <= toIndex: " + fromIndex + ", " + toIndex;
|
||||
|
||||
System.arraycopy(buffer, toIndex, buffer, fromIndex, elementsCount - toIndex);
|
||||
final int count = toIndex - fromIndex;
|
||||
elementsCount -= count;
|
||||
|
||||
Arrays.fill(buffer, elementsCount, elementsCount + count, null);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean removeElement(KType e1) {
|
||||
return removeFirst(e1) != -1;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeFirst(KType e1) {
|
||||
final int index = indexOf(e1);
|
||||
if (index >= 0)
|
||||
removeAt(index);
|
||||
return index;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeLast(KType e1) {
|
||||
final int index = lastIndexOf(e1);
|
||||
if (index >= 0)
|
||||
removeAt(index);
|
||||
return index;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeAll(KType e1) {
|
||||
int to = 0;
|
||||
for (int from = 0; from < elementsCount; from++) {
|
||||
if (this.equals(e1, buffer[from])) {
|
||||
continue;
|
||||
}
|
||||
if (to != from) {
|
||||
buffer[to] = buffer[from];
|
||||
}
|
||||
to++;
|
||||
}
|
||||
final int deleted = elementsCount - to;
|
||||
this.elementsCount = to;
|
||||
|
||||
Arrays.fill(buffer, elementsCount, elementsCount + deleted, null);
|
||||
|
||||
return deleted;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean contains(KType e1) {
|
||||
return indexOf(e1) >= 0;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int indexOf(KType e1) {
|
||||
for (int i = 0; i < elementsCount; i++) {
|
||||
if (this.equals(e1, buffer[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int lastIndexOf(KType e1) {
|
||||
for (int i = elementsCount - 1; i >= 0; i--) {
|
||||
if (this.equals(e1, buffer[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return elementsCount == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure this container can hold at least the given number of elements without
|
||||
* resizing its buffers.
|
||||
*
|
||||
* @param expectedElements The total number of elements, inclusive.
|
||||
*/
|
||||
@Override
|
||||
public void ensureCapacity(int expectedElements) {
|
||||
final int bufferLen = (buffer == null ? 0 : buffer.length);
|
||||
if (expectedElements > bufferLen) {
|
||||
ensureBufferSpace(expectedElements - size());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the internal buffer has enough free slots to store
|
||||
* <code>expectedAdditions</code>. Increases internal buffer size if needed.
|
||||
*/
|
||||
protected void ensureBufferSpace(int expectedAdditions) {
|
||||
final int bufferLen = (buffer == null ? 0 : buffer.length);
|
||||
if (elementsCount + expectedAdditions > bufferLen) {
|
||||
final int newSize = resizer.grow(bufferLen, elementsCount, expectedAdditions);
|
||||
assert newSize >= elementsCount + expectedAdditions : "Resizer failed to" + " return sensible new size: "
|
||||
+ newSize + " <= " + (elementsCount + expectedAdditions);
|
||||
|
||||
this.buffer = Arrays.copyOf(buffer, newSize);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncate or expand the list to the new size. If the list is truncated, the
|
||||
* buffer will not be reallocated (use {@link #trimToSize()} if you need a
|
||||
* truncated buffer), but the truncated values will be reset to the default
|
||||
* value (zero). If the list is expanded, the elements beyond the current size
|
||||
* are initialized with JVM-defaults (zero or <code>null</code> values).
|
||||
*/
|
||||
public void resize(int newSize) {
|
||||
if (newSize <= buffer.length) {
|
||||
if (newSize < elementsCount) {
|
||||
Arrays.fill(buffer, newSize, elementsCount, null);
|
||||
} else {
|
||||
Arrays.fill(buffer, elementsCount, newSize, null);
|
||||
}
|
||||
} else {
|
||||
ensureCapacity(newSize);
|
||||
}
|
||||
this.elementsCount = newSize;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int size() {
|
||||
return elementsCount;
|
||||
}
|
||||
|
||||
/** Trim the internal buffer to the current size. */
|
||||
public void trimToSize() {
|
||||
if (size() != this.buffer.length) {
|
||||
this.buffer = (KType[]) toArray();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the number of stored elements to zero. Releases and initializes the
|
||||
* internal storage array to default values. To clear the list without cleaning
|
||||
* the buffer, simply set the {@link #elementsCount} field to zero.
|
||||
*/
|
||||
@Override
|
||||
public void clear() {
|
||||
Arrays.fill(buffer, 0, elementsCount, null);
|
||||
this.elementsCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the number of stored elements to zero and releases the internal storage
|
||||
* array.
|
||||
*/
|
||||
@Override
|
||||
public void release() {
|
||||
this.buffer = (KType[]) EMPTY_ARRAY;
|
||||
this.elementsCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* <p>
|
||||
* The returned array is sized to match exactly the number of elements of the
|
||||
* stack.
|
||||
*/
|
||||
@Override
|
||||
public Object[] toArray() {
|
||||
|
||||
return Arrays.copyOf(buffer, elementsCount);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Stream<KType> stream() {
|
||||
return (Stream<KType>) Arrays.stream(buffer, 0, size());
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public ObjectIndexedContainer<KType> sort() {
|
||||
Arrays.sort(buffer, 0, elementsCount);
|
||||
return this;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public ObjectIndexedContainer<KType> reverse() {
|
||||
for (int i = 0, mid = elementsCount >> 1, j = elementsCount - 1; i < mid; i++, j--) {
|
||||
KType tmp = (KType) buffer[i];
|
||||
buffer[i] = buffer[j];
|
||||
buffer[j] = tmp;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone this object. The returned clone will reuse the same hash function and
|
||||
* array resizing strategy.
|
||||
*/
|
||||
@Override
|
||||
public ObjectArrayList<KType> clone() {
|
||||
try {
|
||||
|
||||
final ObjectArrayList<KType> cloned = (ObjectArrayList<KType>) super.clone();
|
||||
cloned.buffer = buffer.clone();
|
||||
return cloned;
|
||||
} catch (CloneNotSupportedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int h = 1, max = elementsCount;
|
||||
for (int i = 0; i < max; i++) {
|
||||
h = 31 * h + BitMixer.mix(this.buffer[i]);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns <code>true</code> only if the other object is an instance of the same
|
||||
* class and with the same elements. Equality comparison is performed with this
|
||||
* object's {@link #equals(Object, Object)} method.
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return (this == obj) || (obj != null && getClass() == obj.getClass() && equalElements(getClass().cast(obj)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare index-aligned elements against another
|
||||
* {@link ObjectIndexedContainer}. Equality comparison is performed with this
|
||||
* object's {@link #equals(Object, Object)} method.
|
||||
*/
|
||||
protected boolean equalElements(ObjectArrayList<?> other) {
|
||||
int max = size();
|
||||
if (other.size() != max) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < max; i++) {
|
||||
if (!this.equals(get(i), other.get(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long ramBytesAllocated() {
|
||||
// int: elementsCount
|
||||
return RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + Integer.BYTES + resizer.ramBytesAllocated()
|
||||
+ RamUsageEstimator.shallowSizeOfArray(buffer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long ramBytesUsed() {
|
||||
// int: elementsCount
|
||||
return RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + Integer.BYTES + resizer.ramBytesUsed()
|
||||
+ RamUsageEstimator.shallowUsedSizeOfArray(buffer, elementsCount);
|
||||
}
|
||||
|
||||
/** An iterator implementation for {@link ObjectArrayList#iterator}. */
|
||||
static final class ValueIterator<KType> extends AbstractIterator<ObjectCursor<KType>> {
|
||||
private final ObjectCursor<KType> cursor;
|
||||
|
||||
private final KType[] buffer;
|
||||
private final int size;
|
||||
|
||||
public ValueIterator(KType[] buffer, int size) {
|
||||
this.cursor = new ObjectCursor<KType>();
|
||||
this.cursor.index = -1;
|
||||
this.size = size;
|
||||
this.buffer = buffer;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ObjectCursor<KType> fetch() {
|
||||
if (cursor.index + 1 == size)
|
||||
return done();
|
||||
|
||||
cursor.value = buffer[++cursor.index];
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public Iterator<ObjectCursor<KType>> iterator() {
|
||||
return new ValueIterator<KType>((KType[]) buffer, size());
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public <T extends ObjectProcedure<? super KType>> T forEach(T procedure) {
|
||||
return forEach(procedure, 0, size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies <code>procedure</code> to a slice of the list,
|
||||
* <code>fromIndex</code>, inclusive, to <code>toIndex</code>, exclusive.
|
||||
*/
|
||||
public <T extends ObjectProcedure<? super KType>> T forEach(T procedure, int fromIndex, final int toIndex) {
|
||||
assert (fromIndex >= 0 && fromIndex <= size())
|
||||
: "Index " + fromIndex + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
|
||||
assert (toIndex >= 0 && toIndex <= size()) : "Index " + toIndex + " out of bounds [" + 0 + ", " + size() + "].";
|
||||
|
||||
assert fromIndex <= toIndex : "fromIndex must be <= toIndex: " + fromIndex + ", " + toIndex;
|
||||
|
||||
final KType[] buffer = (KType[]) this.buffer;
|
||||
for (int i = fromIndex; i < toIndex; i++) {
|
||||
procedure.apply(buffer[i]);
|
||||
}
|
||||
|
||||
return procedure;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeAll(ObjectPredicate<? super KType> predicate) {
|
||||
final KType[] buffer = (KType[]) this.buffer;
|
||||
final int elementsCount = this.elementsCount;
|
||||
int to = 0;
|
||||
int from = 0;
|
||||
try {
|
||||
for (; from < elementsCount; from++) {
|
||||
if (predicate.apply(buffer[from])) {
|
||||
buffer[from] = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (to != from) {
|
||||
buffer[to] = buffer[from];
|
||||
buffer[from] = null;
|
||||
}
|
||||
to++;
|
||||
}
|
||||
} finally {
|
||||
// Keep the list in a consistent state, even if the predicate throws an
|
||||
// exception.
|
||||
for (; from < elementsCount; from++) {
|
||||
if (to != from) {
|
||||
buffer[to] = buffer[from];
|
||||
buffer[from] = null;
|
||||
}
|
||||
to++;
|
||||
}
|
||||
|
||||
this.elementsCount = to;
|
||||
}
|
||||
|
||||
return elementsCount - to;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public <T extends ObjectPredicate<? super KType>> T forEach(T predicate) {
|
||||
return forEach(predicate, 0, size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies <code>predicate</code> to a slice of the list,
|
||||
* <code>fromIndex</code>, inclusive, to <code>toIndex</code>, exclusive, or
|
||||
* until predicate returns <code>false</code>.
|
||||
*/
|
||||
public <T extends ObjectPredicate<? super KType>> T forEach(T predicate, int fromIndex, final int toIndex) {
|
||||
assert (fromIndex >= 0 && fromIndex <= size())
|
||||
: "Index " + fromIndex + " out of bounds [" + 0 + ", " + size() + ").";
|
||||
assert (toIndex >= 0 && toIndex <= size()) : "Index " + toIndex + " out of bounds [" + 0 + ", " + size() + "].";
|
||||
assert fromIndex <= toIndex : "fromIndex must be <= toIndex: " + fromIndex + ", " + toIndex;
|
||||
|
||||
final KType[] buffer = (KType[]) this.buffer;
|
||||
for (int i = fromIndex; i < toIndex; i++) {
|
||||
if (!predicate.apply(buffer[i]))
|
||||
break;
|
||||
}
|
||||
|
||||
return predicate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a list from a variable number of arguments or an array of
|
||||
* <code>Object</code>. The elements are copied from the argument to the
|
||||
* internal buffer.
|
||||
*/
|
||||
@SafeVarargs
|
||||
public static <KType> ObjectArrayList<KType> from(KType... elements) {
|
||||
final ObjectArrayList<KType> list = new ObjectArrayList<KType>(elements.length);
|
||||
list.add(elements);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
/**
|
||||
* Reused buffer visualization routines.
|
||||
*
|
||||
* @see ObjectSet#visualizeKeyDistribution(int)
|
||||
* @see ObjectVTypeMap#visualizeKeyDistribution(int)
|
||||
*/
|
||||
class ObjectBufferVisualizer<KType> {
|
||||
static <KType> String visualizeKeyDistribution(Object[] buffer, int max, int characters) {
|
||||
final StringBuilder b = new StringBuilder();
|
||||
final char[] chars = ".123456789X".toCharArray();
|
||||
for (int i = 1, start = -1; i <= characters; i++) {
|
||||
int end = (int) ((long) i * max / characters);
|
||||
|
||||
if (start + 1 <= end) {
|
||||
int taken = 0;
|
||||
int slots = 0;
|
||||
for (int slot = start + 1; slot <= end; slot++, slots++) {
|
||||
if (!((buffer[slot]) == null)) {
|
||||
taken++;
|
||||
}
|
||||
}
|
||||
b.append(chars[Math.min(chars.length - 1, taken * chars.length / slots)]);
|
||||
start = end;
|
||||
}
|
||||
}
|
||||
while (b.length() < characters) {
|
||||
b.append(' ');
|
||||
}
|
||||
return b.toString();
|
||||
}
|
||||
}
|
||||
+810
@@ -0,0 +1,810 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.*;
|
||||
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.Containers.*;
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.HashContainers.*;
|
||||
|
||||
/**
|
||||
* A hash set of <code>Object</code>s, implemented using open addressing with
|
||||
* linear probing for collision resolution.
|
||||
*
|
||||
* @see <a href="{@docRoot}/overview-summary.html#interfaces">HPPC interfaces
|
||||
* diagram</a>
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public class ObjectHashSet<KType> extends AbstractObjectCollection<KType>
|
||||
implements ObjectLookupContainer<KType>, ObjectSet<KType>, Preallocable, Cloneable, Accountable {
|
||||
/** The hash array holding keys. */
|
||||
public Object[] keys;
|
||||
|
||||
/**
|
||||
* The number of stored keys (assigned key slots), excluding the special "empty"
|
||||
* key, if any.
|
||||
*
|
||||
* @see #size()
|
||||
* @see #hasEmptyKey
|
||||
*/
|
||||
protected int assigned;
|
||||
|
||||
/** Mask for slot scans in {@link #keys}. */
|
||||
protected int mask;
|
||||
|
||||
/** Expand (rehash) {@link #keys} when {@link #assigned} hits this value. */
|
||||
protected int resizeAt;
|
||||
|
||||
/** Special treatment for the "empty slot" key marker. */
|
||||
protected boolean hasEmptyKey;
|
||||
|
||||
/** The load factor for {@link #keys}. */
|
||||
protected double loadFactor;
|
||||
|
||||
/**
|
||||
* Seed used to ensure the hash iteration order is different from an iteration
|
||||
* to another.
|
||||
*/
|
||||
protected int iterationSeed;
|
||||
|
||||
/**
|
||||
* New instance with sane defaults.
|
||||
*
|
||||
* @see #ObjectHashSet(int, double)
|
||||
*/
|
||||
public ObjectHashSet() {
|
||||
this(DEFAULT_EXPECTED_ELEMENTS, DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with sane defaults.
|
||||
*
|
||||
* @see #ObjectHashSet(int, double)
|
||||
*/
|
||||
public ObjectHashSet(int expectedElements) {
|
||||
this(expectedElements, DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with the provided defaults.
|
||||
*
|
||||
* @param expectedElements The expected number of elements guaranteed not to
|
||||
* cause a rehash (inclusive).
|
||||
* @param loadFactor The load factor for internal buffers. Insane load
|
||||
* factors (zero, full capacity) are rejected by
|
||||
* {@link #verifyLoadFactor(double)}.
|
||||
*/
|
||||
public ObjectHashSet(int expectedElements, double loadFactor) {
|
||||
this.loadFactor = verifyLoadFactor(loadFactor);
|
||||
iterationSeed = HashContainers.nextIterationSeed();
|
||||
ensureCapacity(expectedElements);
|
||||
}
|
||||
|
||||
/** New instance copying elements from another {@link ObjectContainer}. */
|
||||
public ObjectHashSet(ObjectContainer<? extends KType> container) {
|
||||
this(container.size());
|
||||
addAll(container);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean add(KType key) {
|
||||
if (((key) == null)) {
|
||||
assert ((keys[mask + 1]) == null);
|
||||
boolean added = !hasEmptyKey;
|
||||
hasEmptyKey = true;
|
||||
return added;
|
||||
} else {
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
final int mask = this.mask;
|
||||
int slot = hashKey(key) & mask;
|
||||
|
||||
KType existing;
|
||||
while (!((existing = keys[slot]) == null)) {
|
||||
if (this.equals(key, existing)) {
|
||||
return false;
|
||||
}
|
||||
slot = (slot + 1) & mask;
|
||||
}
|
||||
|
||||
if (assigned == resizeAt) {
|
||||
allocateThenInsertThenRehash(slot, key);
|
||||
} else {
|
||||
keys[slot] = key;
|
||||
}
|
||||
|
||||
assigned++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds all elements from the given list (vararg) to this set.
|
||||
*
|
||||
* @return Returns the number of elements actually added as a result of this
|
||||
* call (not previously present in the set).
|
||||
*/
|
||||
@SafeVarargs
|
||||
public final int addAll(KType... elements) {
|
||||
ensureCapacity(elements.length);
|
||||
int count = 0;
|
||||
for (KType e : elements) {
|
||||
if (add(e)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds all elements from the given {@link ObjectContainer} to this set.
|
||||
*
|
||||
* @return Returns the number of elements actually added as a result of this
|
||||
* call (not previously present in the set).
|
||||
*/
|
||||
public int addAll(ObjectContainer<? extends KType> container) {
|
||||
ensureCapacity(container.size());
|
||||
return addAll((Iterable<? extends ObjectCursor<? extends KType>>) container);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds all elements from the given iterable to this set.
|
||||
*
|
||||
* @return Returns the number of elements actually added as a result of this
|
||||
* call (not previously present in the set).
|
||||
*/
|
||||
public int addAll(Iterable<? extends ObjectCursor<? extends KType>> iterable) {
|
||||
int count = 0;
|
||||
for (ObjectCursor<? extends KType> cursor : iterable) {
|
||||
if (add(cursor.value)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public Object[] toArray() {
|
||||
|
||||
final KType[] cloned = ((KType[]) new Object[size()]);
|
||||
int j = 0;
|
||||
if (hasEmptyKey) {
|
||||
cloned[j++] = null;
|
||||
}
|
||||
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
int seed = nextIterationSeed();
|
||||
int inc = iterationIncrement(seed);
|
||||
for (int i = 0, mask = this.mask, slot = seed & mask; i <= mask; i++, slot = (slot + inc) & mask) {
|
||||
KType existing;
|
||||
if (!((existing = keys[slot]) == null)) {
|
||||
cloned[j++] = existing;
|
||||
}
|
||||
}
|
||||
|
||||
return cloned;
|
||||
}
|
||||
|
||||
/** An alias for the (preferred) {@link #removeAll}. */
|
||||
public boolean remove(KType key) {
|
||||
if (((key) == null)) {
|
||||
boolean hadEmptyKey = hasEmptyKey;
|
||||
hasEmptyKey = false;
|
||||
return hadEmptyKey;
|
||||
} else {
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
final int mask = this.mask;
|
||||
int slot = hashKey(key) & mask;
|
||||
|
||||
KType existing;
|
||||
while (!((existing = keys[slot]) == null)) {
|
||||
if (this.equals(key, existing)) {
|
||||
shiftConflictingKeys(slot);
|
||||
return true;
|
||||
}
|
||||
slot = (slot + 1) & mask;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeAll(KType key) {
|
||||
return remove(key) ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all keys present in a given container.
|
||||
*
|
||||
* @return Returns the number of elements actually removed as a result of this
|
||||
* call.
|
||||
*/
|
||||
public int removeAll(ObjectContainer<? super KType> other) {
|
||||
final int before = size();
|
||||
|
||||
// Try to iterate over the smaller set or over the container that isn't
|
||||
// implementing
|
||||
// efficient contains() lookup.
|
||||
|
||||
if (other.size() >= size() && other instanceof ObjectLookupContainer<?>) {
|
||||
if (hasEmptyKey && other.contains(null)) {
|
||||
hasEmptyKey = false;
|
||||
}
|
||||
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
for (int slot = 0, max = this.mask; slot <= max;) {
|
||||
KType existing;
|
||||
if (!((existing = keys[slot]) == null) && other.contains(existing)) {
|
||||
// Shift, do not increment slot.
|
||||
shiftConflictingKeys(slot);
|
||||
} else {
|
||||
slot++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (ObjectCursor<?> c : other) {
|
||||
remove((KType) c.value);
|
||||
}
|
||||
}
|
||||
|
||||
return before - size();
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int removeAll(ObjectPredicate<? super KType> predicate) {
|
||||
int before = size();
|
||||
|
||||
if (hasEmptyKey) {
|
||||
if (predicate.apply(null)) {
|
||||
hasEmptyKey = false;
|
||||
}
|
||||
}
|
||||
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
for (int slot = 0, max = this.mask; slot <= max;) {
|
||||
KType existing;
|
||||
if (!((existing = keys[slot]) == null)) {
|
||||
if (predicate.apply(existing)) {
|
||||
shiftConflictingKeys(slot);
|
||||
continue; // Repeat the check for the same slot i (shifted).
|
||||
}
|
||||
}
|
||||
slot++;
|
||||
}
|
||||
|
||||
return before - size();
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean contains(KType key) {
|
||||
if (((key) == null)) {
|
||||
return hasEmptyKey;
|
||||
} else {
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
final int mask = this.mask;
|
||||
int slot = hashKey(key) & mask;
|
||||
KType existing;
|
||||
while (!((existing = keys[slot]) == null)) {
|
||||
if (this.equals(key, existing)) {
|
||||
return true;
|
||||
}
|
||||
slot = (slot + 1) & mask;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void clear() {
|
||||
assigned = 0;
|
||||
hasEmptyKey = false;
|
||||
Arrays.fill(keys, null);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public void release() {
|
||||
assigned = 0;
|
||||
hasEmptyKey = false;
|
||||
keys = null;
|
||||
ensureCapacity(Containers.DEFAULT_EXPECTED_ELEMENTS);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure this container can hold at least the given number of elements without
|
||||
* resizing its buffers.
|
||||
*
|
||||
* @param expectedElements The total number of elements, inclusive.
|
||||
*/
|
||||
@Override
|
||||
public void ensureCapacity(int expectedElements) {
|
||||
if (expectedElements > resizeAt || keys == null) {
|
||||
final KType[] prevKeys = (KType[]) this.keys;
|
||||
allocateBuffers(minBufferSize(expectedElements, loadFactor));
|
||||
if (prevKeys != null && !isEmpty()) {
|
||||
rehash(prevKeys);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int size() {
|
||||
return assigned + (hasEmptyKey ? 1 : 0);
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int h = hasEmptyKey ? 0xDEADBEEF : 0;
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
for (int slot = mask; slot >= 0; slot--) {
|
||||
KType existing;
|
||||
if (!((existing = keys[slot]) == null)) {
|
||||
h += BitMixer.mix(existing);
|
||||
}
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return (this == obj) || (obj != null && getClass() == obj.getClass() && sameKeys(getClass().cast(obj)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if all keys of some other container exist in this container.
|
||||
* Equality comparison is performed with this object's
|
||||
* {@link #equals(Object, Object)} method.
|
||||
*/
|
||||
private boolean sameKeys(ObjectSet<?> other) {
|
||||
if (other.size() != size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (ObjectCursor<?> c : other) {
|
||||
if (!contains((KType) c.value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public ObjectHashSet<KType> clone() {
|
||||
try {
|
||||
|
||||
ObjectHashSet<KType> cloned = (ObjectHashSet<KType>) super.clone();
|
||||
cloned.keys = keys.clone();
|
||||
cloned.hasEmptyKey = hasEmptyKey;
|
||||
cloned.iterationSeed = HashContainers.nextIterationSeed();
|
||||
return cloned;
|
||||
} catch (CloneNotSupportedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public Iterator<ObjectCursor<KType>> iterator() {
|
||||
return new EntryIterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long ramBytesAllocated() {
|
||||
// int: assigned, mask, keyMixer, resizeAt
|
||||
// double: loadFactor
|
||||
// boolean: hasEmptyKey
|
||||
return RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + 4 * Integer.BYTES + Double.BYTES + 1
|
||||
+ RamUsageEstimator.shallowSizeOfArray(keys);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long ramBytesUsed() {
|
||||
// int: assigned, mask, keyMixer, resizeAt
|
||||
// double: loadFactor
|
||||
// boolean: hasEmptyKey
|
||||
return RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + 4 * Integer.BYTES + Double.BYTES + 1
|
||||
+ RamUsageEstimator.shallowUsedSizeOfArray(keys, size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides the next iteration seed used to build the iteration starting slot
|
||||
* and offset increment. This method does not need to be synchronized, what
|
||||
* matters is that each thread gets a sequence of varying seeds.
|
||||
*/
|
||||
protected int nextIterationSeed() {
|
||||
return iterationSeed = BitMixer.mixPhi(iterationSeed);
|
||||
}
|
||||
|
||||
/** An iterator implementation for {@link #iterator}. */
|
||||
protected final class EntryIterator extends AbstractIterator<ObjectCursor<KType>> {
|
||||
private final ObjectCursor<KType> cursor;
|
||||
private final int increment;
|
||||
private int index;
|
||||
private int slot;
|
||||
|
||||
public EntryIterator() {
|
||||
cursor = new ObjectCursor<KType>();
|
||||
int seed = nextIterationSeed();
|
||||
increment = iterationIncrement(seed);
|
||||
slot = seed & mask;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ObjectCursor<KType> fetch() {
|
||||
final int mask = ObjectHashSet.this.mask;
|
||||
while (index <= mask) {
|
||||
KType existing;
|
||||
index++;
|
||||
slot = (slot + increment) & mask;
|
||||
if (!((existing = (KType) keys[slot]) == null)) {
|
||||
cursor.index = slot;
|
||||
cursor.value = existing;
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
|
||||
if (index == mask + 1 && hasEmptyKey) {
|
||||
cursor.index = index++;
|
||||
cursor.value = null;
|
||||
return cursor;
|
||||
}
|
||||
|
||||
return done();
|
||||
}
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public <T extends ObjectProcedure<? super KType>> T forEach(T procedure) {
|
||||
if (hasEmptyKey) {
|
||||
procedure.apply(null);
|
||||
}
|
||||
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
int seed = nextIterationSeed();
|
||||
int inc = iterationIncrement(seed);
|
||||
for (int i = 0, mask = this.mask, slot = seed & mask; i <= mask; i++, slot = (slot + inc) & mask) {
|
||||
KType existing;
|
||||
if (!((existing = keys[slot]) == null)) {
|
||||
procedure.apply(existing);
|
||||
}
|
||||
}
|
||||
|
||||
return procedure;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
public <T extends ObjectPredicate<? super KType>> T forEach(T predicate) {
|
||||
if (hasEmptyKey) {
|
||||
if (!predicate.apply(null)) {
|
||||
return predicate;
|
||||
}
|
||||
}
|
||||
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
int seed = nextIterationSeed();
|
||||
int inc = iterationIncrement(seed);
|
||||
for (int i = 0, mask = this.mask, slot = seed & mask; i <= mask; i++, slot = (slot + inc) & mask) {
|
||||
KType existing;
|
||||
if (!((existing = keys[slot]) == null)) {
|
||||
if (!predicate.apply(existing)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return predicate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a set from a variable number of arguments or an array of
|
||||
* <code>Object</code>. The elements are copied from the argument to the
|
||||
* internal buffer.
|
||||
*/
|
||||
@SafeVarargs
|
||||
public static <KType> ObjectHashSet<KType> from(KType... elements) {
|
||||
final ObjectHashSet<KType> set = new ObjectHashSet<KType>(elements.length);
|
||||
set.addAll(elements);
|
||||
return set;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a hash code for the given key.
|
||||
*
|
||||
* <p>
|
||||
* The output from this function should evenly distribute keys across the entire
|
||||
* integer range.
|
||||
*/
|
||||
protected int hashKey(KType key) {
|
||||
assert !((key) == null); // Handled as a special case (empty slot marker).
|
||||
return BitMixer.mixPhi(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a logical "index" of a given key that can be used to speed up
|
||||
* follow-up logic in certain scenarios (conditional logic).
|
||||
*
|
||||
* <p>
|
||||
* The semantics of "indexes" are not strictly defined. Indexes may (and
|
||||
* typically won't be) contiguous.
|
||||
*
|
||||
* <p>
|
||||
* The index is valid only between modifications (it will not be affected by
|
||||
* read-only operations).
|
||||
*
|
||||
* @see #indexExists
|
||||
* @see #indexGet
|
||||
* @see #indexInsert
|
||||
* @see #indexReplace
|
||||
* @param key The key to locate in the set.
|
||||
* @return A non-negative value of the logical "index" of the key in the set or
|
||||
* a negative value if the key did not exist.
|
||||
*/
|
||||
public int indexOf(KType key) {
|
||||
final int mask = this.mask;
|
||||
if (((key) == null)) {
|
||||
return hasEmptyKey ? mask + 1 : ~(mask + 1);
|
||||
} else {
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
int slot = hashKey(key) & mask;
|
||||
|
||||
KType existing;
|
||||
while (!((existing = keys[slot]) == null)) {
|
||||
if (this.equals(key, existing)) {
|
||||
return slot;
|
||||
}
|
||||
slot = (slot + 1) & mask;
|
||||
}
|
||||
|
||||
return ~slot;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #indexOf
|
||||
* @param index The index of a given key, as returned from {@link #indexOf}.
|
||||
* @return Returns <code>true</code> if the index corresponds to an existing key
|
||||
* or false otherwise. This is equivalent to checking whether the index
|
||||
* is a positive value (existing keys) or a negative value (non-existing
|
||||
* keys).
|
||||
*/
|
||||
public boolean indexExists(int index) {
|
||||
assert index < 0 || index <= mask || (index == mask + 1 && hasEmptyKey);
|
||||
|
||||
return index >= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the exact value of the existing key. This method makes sense for sets
|
||||
* of objects which define custom key-equality relationship.
|
||||
*
|
||||
* @see #indexOf
|
||||
* @param index The index of an existing key.
|
||||
* @return Returns the equivalent key currently stored in the set.
|
||||
* @throws AssertionError If assertions are enabled and the index does not
|
||||
* correspond to an existing key.
|
||||
*/
|
||||
public KType indexGet(int index) {
|
||||
assert index >= 0 : "The index must point at an existing key.";
|
||||
assert index <= mask || (index == mask + 1 && hasEmptyKey);
|
||||
|
||||
return (KType) keys[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the existing equivalent key with the given one and returns any
|
||||
* previous value stored for that key.
|
||||
*
|
||||
* @see #indexOf
|
||||
* @param index The index of an existing key.
|
||||
* @param equivalentKey The key to put in the set as a replacement. Must be
|
||||
* equivalent to the key currently stored at the provided
|
||||
* index.
|
||||
* @return Returns the previous key stored in the set.
|
||||
* @throws AssertionError If assertions are enabled and the index does not
|
||||
* correspond to an existing key.
|
||||
*/
|
||||
public KType indexReplace(int index, KType equivalentKey) {
|
||||
assert index >= 0 : "The index must point at an existing key.";
|
||||
assert index <= mask || (index == mask + 1 && hasEmptyKey);
|
||||
assert this.equals(keys[index], equivalentKey);
|
||||
|
||||
KType previousValue = (KType) keys[index];
|
||||
keys[index] = equivalentKey;
|
||||
return previousValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts a key for an index that is not present in the set. This method may
|
||||
* help in avoiding double recalculation of the key's hash.
|
||||
*
|
||||
* @see #indexOf
|
||||
* @param index The index of a previously non-existing key, as returned from
|
||||
* {@link #indexOf}.
|
||||
* @throws AssertionError If assertions are enabled and the index does not
|
||||
* correspond to an existing key.
|
||||
*/
|
||||
public void indexInsert(int index, KType key) {
|
||||
assert index < 0 : "The index must not point at an existing key.";
|
||||
|
||||
index = ~index;
|
||||
if (((key) == null)) {
|
||||
assert index == mask + 1;
|
||||
assert ((keys[index]) == null);
|
||||
hasEmptyKey = true;
|
||||
} else {
|
||||
assert ((keys[index]) == null);
|
||||
|
||||
if (assigned == resizeAt) {
|
||||
allocateThenInsertThenRehash(index, key);
|
||||
} else {
|
||||
keys[index] = key;
|
||||
}
|
||||
|
||||
assigned++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a key at an index previously acquired from {@link #indexOf}.
|
||||
*
|
||||
* @see #indexOf
|
||||
* @param index The index of the key to remove, as returned from
|
||||
* {@link #indexOf}.
|
||||
* @throws AssertionError If assertions are enabled and the index does not
|
||||
* correspond to an existing key.
|
||||
*/
|
||||
public void indexRemove(int index) {
|
||||
assert index >= 0 : "The index must point at an existing key.";
|
||||
assert index <= mask || (index == mask + 1 && hasEmptyKey);
|
||||
|
||||
if (index > mask) {
|
||||
hasEmptyKey = false;
|
||||
} else {
|
||||
shiftConflictingKeys(index);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String visualizeKeyDistribution(int characters) {
|
||||
return ObjectBufferVisualizer.visualizeKeyDistribution(keys, mask, characters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate load factor range and return it. Override and suppress if you need
|
||||
* insane load factors.
|
||||
*/
|
||||
protected double verifyLoadFactor(double loadFactor) {
|
||||
checkLoadFactor(loadFactor, MIN_LOAD_FACTOR, MAX_LOAD_FACTOR);
|
||||
return loadFactor;
|
||||
}
|
||||
|
||||
/** Rehash from old buffers to new buffers. */
|
||||
protected void rehash(KType[] fromKeys) {
|
||||
assert HashContainers.checkPowerOfTwo(fromKeys.length - 1);
|
||||
|
||||
// Rehash all stored keys into the new buffers.
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
final int mask = this.mask;
|
||||
KType existing;
|
||||
for (int i = fromKeys.length - 1; --i >= 0;) {
|
||||
if (!((existing = fromKeys[i]) == null)) {
|
||||
int slot = hashKey(existing) & mask;
|
||||
while (!((keys[slot]) == null)) {
|
||||
slot = (slot + 1) & mask;
|
||||
}
|
||||
keys[slot] = existing;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Allocate new internal buffers. This method attempts to allocate and assign
|
||||
* internal buffers atomically (either allocations succeed or not).
|
||||
*/
|
||||
protected void allocateBuffers(int arraySize) {
|
||||
assert Integer.bitCount(arraySize) == 1;
|
||||
|
||||
// Ensure no change is done if we hit an OOM.
|
||||
KType[] prevKeys = (KType[]) this.keys;
|
||||
try {
|
||||
int emptyElementSlot = 1;
|
||||
this.keys = ((KType[]) new Object[arraySize + emptyElementSlot]);
|
||||
} catch (OutOfMemoryError e) {
|
||||
this.keys = prevKeys;
|
||||
throw new BufferAllocationException("Not enough memory to allocate buffers for rehashing: %,d -> %,d", e,
|
||||
this.keys == null ? 0 : size(), arraySize);
|
||||
}
|
||||
|
||||
this.resizeAt = expandAtCount(arraySize, loadFactor);
|
||||
this.mask = arraySize - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is invoked when there is a new key to be inserted into the buffer
|
||||
* but there is not enough empty slots to do so.
|
||||
*
|
||||
* <p>
|
||||
* New buffers are allocated. If this succeeds, we know we can proceed with
|
||||
* rehashing so we assign the pending element to the previous buffer (possibly
|
||||
* violating the invariant of having at least one empty slot) and rehash all
|
||||
* keys, substituting new buffers at the end.
|
||||
*/
|
||||
protected void allocateThenInsertThenRehash(int slot, KType pendingKey) {
|
||||
assert assigned == resizeAt && (((KType) keys[slot]) == null) && !((pendingKey) == null);
|
||||
|
||||
// Try to allocate new buffers first. If we OOM, we leave in a consistent state.
|
||||
final KType[] prevKeys = (KType[]) this.keys;
|
||||
allocateBuffers(nextBufferSize(mask + 1, size(), loadFactor));
|
||||
assert this.keys.length > prevKeys.length;
|
||||
|
||||
// We have succeeded at allocating new data so insert the pending key/value at
|
||||
// the free slot in the old arrays before rehashing.
|
||||
prevKeys[slot] = pendingKey;
|
||||
|
||||
// Rehash old keys, including the pending key.
|
||||
rehash(prevKeys);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shift all the slot-conflicting keys allocated to (and including)
|
||||
* <code>slot</code>.
|
||||
*/
|
||||
protected void shiftConflictingKeys(int gapSlot) {
|
||||
final KType[] keys = (KType[]) this.keys;
|
||||
final int mask = this.mask;
|
||||
|
||||
// Perform shifts of conflicting keys to fill in the gap.
|
||||
int distance = 0;
|
||||
while (true) {
|
||||
final int slot = (gapSlot + (++distance)) & mask;
|
||||
final KType existing = keys[slot];
|
||||
if (((existing) == null)) {
|
||||
break;
|
||||
}
|
||||
|
||||
final int idealSlot = hashKey(existing);
|
||||
final int shift = (slot - idealSlot) & mask;
|
||||
if (shift >= distance) {
|
||||
// Entry at this position was originally at or before the gap slot.
|
||||
// Move the conflict-shifted entry to the gap's position and repeat the
|
||||
// procedure
|
||||
// for any entries to the right of the current position, treating it
|
||||
// as the new gap.
|
||||
keys[gapSlot] = existing;
|
||||
gapSlot = slot;
|
||||
distance = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Mark the last found gap slot without a conflict as empty.
|
||||
keys[gapSlot] = null;
|
||||
assigned--;
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.Containers.*;
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.HashContainers.*;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.ObjectContainer;
|
||||
|
||||
/** A reference-equality (identity) hash set. */
|
||||
public class ObjectIdentityHashSet<KType> extends ObjectHashSet<KType> {
|
||||
/** New instance with sane defaults. */
|
||||
public ObjectIdentityHashSet() {
|
||||
this(DEFAULT_EXPECTED_ELEMENTS, DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
/** New instance with sane defaults. */
|
||||
public ObjectIdentityHashSet(int expectedElements) {
|
||||
this(expectedElements, DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with the provided defaults.
|
||||
*
|
||||
* @param expectedElements The expected number of elements guaranteed not to
|
||||
* cause a rehash (inclusive).
|
||||
* @param loadFactor The load factor for internal buffers. Insane load
|
||||
* factors (zero, full capacity) are rejected by
|
||||
* {@link #verifyLoadFactor(double)}.
|
||||
*/
|
||||
public ObjectIdentityHashSet(int expectedElements, double loadFactor) {
|
||||
super(expectedElements, loadFactor);
|
||||
}
|
||||
|
||||
/** New instance copying elements from another {@link ObjectContainer}. */
|
||||
public ObjectIdentityHashSet(ObjectContainer<? extends KType> container) {
|
||||
this(container.size());
|
||||
addAll(container);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int hashKey(KType key) {
|
||||
assert key != null; // Handled as a special case (empty slot marker).
|
||||
return BitMixer.mixPhi(System.identityHashCode(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean equals(Object v1, Object v2) {
|
||||
return v1 == v2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a set from a variable number of arguments or an array of
|
||||
* <code>KType</code>. The elements are copied from the argument to the internal
|
||||
* buffer.
|
||||
*/
|
||||
@SafeVarargs
|
||||
public static <KType> ObjectIdentityHashSet<KType> from(KType... elements) {
|
||||
final ObjectIdentityHashSet<KType> set = new ObjectIdentityHashSet<KType>(elements.length);
|
||||
set.addAll(elements);
|
||||
return set;
|
||||
}
|
||||
}
|
||||
+1093
File diff suppressed because it is too large
Load Diff
+79
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.Containers.*;
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.HashContainers.*;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.*;
|
||||
|
||||
/** An identity hash map of <code>Object</code> to <code>int</code>. */
|
||||
public class ObjectIntIdentityHashMap<KType> extends ObjectIntHashMap<KType> {
|
||||
/** New instance with sane defaults. */
|
||||
public ObjectIntIdentityHashMap() {
|
||||
this(DEFAULT_EXPECTED_ELEMENTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with sane defaults.
|
||||
*
|
||||
* @param expectedElements The expected number of elements guaranteed not to
|
||||
* cause buffer expansion (inclusive).
|
||||
*/
|
||||
public ObjectIntIdentityHashMap(int expectedElements) {
|
||||
this(expectedElements, DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with the provided defaults.
|
||||
*
|
||||
* @param expectedElements The expected number of elements guaranteed not to
|
||||
* cause a rehash (inclusive).
|
||||
* @param loadFactor The load factor for internal buffers. Insane load
|
||||
* factors (zero, full capacity) are rejected by
|
||||
* {@link #verifyLoadFactor(double)}.
|
||||
*/
|
||||
public ObjectIntIdentityHashMap(int expectedElements, double loadFactor) {
|
||||
super(expectedElements, loadFactor);
|
||||
}
|
||||
|
||||
/** Create a hash map from all key-value pairs of another container. */
|
||||
public ObjectIntIdentityHashMap(ObjectIntAssociativeContainer<? extends KType> container) {
|
||||
this(container.size());
|
||||
putAll(container);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashKey(KType key) {
|
||||
assert !((key) == null); // Handled as a special case (empty slot marker).
|
||||
return BitMixer.mixPhi(System.identityHashCode(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object v1, Object v2) {
|
||||
return v1 == v2;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
|
||||
/** Creates a hash map from two index-aligned arrays of key-value pairs. */
|
||||
public static <KType> ObjectIntIdentityHashMap<KType> from(KType[] keys, int[] values) {
|
||||
if (keys.length != values.length) {
|
||||
throw new IllegalArgumentException("Arrays of keys and values must have an identical length.");
|
||||
}
|
||||
|
||||
ObjectIntIdentityHashMap<KType> map = new ObjectIntIdentityHashMap<>(keys.length);
|
||||
for (int i = 0; i < keys.length; i++) {
|
||||
map.put(keys[i], values[i]);
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
}
|
||||
+1057
File diff suppressed because it is too large
Load Diff
+94
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.Containers.*;
|
||||
import static net.lax1dude.eaglercraft.backend.server.base.collect.HashContainers.*;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.api.collect.*;
|
||||
|
||||
/** An identity hash map of <code>Object</code> to <code>Object</code>. */
|
||||
public class ObjectObjectIdentityHashMap<KType, VType> extends ObjectObjectHashMap<KType, VType> {
|
||||
/** New instance with sane defaults. */
|
||||
public ObjectObjectIdentityHashMap() {
|
||||
this(DEFAULT_EXPECTED_ELEMENTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with sane defaults.
|
||||
*
|
||||
* @param expectedElements The expected number of elements guaranteed not to
|
||||
* cause buffer expansion (inclusive).
|
||||
*/
|
||||
public ObjectObjectIdentityHashMap(int expectedElements) {
|
||||
this(expectedElements, DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* New instance with the provided defaults.
|
||||
*
|
||||
* @param expectedElements The expected number of elements guaranteed not to
|
||||
* cause a rehash (inclusive).
|
||||
* @param loadFactor The load factor for internal buffers. Insane load
|
||||
* factors (zero, full capacity) are rejected by
|
||||
* {@link #verifyLoadFactor(double)}.
|
||||
*/
|
||||
public ObjectObjectIdentityHashMap(int expectedElements, double loadFactor) {
|
||||
super(expectedElements, loadFactor);
|
||||
}
|
||||
|
||||
/** Create a hash map from all key-value pairs of another container. */
|
||||
public ObjectObjectIdentityHashMap(ObjectObjectAssociativeContainer<? extends KType, ? extends VType> container) {
|
||||
this(container.size());
|
||||
putAll(container);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashKey(KType key) {
|
||||
assert !((key) == null); // Handled as a special case (empty slot marker).
|
||||
return BitMixer.mixPhi(System.identityHashCode(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object v1, Object v2) {
|
||||
return v1 == v2;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
protected boolean equalElements(ObjectObjectHashMap<?, ?> other) {
|
||||
if (other.size() != size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (ObjectObjectCursor<?, ?> c : other) {
|
||||
KType key = (KType) c.key;
|
||||
if (!containsKey(key) || !equals(c.value, get(key))) { // Compare values using the same function as keys.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Creates a hash map from two index-aligned arrays of key-value pairs. */
|
||||
public static <KType, VType> ObjectObjectIdentityHashMap<KType, VType> from(KType[] keys, VType[] values) {
|
||||
if (keys.length != values.length) {
|
||||
throw new IllegalArgumentException("Arrays of keys and values must have an identical length.");
|
||||
}
|
||||
|
||||
ObjectObjectIdentityHashMap<KType, VType> map = new ObjectObjectIdentityHashMap<>(keys.length);
|
||||
for (int i = 0; i < keys.length; i++) {
|
||||
map.put(keys[i], values[i]);
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
/*
|
||||
* HPPC
|
||||
*
|
||||
* Copyright (C) 2010-2024 Carrot Search s.c. and contributors
|
||||
* All rights reserved.
|
||||
*
|
||||
* Refer to the full license file "LICENSE.txt":
|
||||
* https://github.com/carrotsearch/hppc/blob/master/LICENSE.txt
|
||||
*/
|
||||
package net.lax1dude.eaglercraft.backend.server.base.collect;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Helper class that helps estimate memory usage
|
||||
*
|
||||
* <p>
|
||||
* Mostly forked from Lucene tag releases/lucene-solr/8.5.1
|
||||
*/
|
||||
final class RamUsageEstimator {
|
||||
/** No instantiation. */
|
||||
private RamUsageEstimator() {
|
||||
}
|
||||
|
||||
/** True, iff compressed references (oops) are enabled by this JVM */
|
||||
static final boolean COMPRESSED_REFS_ENABLED;
|
||||
|
||||
/** Number of bytes this JVM uses to represent an object reference. */
|
||||
static final int NUM_BYTES_OBJECT_REF;
|
||||
|
||||
/** Number of bytes to represent an object header (no fields, no alignments). */
|
||||
static final int NUM_BYTES_OBJECT_HEADER;
|
||||
|
||||
/**
|
||||
* Number of bytes to represent an array header (no content, but with
|
||||
* alignments).
|
||||
*/
|
||||
static final int NUM_BYTES_ARRAY_HEADER;
|
||||
|
||||
/**
|
||||
* A constant specifying the object alignment boundary inside the JVM. Objects
|
||||
* will always take a full multiple of this constant, possibly wasting some
|
||||
* space.
|
||||
*/
|
||||
static final int NUM_BYTES_OBJECT_ALIGNMENT;
|
||||
|
||||
/** Sizes of primitive classes. */
|
||||
static final Map<Class<?>, Integer> primitiveSizes;
|
||||
|
||||
static {
|
||||
Map<Class<?>, Integer> primitiveSizesMap = new IdentityHashMap<>();
|
||||
primitiveSizesMap.put(boolean.class, 1);
|
||||
primitiveSizesMap.put(byte.class, 1);
|
||||
primitiveSizesMap.put(char.class, Character.BYTES);
|
||||
primitiveSizesMap.put(short.class, Short.BYTES);
|
||||
primitiveSizesMap.put(int.class, Integer.BYTES);
|
||||
primitiveSizesMap.put(float.class, Float.BYTES);
|
||||
primitiveSizesMap.put(double.class, Double.BYTES);
|
||||
primitiveSizesMap.put(long.class, Long.BYTES);
|
||||
|
||||
primitiveSizes = Collections.unmodifiableMap(primitiveSizesMap);
|
||||
}
|
||||
|
||||
static final boolean JRE_IS_64BIT;
|
||||
|
||||
static final String MANAGEMENT_FACTORY_CLASS = "java.lang.management.ManagementFactory";
|
||||
static final String HOTSPOT_BEAN_CLASS = "com.sun.management.HotSpotDiagnosticMXBean";
|
||||
|
||||
static final String OS_ARCH = System.getProperty("os.arch");
|
||||
|
||||
// Initialize constants and try to collect information about the JVM internals.
|
||||
static {
|
||||
boolean is64Bit = false;
|
||||
String datamodel = null;
|
||||
try {
|
||||
datamodel = System.getProperty("sun.arch.data.model");
|
||||
if (datamodel != null) {
|
||||
is64Bit = datamodel.contains("64");
|
||||
}
|
||||
} catch (SecurityException ignored) {
|
||||
}
|
||||
if (datamodel == null) {
|
||||
is64Bit = OS_ARCH != null && OS_ARCH.contains("64");
|
||||
}
|
||||
JRE_IS_64BIT = is64Bit;
|
||||
if (JRE_IS_64BIT) {
|
||||
// Try to get compressed oops and object alignment (the default seems to be 8 on
|
||||
// Hotspot);
|
||||
// (this only works on 64 bit, on 32 bits the alignment and reference size is
|
||||
// fixed):
|
||||
boolean compressedOops = false;
|
||||
int objectAlignment = 8;
|
||||
try {
|
||||
final Class<?> beanClazz = Class.forName(HOTSPOT_BEAN_CLASS);
|
||||
// we use reflection for this, because the management factory is not part
|
||||
// of Java 8's compact profile:
|
||||
final Object hotSpotBean = Class.forName(MANAGEMENT_FACTORY_CLASS)
|
||||
.getMethod("getPlatformMXBean", Class.class).invoke(null, beanClazz);
|
||||
if (hotSpotBean != null) {
|
||||
final Method getVMOptionMethod = beanClazz.getMethod("getVMOption", String.class);
|
||||
try {
|
||||
final Object vmOption = getVMOptionMethod.invoke(hotSpotBean, "UseCompressedOops");
|
||||
compressedOops = Boolean
|
||||
.parseBoolean(vmOption.getClass().getMethod("getValue").invoke(vmOption).toString());
|
||||
} catch (ReflectiveOperationException | RuntimeException ignored) {
|
||||
}
|
||||
try {
|
||||
final Object vmOption = getVMOptionMethod.invoke(hotSpotBean, "ObjectAlignmentInBytes");
|
||||
objectAlignment = Integer
|
||||
.parseInt(vmOption.getClass().getMethod("getValue").invoke(vmOption).toString());
|
||||
} catch (ReflectiveOperationException | RuntimeException ignored) {
|
||||
}
|
||||
}
|
||||
} catch (ReflectiveOperationException | RuntimeException ignored) {
|
||||
}
|
||||
COMPRESSED_REFS_ENABLED = compressedOops;
|
||||
NUM_BYTES_OBJECT_ALIGNMENT = objectAlignment;
|
||||
// reference size is 4, if we have compressed oops:
|
||||
NUM_BYTES_OBJECT_REF = COMPRESSED_REFS_ENABLED ? 4 : 8;
|
||||
// "best guess" based on reference size:
|
||||
NUM_BYTES_OBJECT_HEADER = 8 + NUM_BYTES_OBJECT_REF;
|
||||
// array header is NUM_BYTES_OBJECT_HEADER + NUM_BYTES_INT, but aligned (object
|
||||
// alignment):
|
||||
NUM_BYTES_ARRAY_HEADER = (int) alignObjectSize(NUM_BYTES_OBJECT_HEADER + Integer.BYTES);
|
||||
} else {
|
||||
COMPRESSED_REFS_ENABLED = false;
|
||||
NUM_BYTES_OBJECT_ALIGNMENT = 8;
|
||||
NUM_BYTES_OBJECT_REF = 4;
|
||||
NUM_BYTES_OBJECT_HEADER = 8;
|
||||
// For 32 bit JVMs, no extra alignment of array header:
|
||||
NUM_BYTES_ARRAY_HEADER = NUM_BYTES_OBJECT_HEADER + Integer.BYTES;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Aligns an object size to be the next multiple of
|
||||
* {@link #NUM_BYTES_OBJECT_ALIGNMENT}.
|
||||
*/
|
||||
static long alignObjectSize(long size) {
|
||||
size += (long) NUM_BYTES_OBJECT_ALIGNMENT - 1L;
|
||||
return size - (size % NUM_BYTES_OBJECT_ALIGNMENT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return used part of shallow size of any <code>array</code>.
|
||||
*
|
||||
* @param usedSize Size that array is actually used
|
||||
*/
|
||||
static long shallowUsedSizeOfArray(Object array, int usedSize) {
|
||||
long size = NUM_BYTES_ARRAY_HEADER;
|
||||
if (usedSize > 0) {
|
||||
Class<?> arrayElementClazz = array.getClass().getComponentType();
|
||||
if (arrayElementClazz.isPrimitive()) {
|
||||
size += (long) usedSize * primitiveSizes.get(arrayElementClazz);
|
||||
} else {
|
||||
size += (long) NUM_BYTES_OBJECT_REF * usedSize;
|
||||
}
|
||||
}
|
||||
return alignObjectSize(size);
|
||||
}
|
||||
|
||||
/** Return shallow size of any <code>array</code>. */
|
||||
static long shallowSizeOfArray(Object array) {
|
||||
return shallowUsedSizeOfArray(array, Array.getLength(array));
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base.command;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IEaglerXServerCommandType;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformCommandSender;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformComponentBuilder.EnumChatColor;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.brand.IBrandRegistration;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.BasePlayerInstance;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.EaglerPlayerInstance;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.EaglerXServer;
|
||||
|
||||
public class CommandBrand<PlayerObject> extends EaglerCommand<PlayerObject> {
|
||||
|
||||
public CommandBrand(EaglerXServer<PlayerObject> server) {
|
||||
super(server, "brand", "eaglercraft.command.brand", "eaglerbrand", "eagler-brand");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(IEaglerXServerCommandType<PlayerObject> command, IPlatformCommandSender<PlayerObject> sender,
|
||||
String[] args) {
|
||||
if (args.length == 0 && sender.isPlayer()) {
|
||||
handle(sender, sender.asPlayer().getPlayerAttachment(), true, true, true);
|
||||
return;
|
||||
} else if (args.length == 1) {
|
||||
BasePlayerInstance<PlayerObject> player = getServer().getPlayerByName(args[0]);
|
||||
if (player != null) {
|
||||
handle(sender, player, true, true, true);
|
||||
return;
|
||||
} else {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.RED).end()
|
||||
.text("Player \"" + args[0] + "\" was not found").end());
|
||||
}
|
||||
} else if (args.length == 2) {
|
||||
BasePlayerInstance<PlayerObject> player = getServer().getPlayerByName(args[1]);
|
||||
if (player != null) {
|
||||
String s = args[0].toLowerCase();
|
||||
boolean a = "name".equals(s);
|
||||
boolean b = !a && "uuid".equals(s);
|
||||
boolean c = !a && !b && "mc".equals(s);
|
||||
if (a || b || c) {
|
||||
handle(sender, player, a, b, c);
|
||||
return;
|
||||
} else {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.RED).end()
|
||||
.text("Unknown brand lookup type \"" + args[0] + "\"").end());
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.RED).end()
|
||||
.text("Player \"" + args[1] + "\" was not found").end());
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.RED).end()
|
||||
.text("Invalid number of arguments").end());
|
||||
}
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.RED).end()
|
||||
.text("Usage: /brand [name|uuid|mc] <username>").end());
|
||||
}
|
||||
|
||||
private void handle(IPlatformCommandSender<PlayerObject> sender, BasePlayerInstance<PlayerObject> player,
|
||||
boolean name, boolean uuid, boolean mc) {
|
||||
if (name) {
|
||||
if (player.isEaglerPlayer()) {
|
||||
EaglerPlayerInstance<PlayerObject> eagPlayer = player.asEaglerPlayer();
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.AQUA).end()
|
||||
.text("Eagler Client Brand: ").appendTextComponent().beginStyle().color(EnumChatColor.GOLD)
|
||||
.end().text(eagPlayer.getEaglerBrandString()).end().end());
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.AQUA).end()
|
||||
.text("Eagler Client Version: ").appendTextComponent().beginStyle().color(EnumChatColor.GOLD)
|
||||
.end().text(eagPlayer.getEaglerVersionString()).end().end());
|
||||
} else {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.AQUA).end()
|
||||
.text("Player is not using Eaglercraft").end());
|
||||
}
|
||||
}
|
||||
if (uuid) {
|
||||
UUID brandUUID = player.getEaglerBrandUUID();
|
||||
IBrandRegistration registeredBrand = getServer().getBrandService().lookupRegisteredBrand(brandUUID);
|
||||
if (registeredBrand != null) {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.AQUA).end()
|
||||
.text("Eagler Client UUID: ").appendTextComponent().beginStyle().color(EnumChatColor.GOLD).end()
|
||||
.text(brandUUID.toString()).end().appendTextComponent().beginStyle().color(EnumChatColor.AQUA)
|
||||
.end().text(" (").end().appendTextComponent().beginStyle().color(EnumChatColor.GOLD).end()
|
||||
.text(registeredBrand.getBrandDesc()).end().appendTextComponent().beginStyle()
|
||||
.color(EnumChatColor.AQUA).end().text(")").end().end());
|
||||
} else {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.AQUA).end()
|
||||
.text("Eagler Client UUID: ").appendTextComponent().beginStyle().color(EnumChatColor.GOLD).end()
|
||||
.text(brandUUID.toString()).end().appendTextComponent().beginStyle().color(EnumChatColor.AQUA)
|
||||
.end().text(" (Unknown)").end().end());
|
||||
}
|
||||
}
|
||||
if (mc) {
|
||||
String mcBrand = player.getMinecraftBrand();
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.AQUA).end()
|
||||
.text("Minecraft Client Brand: ").appendTextComponent().beginStyle()
|
||||
.color(mcBrand != null ? EnumChatColor.GOLD : EnumChatColor.AQUA).end()
|
||||
.text(mcBrand != null ? mcBrand : "(null)").end().end());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base.command;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IEaglerXServerCommandType;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformCommandSender;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformComponentBuilder.EnumChatColor;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.EaglerXServer;
|
||||
import net.lax1dude.eaglercraft.backend.server.util.Util;
|
||||
|
||||
public class CommandConfirmCode<PlayerObject> extends EaglerCommand<PlayerObject> {
|
||||
|
||||
public CommandConfirmCode(EaglerXServer<PlayerObject> server) {
|
||||
super(server, "confirm-code", "eaglercraft.command.confirmcode", "confirmcode");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(IEaglerXServerCommandType<PlayerObject> command, IPlatformCommandSender<PlayerObject> sender,
|
||||
String[] args) {
|
||||
if (args.length != 1) {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.RED).end()
|
||||
.text("How to use: ").appendTextComponent().beginStyle().color(EnumChatColor.WHITE).end()
|
||||
.text("/confirm-code <code>").end().end());
|
||||
} else {
|
||||
getServer().setServerListConfirmCode(Util.hash2string(Util.sha1(args[0].getBytes(StandardCharsets.US_ASCII))));
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.AQUA).end()
|
||||
.text("Server list 2FA code has been set to: ").appendTextComponent().beginStyle()
|
||||
.color(EnumChatColor.GOLD).end().text(args[0]).end().end());
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.AQUA).end()
|
||||
.text("You can now return to the server list site and continue").end());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* Copyright (c) 2025 lax1dude. All Rights Reserved.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
*/
|
||||
|
||||
package net.lax1dude.eaglercraft.backend.server.base.command;
|
||||
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IEaglerXServerCommandType;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformCommandSender;
|
||||
import net.lax1dude.eaglercraft.backend.server.adapter.IPlatformComponentBuilder.EnumChatColor;
|
||||
import net.lax1dude.eaglercraft.backend.server.api.EnumWebSocketHeader;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.BasePlayerInstance;
|
||||
import net.lax1dude.eaglercraft.backend.server.base.EaglerXServer;
|
||||
|
||||
public class CommandDomain<PlayerObject> extends EaglerCommand<PlayerObject> {
|
||||
|
||||
public CommandDomain(EaglerXServer<PlayerObject> server) {
|
||||
super(server, "domain", "eaglercraft.command.domain", "eaglerdomain", "eagler-domain");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(IEaglerXServerCommandType<PlayerObject> command, IPlatformCommandSender<PlayerObject> sender,
|
||||
String[] args) {
|
||||
if (args.length == 0 && sender.isPlayer()) {
|
||||
handle(sender, sender.asPlayer().getPlayerAttachment());
|
||||
return;
|
||||
} else if (args.length == 1) {
|
||||
BasePlayerInstance<PlayerObject> player = getServer().getPlayerByName(args[0]);
|
||||
if (player != null) {
|
||||
handle(sender, player);
|
||||
return;
|
||||
} else {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.RED).end()
|
||||
.text("Player \"" + args[0] + "\" was not found").end());
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.RED).end()
|
||||
.text("Invalid number of arguments").end());
|
||||
}
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.RED).end()
|
||||
.text("Usage: /domain <username>").end());
|
||||
}
|
||||
|
||||
private void handle(IPlatformCommandSender<PlayerObject> sender, BasePlayerInstance<PlayerObject> player) {
|
||||
if (player.isEaglerPlayer()) {
|
||||
String origin = player.asEaglerPlayer().getWebSocketHeader(EnumWebSocketHeader.HEADER_ORIGIN);
|
||||
if (origin != null) {
|
||||
if ("null".equals(origin)) {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.BLUE)
|
||||
.end().text("The player " + player.getUsername() + " is using an offline download").end());
|
||||
} else {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.BLUE)
|
||||
.end().text("The player " + player.getUsername() + "'s domain is \"" + origin + "\"")
|
||||
.end());
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(getChatBuilder()
|
||||
.buildTextComponent().beginStyle().color(EnumChatColor.BLUE).end().text("The player "
|
||||
+ player.getUsername() + " is using a browser that did not send an origin header")
|
||||
.end());
|
||||
}
|
||||
} else {
|
||||
sender.sendMessage(getChatBuilder().buildTextComponent().beginStyle().color(EnumChatColor.BLUE).end()
|
||||
.text("The player " + player.getUsername() + " is not using Eaglercraft").end());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user