├── README.md ├── src └── main │ ├── java │ └── org │ │ └── itxtech │ │ └── synapseapi │ │ ├── event │ │ ├── SynapseEvent.java │ │ └── player │ │ │ ├── SynapsePlayerEvent.java │ │ │ ├── SynapseFullServerPlayerTransferEvent.java │ │ │ ├── SynapsePlayerTransferEvent.java │ │ │ ├── SynapsePlayerConnectEvent.java │ │ │ └── SynapsePlayerCreationEvent.java │ │ ├── messaging │ │ ├── PluginMessageListener.java │ │ ├── ReservedChannelException.java │ │ ├── ChannelNotRegisteredException.java │ │ ├── ChannelNameTooLongException.java │ │ ├── MessageTooLargeException.java │ │ ├── Messenger.java │ │ ├── PluginMessageListenerRegistration.java │ │ └── StandardMessenger.java │ │ ├── network │ │ ├── protocol │ │ │ └── spp │ │ │ │ ├── SynapseInfo.java │ │ │ │ ├── PluginMessagePacket.java │ │ │ │ ├── PlayerLogoutPacket.java │ │ │ │ ├── TransferPacket.java │ │ │ │ ├── HeartbeatPacket.java │ │ │ │ ├── DisconnectPacket.java │ │ │ │ ├── RedirectPacket.java │ │ │ │ ├── InformationPacket.java │ │ │ │ ├── PlayerCountPacket.java │ │ │ │ ├── SynapseDataPacket.java │ │ │ │ ├── BroadcastPacket.java │ │ │ │ ├── PlayerLoginPacket.java │ │ │ │ └── ConnectPacket.java │ │ ├── synlib │ │ │ ├── SynapseContextException.java │ │ │ ├── SynapseProtocolHeader.java │ │ │ ├── SynapsePacketEncoder.java │ │ │ ├── SynapseClientInitializer.java │ │ │ ├── SynapsePacketDecoder.java │ │ │ ├── SynapseClientHandler.java │ │ │ ├── Session.java │ │ │ └── SynapseClient.java │ │ ├── SynLibInterface.java │ │ └── SynapseInterface.java │ │ ├── runnable │ │ └── TransferRunnable.java │ │ ├── utils │ │ ├── ClientData.java │ │ └── DataPacketEidReplacer.java │ │ ├── SynapseAPI.java │ │ ├── SynapseEntry.java │ │ └── SynapsePlayer.java │ └── resources │ ├── config.yml │ └── plugin.yml ├── .circleci └── config.yml ├── .gitignore ├── pom.xml └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | Custom version of [Synapse API](https://github.com/CloudburstMC/SynapseAPI) for [NemisysProxy](https://github.com/PetteriM1/NemisysProxy) 2 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/event/SynapseEvent.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.event; 2 | 3 | import cn.nukkit.event.Event; 4 | 5 | /** 6 | * Created by boybook on 16/6/25. 7 | */ 8 | public class SynapseEvent extends Event { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/resources/config.yml: -------------------------------------------------------------------------------- 1 | lobbies: 2 | - "lobby" 3 | 4 | entries: 5 | - server-ip: 127.0.0.1 6 | server-port: 10305 7 | isLobbyServer: true 8 | transferOnShutdown: true 9 | password: must16keyslength 10 | description: Synapse Nukkit Server 11 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/messaging/PluginMessageListener.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.messaging; 2 | 3 | import org.itxtech.synapseapi.SynapseEntry; 4 | 5 | public interface PluginMessageListener { 6 | 7 | void onPluginMessageReceived(SynapseEntry entry, String channel, byte[] message); 8 | } 9 | 10 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | 5 | working_directory: ~/SynapseAPI 6 | 7 | docker: 8 | - image: cimg/openjdk:8.0 9 | 10 | steps: 11 | 12 | - checkout 13 | 14 | - run: mvn clean package 15 | 16 | - store_artifacts: 17 | path: target/SynapseAPI-PM1E.jar 18 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/messaging/ReservedChannelException.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.messaging; 2 | 3 | public class ReservedChannelException extends RuntimeException { 4 | 5 | public ReservedChannelException() { 6 | this("Attempted to register for a reserved channel name."); 7 | } 8 | 9 | public ReservedChannelException(String name) { 10 | super("Attempted to register for a reserved channel name ('" + name + "')"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/messaging/ChannelNotRegisteredException.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.messaging; 2 | 3 | public class ChannelNotRegisteredException extends RuntimeException { 4 | 5 | public ChannelNotRegisteredException() { 6 | this("Attempted to send a plugin message through an unregistered channel."); 7 | } 8 | 9 | public ChannelNotRegisteredException(String channel) { 10 | super("Attempted to send a plugin message through the unregistered channel `" + channel + "'."); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/event/player/SynapsePlayerEvent.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.event.player; 2 | 3 | import org.itxtech.synapseapi.SynapsePlayer; 4 | import org.itxtech.synapseapi.event.SynapseEvent; 5 | 6 | /** 7 | * Created by boybook on 16/6/25. 8 | */ 9 | public class SynapsePlayerEvent extends SynapseEvent { 10 | 11 | protected SynapsePlayer player; 12 | 13 | public SynapsePlayerEvent(SynapsePlayer player) { 14 | this.player = player; 15 | } 16 | 17 | public SynapsePlayer getPlayer() { 18 | return player; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/messaging/ChannelNameTooLongException.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.messaging; 2 | 3 | public class ChannelNameTooLongException extends RuntimeException { 4 | 5 | public ChannelNameTooLongException() { 6 | super("Attempted to send a Plugin Message to a channel that was too large. The maximum length is 20 chars."); 7 | } 8 | 9 | public ChannelNameTooLongException(String channel) { 10 | super("Attempted to send a Plugin Message to a channel that was too large. The maximum length is 20 chars (attempted " + channel.length() + " - '" + channel + '.'); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/SynapseInfo.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | public interface SynapseInfo { 4 | 5 | int CURRENT_PROTOCOL = 100202; 6 | 7 | byte HEARTBEAT_PACKET = 0x01; 8 | byte CONNECT_PACKET = 0x02; 9 | byte DISCONNECT_PACKET = 0x03; 10 | byte REDIRECT_PACKET = 0x04; 11 | byte PLAYER_LOGIN_PACKET = 0x05; 12 | byte PLAYER_LOGOUT_PACKET = 0x06; 13 | byte INFORMATION_PACKET = 0x07; 14 | byte TRANSFER_PACKET = 0x08; 15 | byte BROADCAST_PACKET = 0x09; 16 | byte PLUGIN_MESSAGE_PACKET = 0x0a; 17 | byte PLAYER_COUNT_PACKET = 0x0b; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/synlib/SynapseContextException.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.synlib; 2 | 3 | /** 4 | * SynapseContextException 5 | * =============== 6 | * author: boybook 7 | * Nemisys Project 8 | * =============== 9 | */ 10 | public class SynapseContextException extends Exception { 11 | 12 | public SynapseContextException(String message) { 13 | super(message); 14 | } 15 | 16 | public SynapseContextException(String message, Throwable cause) { 17 | super(message, cause); 18 | } 19 | 20 | public SynapseContextException(Throwable cause) { 21 | super(cause); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/event/player/SynapseFullServerPlayerTransferEvent.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.event.player; 2 | 3 | import cn.nukkit.event.Cancellable; 4 | import cn.nukkit.event.HandlerList; 5 | import org.itxtech.synapseapi.SynapsePlayer; 6 | 7 | public class SynapseFullServerPlayerTransferEvent extends SynapsePlayerEvent implements Cancellable { 8 | 9 | private static final HandlerList handlers = new HandlerList(); 10 | 11 | public SynapseFullServerPlayerTransferEvent(SynapsePlayer player) { 12 | super(player); 13 | } 14 | 15 | public static HandlerList getHandlers() { 16 | return handlers; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/PluginMessagePacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | /** 4 | * @author CreeperFace 5 | */ 6 | public class PluginMessagePacket extends SynapseDataPacket { 7 | 8 | public String channel; 9 | public byte[] data; 10 | 11 | @Override 12 | public byte pid() { 13 | return SynapseInfo.PLUGIN_MESSAGE_PACKET; 14 | } 15 | 16 | @Override 17 | public void encode() { 18 | this.reset(); 19 | this.putString(this.channel); 20 | this.putByteArray(this.data); 21 | } 22 | 23 | @Override 24 | public void decode() { 25 | this.channel = this.getString(); 26 | this.data = this.getByteArray(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/PlayerLogoutPacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | import java.util.UUID; 4 | 5 | /** 6 | * Created by boybook on 16/6/24. 7 | */ 8 | public class PlayerLogoutPacket extends SynapseDataPacket { 9 | 10 | public UUID uuid; 11 | public String reason; 12 | 13 | @Override 14 | public byte pid() { 15 | return SynapseInfo.PLAYER_LOGOUT_PACKET; 16 | } 17 | 18 | @Override 19 | public void encode() { 20 | this.reset(); 21 | this.putUUID(this.uuid); 22 | this.putString(this.reason); 23 | } 24 | 25 | @Override 26 | public void decode() { 27 | this.uuid = this.getUUID(); 28 | this.reason = this.getString(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/TransferPacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | import java.util.UUID; 4 | 5 | /** 6 | * Created by boybook on 16/6/24. 7 | */ 8 | public class TransferPacket extends SynapseDataPacket { 9 | 10 | public UUID uuid; 11 | public String clientHash; 12 | 13 | @Override 14 | public byte pid() { 15 | return SynapseInfo.TRANSFER_PACKET; 16 | } 17 | 18 | @Override 19 | public void encode() { 20 | this.reset(); 21 | this.putUUID(this.uuid); 22 | this.putString(this.clientHash); 23 | } 24 | 25 | @Override 26 | public void decode() { 27 | this.uuid = this.getUUID(); 28 | this.clientHash = this.getString(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/messaging/MessageTooLargeException.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.messaging; 2 | 3 | public class MessageTooLargeException extends RuntimeException { 4 | 5 | public MessageTooLargeException() { 6 | this("Attempted to send a plugin message that was too large. The maximum length is 32766 bytes."); 7 | } 8 | 9 | public MessageTooLargeException(byte[] message) { 10 | this(message.length); 11 | } 12 | 13 | public MessageTooLargeException(int length) { 14 | this("Attempted to send a plugin message that was too large. The maximum length is 32766 bytes (tried to send one that is " + length + " bytes long)."); 15 | } 16 | 17 | public MessageTooLargeException(String msg) { 18 | super(msg); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/synlib/SynapseProtocolHeader.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.synlib; 2 | 3 | /** 4 | * SynapseProtocolHeader 5 | * =============== 6 | * author: boybook 7 | * Synapse Protocol Header 8 | * nemisys 9 | * =============== 10 | */ 11 | public class SynapseProtocolHeader { 12 | 13 | /** 14 | * Magic 15 | */ 16 | public static final short MAGIC = (short) 0xbabe; 17 | 18 | private int pid; 19 | private int bodyLength; 20 | 21 | public int pid() { 22 | return pid; 23 | } 24 | 25 | public void pid(int pid) { 26 | this.pid = pid; 27 | } 28 | 29 | public int bodyLength() { 30 | return bodyLength; 31 | } 32 | 33 | public void bodyLength(int bodyLength) { 34 | this.bodyLength = bodyLength; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/runnable/TransferRunnable.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.runnable; 2 | 3 | import org.itxtech.synapseapi.SynapsePlayer; 4 | import org.itxtech.synapseapi.network.protocol.spp.TransferPacket; 5 | 6 | /** 7 | * Created by boybook on 16/9/26. 8 | */ 9 | public class TransferRunnable implements Runnable { 10 | 11 | private final SynapsePlayer player; 12 | private final String hash; 13 | 14 | public TransferRunnable(SynapsePlayer player, String hash) { 15 | this.player = player; 16 | this.hash = hash; 17 | } 18 | 19 | @Override 20 | public void run() { 21 | TransferPacket pk = new TransferPacket(); 22 | pk.uuid = this.player.getUniqueId(); 23 | pk.clientHash = hash; 24 | this.player.getSynapseEntry().sendDataPacket(pk); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/HeartbeatPacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | /** 4 | * Created by boybook on 16/6/24. 5 | */ 6 | public class HeartbeatPacket extends SynapseDataPacket { 7 | 8 | public float tps; 9 | public float load; 10 | public long upTime; 11 | 12 | @Override 13 | public byte pid() { 14 | return SynapseInfo.HEARTBEAT_PACKET; 15 | } 16 | 17 | @Override 18 | public void encode() { 19 | this.reset(); 20 | this.putFloat(this.tps); 21 | this.putFloat(this.load); 22 | this.putLong(this.upTime); 23 | } 24 | 25 | @Override 26 | public void decode() { 27 | this.tps = this.getFloat(); 28 | this.load = this.getFloat(); 29 | this.upTime = this.getLong(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/DisconnectPacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | /** 4 | * Created by boybook on 16/6/24. 5 | */ 6 | public class DisconnectPacket extends SynapseDataPacket { 7 | 8 | public static final byte TYPE_WRONG_PROTOCOL = 0; 9 | public static final byte TYPE_GENERIC = 1; 10 | public byte type; 11 | public String message; 12 | 13 | @Override 14 | public byte pid() { 15 | return SynapseInfo.DISCONNECT_PACKET; 16 | } 17 | 18 | @Override 19 | public void encode() { 20 | this.reset(); 21 | this.putByte(this.type); 22 | this.putString(this.message); 23 | } 24 | 25 | @Override 26 | public void decode() { 27 | this.type = (byte) this.getByte(); 28 | this.message = this.getString(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/resources/plugin.yml: -------------------------------------------------------------------------------- 1 | name: SynapseAPI 2 | main: org.itxtech.synapseapi.SynapseAPI 3 | version: "PM1E" 4 | api: "9.9.9" 5 | load: STARTUP 6 | author: iTXTech, PetteriM1 7 | 8 | commands: 9 | transfer: 10 | description: Switch server 11 | usage: "/transfer " 12 | permission: synapse.transfer 13 | srv: 14 | description: Switch server 15 | usage: "/srv " 16 | permission: synapse.transfer 17 | hub: 18 | description: Transfer to lobby 19 | usage: "/hub" 20 | permission: synapse.transfer.hub 21 | lobby: 22 | description: Transfer to lobby 23 | usage: "/lobby" 24 | permission: synapse.transfer.hub 25 | permissions: 26 | synapse.transfer: 27 | description: "Allows player to transfer to other server" 28 | default: true 29 | synapse.transfer.hub: 30 | description: "Allows player to transfer to lobby" 31 | default: true 32 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/event/player/SynapsePlayerTransferEvent.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.event.player; 2 | 3 | import cn.nukkit.event.Cancellable; 4 | import cn.nukkit.event.HandlerList; 5 | import org.itxtech.synapseapi.SynapsePlayer; 6 | import org.itxtech.synapseapi.utils.ClientData.Entry; 7 | 8 | /** 9 | * @author CreeperFace 10 | */ 11 | public class SynapsePlayerTransferEvent extends SynapsePlayerEvent implements Cancellable { 12 | 13 | private static final HandlerList handlers = new HandlerList(); 14 | private final Entry clientData; 15 | 16 | public SynapsePlayerTransferEvent(SynapsePlayer player, Entry data) { 17 | super(player); 18 | this.clientData = data; 19 | } 20 | 21 | public static HandlerList getHandlers() { 22 | return handlers; 23 | } 24 | 25 | public Entry getClientData() { 26 | return clientData; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/event/player/SynapsePlayerConnectEvent.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.event.player; 2 | 3 | import cn.nukkit.event.Cancellable; 4 | import cn.nukkit.event.HandlerList; 5 | import org.itxtech.synapseapi.SynapsePlayer; 6 | 7 | /** 8 | * Created by boybook on 16/6/25. 9 | */ 10 | public class SynapsePlayerConnectEvent extends SynapsePlayerEvent implements Cancellable { 11 | 12 | private static final HandlerList handlers = new HandlerList(); 13 | private boolean firstTime; 14 | 15 | public SynapsePlayerConnectEvent(SynapsePlayer player) { 16 | this(player, true); 17 | } 18 | 19 | public SynapsePlayerConnectEvent(SynapsePlayer player, boolean firstTime) { 20 | super(player); 21 | this.firstTime = firstTime; 22 | } 23 | 24 | public static HandlerList getHandlers() { 25 | return handlers; 26 | } 27 | 28 | public boolean isFirstTime() { 29 | return firstTime; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/RedirectPacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | import java.util.UUID; 4 | 5 | /** 6 | * Created by boybook on 16/6/24. 7 | */ 8 | public class RedirectPacket extends SynapseDataPacket { 9 | 10 | public UUID uuid; 11 | public boolean direct; 12 | public byte[] mcpeBuffer; 13 | 14 | @Override 15 | public byte pid() { 16 | return SynapseInfo.REDIRECT_PACKET; 17 | } 18 | 19 | @Override 20 | public void encode() { 21 | this.reset(); 22 | this.putUUID(this.uuid); 23 | this.putBoolean(this.direct); 24 | this.putUnsignedVarInt(this.mcpeBuffer.length); 25 | this.put(this.mcpeBuffer); 26 | } 27 | 28 | @Override 29 | public void decode() { 30 | this.uuid = this.getUUID(); 31 | this.direct = this.getBoolean(); 32 | this.mcpeBuffer = this.get((int) this.getUnsignedVarInt()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/InformationPacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | /** 4 | * Created by boybook on 16/6/24. 5 | */ 6 | public class InformationPacket extends SynapseDataPacket { 7 | 8 | public static final byte TYPE_LOGIN = 0; 9 | public static final byte TYPE_CLIENT_DATA = 1; 10 | public static final String INFO_LOGIN_SUCCESS = "success"; 11 | public static final String INFO_LOGIN_FAILED = "failed"; 12 | public byte type; 13 | public String message; 14 | 15 | @Override 16 | public byte pid() { 17 | return SynapseInfo.INFORMATION_PACKET; 18 | } 19 | 20 | @Override 21 | public void encode() { 22 | this.reset(); 23 | this.putByte(this.type); 24 | this.putString(this.message); 25 | } 26 | 27 | @Override 28 | public void decode() { 29 | this.type = (byte) this.getByte(); 30 | this.message = this.getString(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/PlayerCountPacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | import java.util.Map; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | 6 | public class PlayerCountPacket extends SynapseDataPacket { 7 | 8 | public Map data; 9 | 10 | @Override 11 | public byte pid() { 12 | return SynapseInfo.PLAYER_COUNT_PACKET; 13 | } 14 | 15 | @Override 16 | public void encode() { 17 | this.reset(); 18 | this.putInt(data.size()); 19 | this.data.forEach((name, count) -> { 20 | this.putString(name); 21 | this.putInt(count); 22 | }); 23 | } 24 | 25 | @Override 26 | public void decode() { 27 | this.data = new ConcurrentHashMap<>(); 28 | int size = this.getInt(); 29 | for (int i = 0; i < size; i++) { 30 | this.data.put(this.getString(), this.getInt()); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/SynapseDataPacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | 4 | import cn.nukkit.utils.BinaryStream; 5 | 6 | public abstract class SynapseDataPacket extends BinaryStream implements Cloneable { 7 | 8 | public boolean isEncoded; 9 | 10 | public abstract byte pid(); 11 | 12 | public abstract void decode(); 13 | 14 | public abstract void encode(); 15 | 16 | @Override 17 | public BinaryStream reset() { 18 | return super.reset(); 19 | } 20 | 21 | public SynapseDataPacket clean() { 22 | this.setBuffer(null); 23 | 24 | this.isEncoded = false; 25 | this.offset = 0; 26 | return this; 27 | } 28 | 29 | @Override 30 | public SynapseDataPacket clone() { 31 | try { 32 | return (SynapseDataPacket) super.clone(); 33 | } catch (CloneNotSupportedException e) { 34 | return null; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/synlib/SynapsePacketEncoder.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.synlib; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.handler.codec.MessageToByteEncoder; 6 | import org.itxtech.synapseapi.network.protocol.spp.SynapseDataPacket; 7 | 8 | /** 9 | * SynapsePacketEncoder 10 | * =============== 11 | * author: boybook 12 | * Nemisys Project 13 | * =============== 14 | */ 15 | public class SynapsePacketEncoder extends MessageToByteEncoder { 16 | 17 | @Override 18 | protected void encode(ChannelHandlerContext ctx, SynapseDataPacket packet, ByteBuf out) throws Exception { 19 | if (!packet.isEncoded) packet.encode(); 20 | byte[] body = packet.getBuffer(); 21 | out.writeShort(SynapseProtocolHeader.MAGIC) 22 | .writeByte(packet.pid()) 23 | .writeInt(body.length) 24 | .writeBytes(body); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .metadata 2 | bin/ 3 | tmp/ 4 | *.tmp 5 | *.bak 6 | *.swp 7 | *~.nib 8 | local.properties 9 | .settings/ 10 | .loadpath 11 | .recommenders 12 | *.launch 13 | .project 14 | .classpath 15 | .idea 16 | .idea/ 17 | .idea/*.xml 18 | .idea/**/workspace.xml 19 | .idea/**/tasks.xml 20 | .idea/dictionaries 21 | .idea/**/dataSources/ 22 | .idea/**/dataSources.ids 23 | .idea/**/dataSources.xml 24 | .idea/**/dataSources.local.xml 25 | .idea/**/sqlDataSources.xml 26 | .idea/**/dynamic.xml 27 | .idea/**/uiDesigner.xml 28 | /out/ 29 | *.iml 30 | modules.xml 31 | .idea/misc.xml 32 | *.ipr 33 | # Compiled class file 34 | *.class 35 | *.log 36 | .mtj.tmp/ 37 | *.war 38 | *.ear 39 | *.zip 40 | *.tar.gz 41 | *.rar 42 | hs_err_pid* 43 | target/ 44 | pom.xml.tag 45 | pom.xml.releaseBackup 46 | pom.xml.versionsBackup 47 | pom.xml.next 48 | release.properties 49 | dependency-reduced-pom.xml 50 | buildNumber.properties 51 | .mvn/timing.properties 52 | !/.mvn/wrapper/maven-wrapper.jar 53 | nbproject/private/ 54 | build/ 55 | nbbuild/ 56 | dist/ 57 | nbdist/ 58 | .nb-gradle/ 59 | rebel.xml 60 | .DS_Store 61 | *.jar 62 | 63 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | SynapseAPI 8 | org.itxtech.synapse 9 | SynapseAPI 10 | PM1E 11 | 12 | 13 | 1.8 14 | 1.8 15 | UTF-8 16 | 17 | 18 | 19 | 20 | cn.nukkit 21 | Nukkit 22 | PM1E 23 | false 24 | system 25 | ${basedir}/patched.jar 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/BroadcastPacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.UUID; 6 | 7 | /** 8 | * Author: PeratX 9 | * SynapseAPI Project 10 | */ 11 | public class BroadcastPacket extends SynapseDataPacket { 12 | 13 | public List entries; 14 | public boolean direct; 15 | public byte[] payload; 16 | 17 | @Override 18 | public byte pid() { 19 | return SynapseInfo.BROADCAST_PACKET; 20 | } 21 | 22 | @Override 23 | public void encode() { 24 | this.reset(); 25 | this.putBoolean(this.direct); 26 | this.putShort(this.entries.size()); 27 | for (UUID uniqueId : this.entries) { 28 | this.putUUID(uniqueId); 29 | } 30 | this.putShort(this.payload.length); 31 | this.put(this.payload); 32 | } 33 | 34 | @Override 35 | public void decode() { 36 | this.direct = this.getBoolean(); 37 | int len = this.getShort(); 38 | this.entries = new ArrayList<>(); 39 | for (int i = 0; i < len; i++) { 40 | this.entries.add(this.getUUID()); 41 | } 42 | this.payload = this.get(this.getShort()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/PlayerLoginPacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | import java.util.UUID; 4 | 5 | /** 6 | * Created by boybook on 16/6/24. 7 | */ 8 | public class PlayerLoginPacket extends SynapseDataPacket { 9 | 10 | public int raknetProtocol; 11 | public UUID uuid; 12 | public String address; 13 | public int port; 14 | public boolean isFirstTime; 15 | public byte[] cachedLoginPacket; 16 | 17 | @Override 18 | public byte pid() { 19 | return SynapseInfo.PLAYER_LOGIN_PACKET; 20 | } 21 | 22 | @Override 23 | public void encode() { 24 | this.reset(); 25 | this.putInt(this.raknetProtocol); 26 | this.putUUID(this.uuid); 27 | this.putString(this.address); 28 | this.putInt(this.port); 29 | this.putBoolean(this.isFirstTime); 30 | this.putInt(this.cachedLoginPacket.length); 31 | this.put(this.cachedLoginPacket); 32 | } 33 | 34 | @Override 35 | public void decode() { 36 | this.raknetProtocol = this.getInt(); 37 | this.uuid = this.getUUID(); 38 | this.address = this.getString(); 39 | this.port = this.getInt(); 40 | this.isFirstTime = this.getBoolean(); 41 | this.cachedLoginPacket = this.get(this.getInt()); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/utils/ClientData.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.utils; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * Created by boybook on 16/6/25. 8 | */ 9 | public class ClientData { 10 | 11 | public Map clientList = new HashMap<>(); 12 | 13 | public String getHashByDescription(String description) { 14 | final String[] re = new String[1]; 15 | this.clientList.forEach((hash, entry) -> { 16 | if (entry.getDescription().equals(description)) { 17 | re[0] = hash; 18 | } 19 | }); 20 | return re[0]; 21 | } 22 | 23 | public static class Entry { 24 | 25 | private String ip; 26 | private int port; 27 | private int playerCount; 28 | private int maxPlayers; 29 | private String description; 30 | 31 | public String getIp() { 32 | return ip; 33 | } 34 | 35 | public int getPort() { 36 | return port; 37 | } 38 | 39 | public int getMaxPlayers() { 40 | return maxPlayers; 41 | } 42 | 43 | public int getPlayerCount() { 44 | return playerCount; 45 | } 46 | 47 | public String getDescription() { 48 | return description; 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/protocol/spp/ConnectPacket.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.protocol.spp; 2 | 3 | /** 4 | * Created by boybook on 16/6/24. 5 | */ 6 | public class ConnectPacket extends SynapseDataPacket { 7 | 8 | public int protocol = SynapseInfo.CURRENT_PROTOCOL; 9 | public int maxPlayers; 10 | public boolean isLobbyServer; 11 | public boolean transferShutdown; 12 | public String description; 13 | public String password; 14 | public boolean useSnappy; 15 | 16 | @Override 17 | public byte pid() { 18 | return SynapseInfo.CONNECT_PACKET; 19 | } 20 | 21 | @Override 22 | public void encode() { 23 | this.reset(); 24 | this.putInt(this.protocol); 25 | this.putInt(this.maxPlayers); 26 | this.putBoolean(this.isLobbyServer); 27 | this.putBoolean(this.transferShutdown); 28 | this.putString(this.description); 29 | this.putString(this.password); 30 | this.putBoolean(this.useSnappy); 31 | } 32 | 33 | @Override 34 | public void decode() { 35 | this.protocol = this.getInt(); 36 | this.maxPlayers = this.getInt(); 37 | this.isLobbyServer = this.getBoolean(); 38 | this.transferShutdown = getBoolean(); 39 | this.description = this.getString(); 40 | this.password = this.getString(); 41 | this.useSnappy = this.getBoolean(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/synlib/SynapseClientInitializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2012 The Netty Project 3 | * 4 | * The Netty Project licenses this file to you under the Apache License, 5 | * version 2.0 (the "License"); you may not use this file except in compliance 6 | * with the License. You may obtain a copy of the License at: 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | package org.itxtech.synapseapi.network.synlib; 17 | 18 | import io.netty.channel.ChannelInitializer; 19 | import io.netty.channel.ChannelPipeline; 20 | import io.netty.channel.socket.SocketChannel; 21 | 22 | /** 23 | * Creates a newly configured {@link ChannelPipeline} for a new channel. 24 | */ 25 | public class SynapseClientInitializer extends ChannelInitializer { 26 | 27 | private final SynapseClient synapseClient; 28 | 29 | public SynapseClientInitializer(SynapseClient synapseClient) { 30 | this.synapseClient = synapseClient; 31 | } 32 | 33 | @Override 34 | public void initChannel(SocketChannel ch) throws Exception { 35 | ChannelPipeline pipeline = ch.pipeline(); 36 | pipeline.addLast(new SynapsePacketDecoder()); 37 | pipeline.addLast(new SynapsePacketEncoder()); 38 | pipeline.addLast(new SynapseClientHandler(this.synapseClient)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/messaging/Messenger.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.messaging; 2 | 3 | import cn.nukkit.plugin.Plugin; 4 | import org.itxtech.synapseapi.SynapseEntry; 5 | 6 | import java.util.Set; 7 | 8 | /** 9 | * @author CreeperFace 10 | */ 11 | public interface Messenger { 12 | 13 | boolean isReservedChannel(String channel); 14 | 15 | void registerOutgoingPluginChannel(Plugin plugin, String channel); 16 | 17 | void unregisterOutgoingPluginChannel(Plugin plugin, String channel); 18 | 19 | void unregisterOutgoingPluginChannel(Plugin plugin); 20 | 21 | PluginMessageListenerRegistration registerIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener); 22 | 23 | void unregisterIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener); 24 | 25 | void unregisterIncomingPluginChannel(Plugin plugin, String channel); 26 | 27 | void unregisterIncomingPluginChannel(Plugin plugin); 28 | 29 | Set getOutgoingChannels(); 30 | 31 | Set getOutgoingChannels(Plugin plugin); 32 | 33 | Set getIncomingChannels(); 34 | 35 | Set getIncomingChannels(Plugin plugin); 36 | 37 | Set getIncomingChannelRegistrations(Plugin plugin); 38 | 39 | Set getIncomingChannelRegistrations(String channel); 40 | 41 | Set getIncomingChannelRegistrations(Plugin plugin, String channel); 42 | 43 | boolean isRegistrationValid(PluginMessageListenerRegistration registration); 44 | 45 | boolean isIncomingChannelRegistered(Plugin plugin, String channel); 46 | 47 | boolean isOutgoingChannelRegistered(Plugin plugin, String channel); 48 | 49 | void dispatchIncomingMessage(SynapseEntry entry, String channel, byte[] message); 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/event/player/SynapsePlayerCreationEvent.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.event.player; 2 | 3 | import cn.nukkit.event.HandlerList; 4 | import cn.nukkit.network.SourceInterface; 5 | import org.itxtech.synapseapi.SynapsePlayer; 6 | import org.itxtech.synapseapi.event.SynapseEvent; 7 | 8 | import java.net.InetSocketAddress; 9 | 10 | public class SynapsePlayerCreationEvent extends SynapseEvent { 11 | 12 | private static final HandlerList handlers = new HandlerList(); 13 | private final SourceInterface interfaz; 14 | private final Long clientId; 15 | private final InetSocketAddress address; 16 | private Class baseClass; 17 | private Class playerClass; 18 | 19 | public SynapsePlayerCreationEvent(SourceInterface interfaz, Class baseClass, Class playerClass, Long clientId, InetSocketAddress address) { 20 | this.interfaz = interfaz; 21 | this.clientId = clientId; 22 | this.address = address; 23 | 24 | this.baseClass = baseClass; 25 | this.playerClass = playerClass; 26 | } 27 | 28 | public static HandlerList getHandlers() { 29 | return handlers; 30 | } 31 | 32 | public SourceInterface getInterface() { 33 | return interfaz; 34 | } 35 | 36 | public String getAddress() { 37 | return this.address.getAddress().getHostAddress(); 38 | } 39 | 40 | public int getPort() { 41 | return this.address.getPort(); 42 | } 43 | 44 | public Long getClientId() { 45 | return clientId; 46 | } 47 | 48 | public Class getBaseClass() { 49 | return baseClass; 50 | } 51 | 52 | public void setBaseClass(Class baseClass) { 53 | this.baseClass = baseClass; 54 | } 55 | 56 | public Class getPlayerClass() { 57 | return playerClass; 58 | } 59 | 60 | public void setPlayerClass(Class playerClass) { 61 | this.playerClass = playerClass; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/synlib/SynapsePacketDecoder.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.synlib; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.handler.codec.ReplayingDecoder; 6 | import org.itxtech.synapseapi.SynapseAPI; 7 | import org.itxtech.synapseapi.network.SynapseInterface; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * SynapsePacketDecoder 13 | * =============== 14 | * author: boybook 15 | * Nemisys Project 16 | * =============== 17 | */ 18 | public class SynapsePacketDecoder extends ReplayingDecoder { 19 | 20 | private final SynapseProtocolHeader header = new SynapseProtocolHeader(); 21 | 22 | public SynapsePacketDecoder() { 23 | super(State.HEADER_MAGIC); 24 | } 25 | 26 | @Override 27 | protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { 28 | switch (state()) { 29 | case HEADER_MAGIC: 30 | if (SynapseProtocolHeader.MAGIC != in.readShort()) { 31 | throw new SynapseContextException("Magic value does not match"); 32 | } 33 | checkpoint(State.HEADER_ID); 34 | case HEADER_ID: 35 | header.pid(in.readByte()); 36 | checkpoint(State.HEADER_BODY_LENGTH); 37 | case HEADER_BODY_LENGTH: 38 | header.bodyLength(in.readInt()); 39 | checkpoint(State.BODY); 40 | case BODY: 41 | int bodyLength = header.bodyLength(); 42 | if (bodyLength < 6291456) { 43 | byte[] bytes = new byte[bodyLength]; 44 | in.readBytes(bytes); 45 | out.add(SynapseInterface.getPacket((byte) header.pid(), bytes)); 46 | break; 47 | } else { 48 | SynapseAPI.getInstance().getLogger().warning("Ignoring too big packet with body length " + bodyLength); 49 | return; 50 | } 51 | default: 52 | break; 53 | } 54 | checkpoint(State.HEADER_MAGIC); 55 | } 56 | 57 | enum State { 58 | HEADER_MAGIC, HEADER_ID, HEADER_BODY_LENGTH, BODY 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/synlib/SynapseClientHandler.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.synlib; 2 | 3 | import cn.nukkit.Server; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.ChannelInboundHandlerAdapter; 6 | import org.itxtech.synapseapi.network.protocol.spp.SynapseDataPacket; 7 | 8 | import java.net.InetSocketAddress; 9 | 10 | /** 11 | * Handles a server-side channel. 12 | */ 13 | public class SynapseClientHandler extends ChannelInboundHandlerAdapter { 14 | 15 | private final SynapseClient synapseClient; 16 | 17 | public SynapseClientHandler(SynapseClient synapseClient) { 18 | this.synapseClient = synapseClient; 19 | } 20 | 21 | public SynapseClient getSynapseClient() { 22 | return synapseClient; 23 | } 24 | 25 | @Override 26 | public void channelActive(ChannelHandlerContext ctx) { 27 | this.getSynapseClient().getSession().channel = ctx.channel(); 28 | InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress(); 29 | this.getSynapseClient().getSession().updateAddress(address); 30 | this.getSynapseClient().getSession().setConnected(true); 31 | this.getSynapseClient().setConnected(true); 32 | Server.getInstance().getLogger().notice("Synapse Client has connected to " + address.getAddress().getHostAddress() + ':' + address.getPort()); 33 | } 34 | 35 | @Override 36 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 37 | this.getSynapseClient().setConnected(false); 38 | this.getSynapseClient().getClientGroup().shutdownGracefully(); 39 | this.getSynapseClient().reconnect(); 40 | } 41 | 42 | @Override 43 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 44 | if (msg instanceof SynapseDataPacket) { 45 | SynapseDataPacket packet = (SynapseDataPacket) msg; 46 | this.getSynapseClient().pushThreadToMainPacket(packet); 47 | } 48 | } 49 | 50 | @Override 51 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 52 | if (cause instanceof Exception) Server.getInstance().getLogger().logException(cause); 53 | ctx.close(); 54 | this.getSynapseClient().setConnected(false); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/SynLibInterface.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network; 2 | 3 | import cn.nukkit.Player; 4 | import cn.nukkit.Server; 5 | import cn.nukkit.network.SourceInterface; 6 | import cn.nukkit.network.protocol.BatchPacket; 7 | import cn.nukkit.network.protocol.DataPacket; 8 | import cn.nukkit.network.session.NetworkPlayerSession; 9 | import cn.nukkit.utils.Binary; 10 | import org.itxtech.synapseapi.network.protocol.spp.RedirectPacket; 11 | 12 | import java.net.InetSocketAddress; 13 | 14 | /** 15 | * Created by boybook on 16/6/24. 16 | */ 17 | public class SynLibInterface implements SourceInterface { 18 | 19 | private final SynapseInterface synapseInterface; 20 | 21 | public SynLibInterface(SynapseInterface synapseInterface) { 22 | this.synapseInterface = synapseInterface; 23 | } 24 | 25 | @Override 26 | public int getNetworkLatency(Player player) { 27 | return 0; 28 | } 29 | 30 | @Override 31 | public void emergencyShutdown() { 32 | } 33 | 34 | @Override 35 | public void setName(String name) { 36 | } 37 | 38 | @Override 39 | public Integer putPacket(Player player, DataPacket packet) { 40 | return this.putPacket(player, packet, false); 41 | } 42 | 43 | @Override 44 | public Integer putPacket(Player player, DataPacket packet, boolean needACK) { 45 | return this.putPacket(player, packet, needACK, false); 46 | } 47 | 48 | @Override 49 | public Integer putPacket(Player player, DataPacket packet, boolean needACK, boolean immediate) { 50 | RedirectPacket pk = new RedirectPacket(); 51 | pk.uuid = player.getUniqueId(); 52 | pk.direct = immediate; 53 | pk.mcpeBuffer = packet instanceof BatchPacket ? Binary.appendBytes((byte) 0xfe, ((BatchPacket) packet).payload) : packet.getBuffer(); 54 | 55 | if (pk.mcpeBuffer.length >= 5242880) { 56 | Server.getInstance().getLogger().error("[Synapse] Too big packet! (pid: " + packet.pid() + ", player: " + player.getName() + ')'); 57 | } else { 58 | this.synapseInterface.putPacket(pk); 59 | } 60 | return 0; 61 | } 62 | 63 | @Override 64 | public NetworkPlayerSession getSession(InetSocketAddress inetSocketAddress) { 65 | return null; 66 | } 67 | 68 | @Override 69 | public boolean process() { 70 | return false; 71 | } 72 | 73 | @Override 74 | public void close(Player player, String reason) { 75 | } 76 | 77 | @Override 78 | public void close(Player player) { 79 | } 80 | 81 | @Override 82 | public void shutdown() { 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/messaging/PluginMessageListenerRegistration.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.messaging; 2 | 3 | import cn.nukkit.plugin.Plugin; 4 | 5 | public final class PluginMessageListenerRegistration { 6 | 7 | private final Messenger messenger; 8 | private final Plugin plugin; 9 | private final String channel; 10 | private final PluginMessageListener listener; 11 | 12 | public PluginMessageListenerRegistration(Messenger messenger, Plugin plugin, String channel, PluginMessageListener listener) { 13 | if (messenger == null) { 14 | throw new IllegalArgumentException("Messenger cannot be null!"); 15 | } 16 | if (plugin == null) { 17 | throw new IllegalArgumentException("Plugin cannot be null!"); 18 | } 19 | if (channel == null) { 20 | throw new IllegalArgumentException("Channel cannot be null!"); 21 | } 22 | if (listener == null) { 23 | throw new IllegalArgumentException("Listener cannot be null!"); 24 | } 25 | this.messenger = messenger; 26 | this.plugin = plugin; 27 | this.channel = channel; 28 | this.listener = listener; 29 | } 30 | 31 | public String getChannel() { 32 | return this.channel; 33 | } 34 | 35 | public PluginMessageListener getListener() { 36 | return this.listener; 37 | } 38 | 39 | public Plugin getPlugin() { 40 | return this.plugin; 41 | } 42 | 43 | public boolean isValid() { 44 | return this.messenger.isRegistrationValid(this); 45 | } 46 | 47 | public boolean equals(Object obj) { 48 | if (obj == null) { 49 | return false; 50 | } 51 | if (this.getClass() != obj.getClass()) { 52 | return false; 53 | } 54 | PluginMessageListenerRegistration other = (PluginMessageListenerRegistration) obj; 55 | if (!(this.messenger == other.messenger || this.messenger != null && this.messenger.equals(other.messenger))) { 56 | return false; 57 | } 58 | if (!(this.plugin == other.plugin || this.plugin != null && this.plugin.equals(other.plugin))) { 59 | return false; 60 | } 61 | if (this.channel == null ? other.channel != null : !this.channel.equals(other.channel)) { 62 | return false; 63 | } 64 | return this.listener == other.listener || this.listener != null && this.listener.equals(other.listener); 65 | } 66 | 67 | public int hashCode() { 68 | int hash = 7; 69 | hash = 53 * hash + (this.messenger != null ? this.messenger.hashCode() : 0); 70 | hash = 53 * hash + (this.plugin != null ? this.plugin.hashCode() : 0); 71 | hash = 53 * hash + (this.channel != null ? this.channel.hashCode() : 0); 72 | hash = 53 * hash + (this.listener != null ? this.listener.hashCode() : 0); 73 | return hash; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/synlib/Session.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.synlib; 2 | 3 | import cn.nukkit.Server; 4 | import io.netty.channel.Channel; 5 | import org.itxtech.synapseapi.SynapseAPI; 6 | import org.itxtech.synapseapi.network.protocol.spp.SynapseDataPacket; 7 | 8 | import java.net.InetSocketAddress; 9 | 10 | public class Session { 11 | 12 | public Channel channel; 13 | private String ip; 14 | private int port; 15 | private final SynapseClient client; 16 | private long lastCheck; 17 | private boolean connected; 18 | private long tickUseTime; 19 | 20 | public Session(SynapseClient client) { 21 | this.client = client; 22 | this.connected = true; 23 | this.lastCheck = System.currentTimeMillis(); 24 | } 25 | 26 | public void updateAddress(InetSocketAddress address) { 27 | this.ip = address.getAddress().getHostAddress(); 28 | this.port = address.getPort(); 29 | } 30 | 31 | public void setConnected(boolean connected) { 32 | this.connected = connected; 33 | } 34 | 35 | public void run() { 36 | this.tickProcessor(); 37 | } 38 | 39 | private void tickProcessor() { 40 | while (!this.client.isShutdown()) { 41 | try { 42 | this.tick(); 43 | } catch (Exception e) { 44 | Server.getInstance().getLogger().logException(e); 45 | } 46 | try { 47 | Thread.sleep(1); 48 | } catch (InterruptedException ignored) { 49 | } 50 | } 51 | if (this.connected) { 52 | this.client.getClientGroup().shutdownGracefully(); 53 | } 54 | } 55 | 56 | private void tick() throws Exception { 57 | if (this.update()) { 58 | long start = System.currentTimeMillis(); 59 | 60 | SynapseDataPacket pk; 61 | 62 | while (System.currentTimeMillis() - start < 3000 && (pk = this.client.readMainToThreadPacket()) != null) { 63 | this.writePacket(pk); 64 | } 65 | } 66 | } 67 | 68 | public String getHash() { 69 | return this.getIp() + ':' + this.getPort(); 70 | } 71 | 72 | public String getIp() { 73 | return ip; 74 | } 75 | 76 | public int getPort() { 77 | return port; 78 | } 79 | 80 | public Channel getChannel() { 81 | return channel; 82 | } 83 | 84 | public boolean update() throws Exception { 85 | if (this.client.needReconnect && this.connected) { 86 | this.connected = false; 87 | this.client.needReconnect = false; 88 | } 89 | if (!this.connected && !this.client.isShutdown() && SynapseAPI.canReconnect) { 90 | long time; 91 | if ((time = System.currentTimeMillis()) - this.lastCheck >= 3000) { 92 | this.client.getLogger().notice("Trying to re-connect to Synapse Server"); 93 | if (this.client.connect()) { 94 | this.connected = true; 95 | this.client.setConnected(true); 96 | this.client.setNeedAuth(true); 97 | } 98 | this.lastCheck = time; 99 | } 100 | return false; 101 | } 102 | return true; 103 | } 104 | 105 | public void writePacket(SynapseDataPacket pk) { 106 | if (this.channel != null) { 107 | this.channel.writeAndFlush(pk); 108 | } 109 | } 110 | 111 | public float getTicksPerSecond() { 112 | long more = this.tickUseTime - 10; 113 | if (more < 0) return 100; 114 | return Math.round(10f / this.tickUseTime) * 100; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/SynapseInterface.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network; 2 | 3 | import cn.nukkit.Server; 4 | import org.itxtech.synapseapi.SynapseEntry; 5 | import org.itxtech.synapseapi.network.protocol.spp.*; 6 | import org.itxtech.synapseapi.network.synlib.SynapseClient; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | /** 12 | * Created by boybook on 16/6/24. 13 | */ 14 | public class SynapseInterface { 15 | 16 | private static final Map packetPool = new HashMap<>(); 17 | private final SynapseEntry synapse; 18 | private final SynapseClient client; 19 | private volatile boolean connected; 20 | 21 | public SynapseInterface(SynapseEntry server, String ip, int port) { 22 | this.synapse = server; 23 | this.registerPackets(); 24 | this.client = new SynapseClient(Server.getInstance().getLogger(), port, ip); 25 | } 26 | 27 | public static SynapseDataPacket getPacket(byte pid, byte[] buffer) { 28 | SynapseDataPacket clazz = packetPool.get(pid); 29 | if (clazz != null) { 30 | SynapseDataPacket pk = clazz.clone(); 31 | pk.setBuffer(buffer, 0); 32 | return pk; 33 | } 34 | 35 | return null; 36 | } 37 | 38 | public static void registerPacket(byte id, SynapseDataPacket packet) { 39 | packetPool.put(id, packet); 40 | } 41 | 42 | public SynapseEntry getSynapse() { 43 | return synapse; 44 | } 45 | 46 | public void reconnect() { 47 | this.client.reconnect(); 48 | } 49 | 50 | public void shutdown() { 51 | this.client.shutdown(); 52 | } 53 | 54 | public void putPacket(SynapseDataPacket pk) { 55 | if (!pk.isEncoded) { 56 | pk.encode(); 57 | } 58 | this.client.pushMainToThreadPacket(pk); 59 | } 60 | 61 | public boolean isConnected() { 62 | return connected; 63 | } 64 | 65 | public void process() { 66 | long start = System.currentTimeMillis(); 67 | 68 | SynapseDataPacket pk; 69 | 70 | while (System.currentTimeMillis() - start < 5000 && (pk = this.client.readThreadToMainPacket()) != null) { 71 | try { 72 | this.handlePacket(pk); 73 | } catch (Throwable e) { 74 | getSynapse().getSynapse().getLogger().error("Exception while handling incoming packet", e); 75 | } 76 | } 77 | 78 | this.connected = this.client.isConnected(); 79 | if (this.connected && this.client.isNeedAuth()) { 80 | this.synapse.connect(); 81 | this.client.setNeedAuth(false); 82 | } 83 | } 84 | 85 | public void handlePacket(SynapseDataPacket pk) { 86 | if (pk != null) { 87 | pk.decode(); 88 | this.synapse.handleDataPacket(pk); 89 | } 90 | } 91 | 92 | private void registerPackets() { 93 | packetPool.clear(); 94 | registerPacket(SynapseInfo.HEARTBEAT_PACKET, new HeartbeatPacket()); 95 | registerPacket(SynapseInfo.CONNECT_PACKET, new ConnectPacket()); 96 | registerPacket(SynapseInfo.DISCONNECT_PACKET, new DisconnectPacket()); 97 | registerPacket(SynapseInfo.REDIRECT_PACKET, new RedirectPacket()); 98 | registerPacket(SynapseInfo.PLAYER_LOGIN_PACKET, new PlayerLoginPacket()); 99 | registerPacket(SynapseInfo.PLAYER_LOGOUT_PACKET, new PlayerLogoutPacket()); 100 | registerPacket(SynapseInfo.INFORMATION_PACKET, new InformationPacket()); 101 | registerPacket(SynapseInfo.TRANSFER_PACKET, new TransferPacket()); 102 | registerPacket(SynapseInfo.BROADCAST_PACKET, new BroadcastPacket()); 103 | registerPacket(SynapseInfo.PLUGIN_MESSAGE_PACKET, new PluginMessagePacket()); 104 | registerPacket(SynapseInfo.PLAYER_COUNT_PACKET, new PlayerCountPacket()); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/network/synlib/SynapseClient.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.network.synlib; 2 | 3 | import cn.nukkit.Server; 4 | import cn.nukkit.utils.MainLogger; 5 | import io.netty.bootstrap.Bootstrap; 6 | import io.netty.channel.ChannelOption; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.nio.NioSocketChannel; 10 | import org.itxtech.synapseapi.network.protocol.spp.SynapseDataPacket; 11 | 12 | import java.util.concurrent.ConcurrentLinkedQueue; 13 | 14 | /** 15 | * Created by boybook on 16/6/24. 16 | */ 17 | public class SynapseClient extends Thread { 18 | 19 | public volatile boolean needReconnect; 20 | protected ConcurrentLinkedQueue externalQueue; 21 | protected ConcurrentLinkedQueue internalQueue; 22 | private final MainLogger logger; 23 | private final String interfaz; 24 | private final int port; 25 | private boolean shutdown; 26 | private volatile boolean needAuth = true; 27 | private volatile boolean connected; 28 | private EventLoopGroup clientGroup; 29 | private Session session; 30 | 31 | public SynapseClient(MainLogger logger, int port) { 32 | this(logger, port, "127.0.0.1"); 33 | } 34 | 35 | public SynapseClient(MainLogger logger, int port, String interfaz) { 36 | this.logger = logger; 37 | this.interfaz = interfaz; 38 | this.port = port; 39 | if (port < 1 || port > 65536) { 40 | throw new IllegalArgumentException("Invalid port range"); 41 | } 42 | this.shutdown = false; 43 | this.externalQueue = new ConcurrentLinkedQueue<>(); 44 | this.internalQueue = new ConcurrentLinkedQueue<>(); 45 | 46 | this.start(); 47 | } 48 | 49 | public void reconnect() { 50 | this.needReconnect = true; 51 | } 52 | 53 | public boolean isNeedAuth() { 54 | return needAuth; 55 | } 56 | 57 | public void setNeedAuth(boolean needAuth) { 58 | this.needAuth = needAuth; 59 | } 60 | 61 | public boolean isConnected() { 62 | return connected; 63 | } 64 | 65 | public void setConnected(boolean connected) { 66 | this.connected = connected; 67 | } 68 | 69 | public ConcurrentLinkedQueue getExternalQueue() { 70 | return externalQueue; 71 | } 72 | 73 | public ConcurrentLinkedQueue getInternalQueue() { 74 | return internalQueue; 75 | } 76 | 77 | public boolean isShutdown() { 78 | return shutdown; 79 | } 80 | 81 | public void shutdown() { 82 | this.shutdown = true; 83 | } 84 | 85 | public int getPort() { 86 | return port; 87 | } 88 | 89 | public String getInterface() { 90 | return interfaz; 91 | } 92 | 93 | public MainLogger getLogger() { 94 | return logger; 95 | } 96 | 97 | public void quit() { 98 | this.shutdown(); 99 | } 100 | 101 | public void pushMainToThreadPacket(SynapseDataPacket data) { 102 | this.internalQueue.offer(data); 103 | } 104 | 105 | public SynapseDataPacket readMainToThreadPacket() { 106 | return this.internalQueue.poll(); 107 | } 108 | 109 | public int getInternalQueueSize() { 110 | return this.internalQueue.size(); 111 | } 112 | 113 | public void pushThreadToMainPacket(SynapseDataPacket data) { 114 | this.externalQueue.offer(data); 115 | } 116 | 117 | public SynapseDataPacket readThreadToMainPacket() { 118 | return this.externalQueue.poll(); 119 | } 120 | 121 | public Session getSession() { 122 | return session; 123 | } 124 | 125 | public void run() { 126 | this.setName("SynLib Client Thread #" + Thread.currentThread().getId()); 127 | Runtime.getRuntime().addShutdownHook(new ShutdownHandler()); 128 | try { 129 | this.session = new Session(this); 130 | this.connect(); 131 | this.session.run(); 132 | } catch (Exception e) { 133 | Server.getInstance().getLogger().logException(e); 134 | } 135 | } 136 | 137 | public boolean connect() { 138 | clientGroup = new NioEventLoopGroup(); 139 | try { 140 | Bootstrap b = new Bootstrap(); 141 | b.group(clientGroup) 142 | .channel(NioSocketChannel.class) 143 | .option(ChannelOption.SO_KEEPALIVE, true) 144 | .handler(new SynapseClientInitializer(this)); 145 | 146 | b.connect(this.interfaz, this.port).get(); 147 | return true; 148 | } catch (Exception e) { 149 | clientGroup.shutdownGracefully(); 150 | Server.getInstance().getLogger().alert("Synapse Client can't connect to server: " + this.interfaz + ':' + this.port); 151 | this.reconnect(); 152 | return false; 153 | } 154 | } 155 | 156 | public EventLoopGroup getClientGroup() { 157 | return clientGroup; 158 | } 159 | 160 | public class ShutdownHandler extends Thread { 161 | public void run() { 162 | if (!shutdown) { 163 | logger.emergency("SynLib Client crashed!"); 164 | } 165 | } 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/SynapseAPI.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi; 2 | 3 | import cn.nukkit.Player; 4 | import cn.nukkit.command.Command; 5 | import cn.nukkit.command.CommandSender; 6 | import cn.nukkit.event.EventHandler; 7 | import cn.nukkit.event.Listener; 8 | import cn.nukkit.event.server.BatchPacketsEvent; 9 | import cn.nukkit.event.server.ServerStopEvent; 10 | import cn.nukkit.network.RakNetInterface; 11 | import cn.nukkit.network.SourceInterface; 12 | import cn.nukkit.network.protocol.DataPacket; 13 | import cn.nukkit.plugin.PluginBase; 14 | import cn.nukkit.utils.ConfigSection; 15 | import cn.nukkit.utils.TextFormat; 16 | import cn.nukkit.utils.Utils; 17 | import cn.nukkit.utils.VarInt; 18 | import org.itxtech.synapseapi.messaging.Messenger; 19 | import org.itxtech.synapseapi.messaging.StandardMessenger; 20 | 21 | import java.io.ByteArrayInputStream; 22 | import java.io.IOException; 23 | import java.util.*; 24 | import java.util.concurrent.ConcurrentHashMap; 25 | 26 | /** 27 | * @author boybook 28 | */ 29 | public class SynapseAPI extends PluginBase implements Listener { 30 | 31 | public static boolean canReconnect = true; 32 | private static SynapseAPI instance; 33 | private final Map synapseEntries = new HashMap<>(); 34 | private Messenger messenger; 35 | public static boolean playerCountUpdates; 36 | public static boolean alwaysSpawn; 37 | public static Map playerCountData = new ConcurrentHashMap<>(); 38 | 39 | public static SynapseAPI getInstance() { 40 | return instance; 41 | } 42 | 43 | @Override 44 | public void onEnable() { 45 | if (!getServer().getName().equals("Nukkit PetteriM1 Edition") && getServer().getCodename().equals("PM1E")) { 46 | getServer().getLogger().error("This build of SynapseAPI can only be used on Nukkit PetteriM1 Edition. Please download correct build."); 47 | getServer().getPluginManager().disablePlugin(this); 48 | return; 49 | } 50 | instance = this; 51 | canReconnect = true; 52 | this.getServer().getPluginManager().registerEvents(this, this); 53 | this.messenger = new StandardMessenger(); 54 | this.loadEntries(); 55 | } 56 | 57 | public Map getSynapseEntries() { 58 | return synapseEntries; 59 | } 60 | 61 | public void addSynapseAPI(SynapseEntry entry) { 62 | this.synapseEntries.put(entry.getHash(), entry); 63 | } 64 | 65 | public SynapseEntry getSynapseEntry(String hash) { 66 | return this.synapseEntries.get(hash); 67 | } 68 | 69 | public void shutdownAll() { 70 | for (SynapseEntry entry : new ArrayList<>(this.synapseEntries.values())) { 71 | entry.shutdown(); 72 | } 73 | } 74 | 75 | @Override 76 | public void onDisable() { 77 | this.shutdownAll(); 78 | } 79 | 80 | public DataPacket getPacket(byte[] buffer) { 81 | ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer); 82 | 83 | int header; 84 | try { 85 | header = (int) VarInt.readUnsignedVarInt(inputStream); 86 | } catch (IOException e) { 87 | throw new RuntimeException("Unable to decode packet header", e); 88 | } 89 | 90 | // | Client ID | Sender ID | Packet ID | 91 | // | 2 bits | 2 bits | 10 bits | 92 | int packetId = header & 0x3ff; 93 | 94 | DataPacket packet = this.getServer().getNetwork().getPacket(packetId == 0xfe ? 0xff : packetId); 95 | 96 | if (packet != null) { 97 | packet.setBuffer(buffer, buffer.length - inputStream.available()); 98 | } 99 | 100 | return packet; 101 | } 102 | 103 | @SuppressWarnings({"unchecked", "rawtypes"}) 104 | private void loadEntries() { 105 | this.saveDefaultConfig(); 106 | 107 | for (SourceInterface sourceInterface : this.getServer().getNetwork().getInterfaces()) { 108 | if (sourceInterface instanceof RakNetInterface) { 109 | sourceInterface.shutdown(); 110 | } 111 | } 112 | 113 | List entries = this.getConfig().getList("entries"); 114 | 115 | for (Object entry : entries) { 116 | ConfigSection section = new ConfigSection((LinkedHashMap) entry); 117 | String serverIp = section.getString("server-ip", "127.0.0.1"); 118 | int port = section.getInt("server-port", 10305); 119 | boolean isLobbyServer = section.getBoolean("isLobbyServer"); 120 | boolean transfer = section.getBoolean("transferOnShutdown", true); 121 | String password = section.getString("password"); 122 | String serverDescription = section.getString("description"); 123 | this.addSynapseAPI(new SynapseEntry(this, serverIp, port, isLobbyServer, transfer, password, serverDescription)); 124 | } 125 | } 126 | 127 | public Messenger getMessenger() { 128 | return messenger; 129 | } 130 | 131 | @Override 132 | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { 133 | if (sender instanceof SynapsePlayer) { 134 | SynapsePlayer p = (SynapsePlayer) sender; 135 | String c = cmd.getName().toLowerCase(); 136 | if (c.equals("transfer") || c.equals("srv")) { 137 | if (args.length > 0) { 138 | if (p.getSynapseEntry().getServerDescription().equals(args[0])) { 139 | p.sendMessage("\u00A7cYou are already on this server"); 140 | } else { 141 | if (p.transferCommand(args[0]) == 0) { 142 | p.sendMessage("\u00A7cUnknown server"); 143 | } 144 | } 145 | } else { 146 | return false; 147 | } 148 | } else if (c.equals("hub") || c.equals("lobby")) { 149 | List l = getConfig().getStringList("lobbies"); 150 | if (l.size() == 0) return true; 151 | if (!l.contains(p.getSynapseEntry().getServerDescription()) && !p.getSynapseEntry().isLobbyServer()) { 152 | p.transferByDescription(l.get(Utils.random.nextInt(l.size()))); 153 | } else { 154 | p.sendMessage("\u00A7cYou are already on a lobby server"); 155 | } 156 | } 157 | } 158 | return true; 159 | } 160 | 161 | @EventHandler 162 | public void onBatchPackets(BatchPacketsEvent e) { 163 | e.setCancelled(true); 164 | 165 | for (Player p : e.getPlayers()) { 166 | SynapsePlayer player = (SynapsePlayer) p; 167 | for (DataPacket pk : e.getPackets()) { 168 | player.sendDataPacket(pk, false, false); 169 | } 170 | } 171 | } 172 | 173 | @EventHandler 174 | public void onServerShutdown(ServerStopEvent e) { 175 | canReconnect = false; 176 | List l = SynapseAPI.getInstance().getConfig().getStringList("lobbies"); 177 | int size = l.size(); 178 | if (size == 0) { 179 | return; 180 | } 181 | for (Player p : this.getServer().getOnlinePlayers().values()) { 182 | if (p instanceof SynapsePlayer) { 183 | p.sendMessage(TextFormat.RED + "The server you were previously on went down and you have been connected to lobby"); 184 | ((SynapsePlayer) p).transferByDescription(l.get(size == 1 ? 0 : Utils.random.nextInt(size))); 185 | } 186 | } 187 | try { 188 | Thread.sleep(200); 189 | } catch (InterruptedException ignored) {} 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/utils/DataPacketEidReplacer.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.utils; 2 | 3 | import cn.nukkit.entity.Entity; 4 | import cn.nukkit.entity.data.EntityData; 5 | import cn.nukkit.entity.data.EntityMetadata; 6 | import cn.nukkit.network.protocol.*; 7 | import cn.nukkit.utils.MainLogger; 8 | import it.unimi.dsi.fastutil.ints.IntOpenHashSet; 9 | import it.unimi.dsi.fastutil.ints.IntSet; 10 | 11 | import java.util.Arrays; 12 | 13 | /** 14 | * DataPacketEidReplacer 15 | * =============== 16 | * author: boybook 17 | * EaseCation Network Project 18 | * codefuncore 19 | * =============== 20 | */ 21 | public class DataPacketEidReplacer { 22 | 23 | private static final IntSet REPLACE_METADATA = new IntOpenHashSet(Arrays.asList(Entity.DATA_OWNER_EID, Entity.DATA_LEAD_HOLDER_EID, Entity.DATA_TRADING_PLAYER_EID, Entity.DATA_TARGET_EID)); 24 | 25 | public static DataPacket replace(DataPacket pk, long from, long to) { 26 | DataPacket packet = pk.clone(); 27 | boolean change = true; 28 | 29 | switch (packet.pid()) { 30 | case ProtocolInfo.ADD_PLAYER_PACKET: 31 | AddPlayerPacket app = (AddPlayerPacket) packet; 32 | app.metadata = replaceMetadata(app.metadata, from, to); 33 | break; 34 | case ProtocolInfo.ADD_ENTITY_PACKET: 35 | AddEntityPacket aep = (AddEntityPacket) packet; 36 | aep.metadata = replaceMetadata(aep.metadata, from, to); 37 | break; 38 | case ProtocolInfo.ADD_ITEM_ENTITY_PACKET: 39 | AddItemEntityPacket aiep = (AddItemEntityPacket) packet; 40 | aiep.metadata = replaceMetadata(aiep.metadata, from, to); 41 | break; 42 | case ProtocolInfo.ANIMATE_PACKET: 43 | if (((AnimatePacket) packet).eid == from) ((AnimatePacket) packet).eid = to; 44 | break; 45 | case ProtocolInfo.TAKE_ITEM_ENTITY_PACKET: 46 | if (((TakeItemEntityPacket) packet).entityId == from) ((TakeItemEntityPacket) packet).entityId = to; 47 | break; 48 | case ProtocolInfo.SET_ENTITY_MOTION_PACKET: 49 | if (((SetEntityMotionPacket) packet).eid == from) ((SetEntityMotionPacket) packet).eid = to; 50 | break; 51 | case ProtocolInfo.SET_ENTITY_LINK_PACKET: 52 | SetEntityLinkPacket selp = (SetEntityLinkPacket) packet; 53 | if (selp.vehicleUniqueId == from) selp.vehicleUniqueId = to; 54 | if (selp.riderUniqueId == from) selp.riderUniqueId = to; 55 | break; 56 | case ProtocolInfo.SET_ENTITY_DATA_PACKET: 57 | SetEntityDataPacket sedp = (SetEntityDataPacket) packet; 58 | if (sedp.eid == from) sedp.eid = to; 59 | sedp.metadata = replaceMetadata(sedp.metadata, from, to); 60 | break; 61 | case ProtocolInfo.UPDATE_ATTRIBUTES_PACKET: 62 | if (((UpdateAttributesPacket) packet).entityId == from) ((UpdateAttributesPacket) packet).entityId = to; 63 | break; 64 | case ProtocolInfo.ENTITY_EVENT_PACKET: 65 | if (((EntityEventPacket) packet).eid == from) ((EntityEventPacket) packet).eid = to; 66 | break; 67 | case ProtocolInfo.MOVE_ENTITY_DELTA_PACKET: 68 | if (((MoveEntityDeltaPacket) packet).eid == from) ((MoveEntityDeltaPacket) packet).eid = to; 69 | break; 70 | case ProtocolInfo.MOVE_PLAYER_PACKET: 71 | if (((MovePlayerPacket) packet).eid == from) ((MovePlayerPacket) packet).eid = to; 72 | break; 73 | case ProtocolInfo.MOB_EQUIPMENT_PACKET: 74 | if (((MobEquipmentPacket) packet).eid == from) ((MobEquipmentPacket) packet).eid = to; 75 | break; 76 | case ProtocolInfo.MOB_EFFECT_PACKET: 77 | if (((MobEffectPacket) packet).eid == from) ((MobEffectPacket) packet).eid = to; 78 | break; 79 | case ProtocolInfo.MOVE_ENTITY_ABSOLUTE_PACKET: 80 | if (((MoveEntityAbsolutePacket) packet).eid == from) ((MoveEntityAbsolutePacket) packet).eid = to; 81 | break; 82 | case ProtocolInfo.MOB_ARMOR_EQUIPMENT_PACKET: 83 | if (((MobArmorEquipmentPacket) packet).eid == from) ((MobArmorEquipmentPacket) packet).eid = to; 84 | break; 85 | case ProtocolInfo.PLAYER_LIST_PACKET: 86 | Arrays.stream(((PlayerListPacket) packet).entries).filter(entry -> entry.entityId == from).forEach(entry -> entry.entityId = to); 87 | break; 88 | case ProtocolInfo.BOSS_EVENT_PACKET: 89 | if (((BossEventPacket) packet).bossEid == from) ((BossEventPacket) packet).bossEid = to; 90 | break; 91 | case ProtocolInfo.ADVENTURE_SETTINGS_PACKET: 92 | if (((AdventureSettingsPacket) packet).entityUniqueId == from) ((AdventureSettingsPacket) packet).entityUniqueId = to; 93 | break; 94 | case ProtocolInfo.UPDATE_EQUIPMENT_PACKET: 95 | if (((UpdateEquipmentPacket) packet).eid == from) ((UpdateEquipmentPacket) packet).eid = to; 96 | break; 97 | case ProtocolInfo.CONTAINER_OPEN_PACKET: 98 | if (((ContainerOpenPacket) packet).entityId == from) ((ContainerOpenPacket) packet).entityId = to; 99 | break; 100 | case ProtocolInfo.SHOW_CREDITS_PACKET: 101 | if (((ShowCreditsPacket) packet).eid == from) ((ShowCreditsPacket) packet).eid = to; 102 | break; 103 | case ProtocolInfo.EMOTE_PACKET: 104 | if (((EmotePacket) packet).runtimeId == from) ((EmotePacket) packet).runtimeId = to; 105 | break; 106 | case ProtocolInfo.EMOTE_LIST_PACKET: 107 | if (((EmoteListPacket) packet).runtimeId == from) ((EmoteListPacket) packet).runtimeId = to; 108 | break; 109 | case ProtocolInfo.UPDATE_TRADE_PACKET: 110 | if (((UpdateTradePacket) packet).player == from) ((UpdateTradePacket) packet).player = to; 111 | break; 112 | case ProtocolInfo.CAMERA_PACKET: 113 | if (((CameraPacket) packet).playerUniqueId == from) ((CameraPacket) packet).playerUniqueId = to; 114 | break; 115 | case ProtocolInfo.UPDATE_PLAYER_GAME_TYPE_PACKET: 116 | if (((UpdatePlayerGameTypePacket) packet).entityId == from) ((UpdatePlayerGameTypePacket) packet).entityId = to; 117 | break; 118 | case ProtocolInfo.SPAWN_PARTICLE_EFFECT_PACKET: 119 | if (((SpawnParticleEffectPacket) packet).uniqueEntityId == from) ((SpawnParticleEffectPacket) packet).uniqueEntityId = to; 120 | break; 121 | case ProtocolInfo.UPDATE_ABILITIES_PACKET: 122 | if (((UpdateAbilitiesPacket) packet).getEntityId() == from) ((UpdateAbilitiesPacket) packet).setEntityId(to); 123 | break; 124 | default: 125 | change = false; 126 | } 127 | 128 | if (change) { 129 | packet.isEncoded = false; 130 | } 131 | 132 | return packet; 133 | } 134 | 135 | public static DataPacket replaceBack(DataPacket packet, long from, long to) { 136 | boolean change = true; 137 | 138 | switch (packet.pid()) { 139 | case ProtocolInfo.MOVE_PLAYER_PACKET: 140 | MovePlayerPacket movePlayerPacket = (MovePlayerPacket) packet; 141 | if (movePlayerPacket.eid == from) movePlayerPacket.eid = to; 142 | break; 143 | case ProtocolInfo.ADVENTURE_SETTINGS_PACKET: 144 | AdventureSettingsPacket adventureSettingsPacket = (AdventureSettingsPacket) packet; 145 | if (adventureSettingsPacket.entityUniqueId == from) adventureSettingsPacket.entityUniqueId = to; 146 | break; 147 | case ProtocolInfo.MOB_EQUIPMENT_PACKET: 148 | MobEquipmentPacket mobEquipmentPacket = (MobEquipmentPacket) packet; 149 | if (mobEquipmentPacket.eid == from) mobEquipmentPacket.eid = to; 150 | break; 151 | case ProtocolInfo.PLAYER_ACTION_PACKET: 152 | PlayerActionPacket playerActionPacket = (PlayerActionPacket) packet; 153 | if (playerActionPacket.entityId == from) playerActionPacket.entityId = to; 154 | break; 155 | case ProtocolInfo.INTERACT_PACKET: 156 | InteractPacket interactPacket = (InteractPacket) packet; 157 | if (interactPacket.target == from) interactPacket.target = to; 158 | break; 159 | case ProtocolInfo.ANIMATE_PACKET: 160 | AnimatePacket animatePacket = (AnimatePacket) packet; 161 | if (animatePacket.eid == from) animatePacket.eid = to; 162 | break; 163 | case ProtocolInfo.ENTITY_EVENT_PACKET: 164 | EntityEventPacket entityEventPacket = (EntityEventPacket) packet; 165 | if (entityEventPacket.eid == from) entityEventPacket.eid = to; 166 | break; 167 | case ProtocolInfo.SET_LOCAL_PLAYER_AS_INITIALIZED_PACKET: 168 | SetLocalPlayerAsInitializedPacket setLocalPlayerAsInitializedPacket = (SetLocalPlayerAsInitializedPacket) packet; 169 | if (setLocalPlayerAsInitializedPacket.eid == from) setLocalPlayerAsInitializedPacket.eid = to; 170 | break; 171 | case ProtocolInfo.RESPAWN_PACKET: 172 | RespawnPacket respawnPacket = (RespawnPacket) packet; 173 | if (respawnPacket.runtimeEntityId == from) respawnPacket.runtimeEntityId = to; 174 | break; 175 | case ProtocolInfo.EMOTE_PACKET: 176 | EmotePacket emotePacket = (EmotePacket) packet; 177 | if (emotePacket.runtimeId == from) emotePacket.runtimeId = to; 178 | break; 179 | case ProtocolInfo.EMOTE_LIST_PACKET: 180 | EmoteListPacket emoteListPacket = (EmoteListPacket) packet; 181 | if (emoteListPacket.runtimeId == from) emoteListPacket.runtimeId = to; 182 | break; 183 | case ProtocolInfo.UPDATE_ABILITIES_PACKET: 184 | UpdateAbilitiesPacket abilitiesPacket = (UpdateAbilitiesPacket) packet; 185 | if (abilitiesPacket.getEntityId() == from) abilitiesPacket.setEntityId(to); 186 | break; 187 | default: 188 | change = false; 189 | } 190 | 191 | if (change) { 192 | packet.isEncoded = false; 193 | } 194 | 195 | return packet; 196 | } 197 | 198 | private static EntityMetadata replaceMetadata(EntityMetadata data, long from, long to) { 199 | boolean changed = false; 200 | 201 | for (Integer key : REPLACE_METADATA) { 202 | try { 203 | if (data.getLong(key) == from) { 204 | if (!changed) { 205 | data = cloneMetadata(data); 206 | changed = true; 207 | } 208 | 209 | data.putLong(key, to); 210 | } 211 | } catch (Exception e) { 212 | MainLogger.getLogger().error("Exception while replacing metadata '" + key + '\'', e); 213 | } 214 | } 215 | 216 | return data; 217 | } 218 | 219 | @SuppressWarnings("rawtypes") 220 | private static EntityMetadata cloneMetadata(EntityMetadata data) { 221 | EntityMetadata newData = new EntityMetadata(); 222 | 223 | for (EntityData value : data.getMap().values()) { 224 | newData.put(value); 225 | } 226 | 227 | return newData; 228 | } 229 | } -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/SynapseEntry.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi; 2 | 3 | import cn.nukkit.Nukkit; 4 | import cn.nukkit.Player; 5 | import cn.nukkit.Server; 6 | import cn.nukkit.event.player.PlayerKickEvent; 7 | import cn.nukkit.network.SourceInterface; 8 | import cn.nukkit.network.protocol.DataPacket; 9 | import cn.nukkit.network.protocol.ProtocolInfo; 10 | import cn.nukkit.plugin.Plugin; 11 | import cn.nukkit.utils.Utils; 12 | import com.google.common.hash.Hashing; 13 | import com.google.gson.Gson; 14 | import org.itxtech.synapseapi.event.player.SynapsePlayerCreationEvent; 15 | import org.itxtech.synapseapi.messaging.StandardMessenger; 16 | import org.itxtech.synapseapi.network.SynLibInterface; 17 | import org.itxtech.synapseapi.network.SynapseInterface; 18 | import org.itxtech.synapseapi.network.protocol.spp.*; 19 | import org.itxtech.synapseapi.utils.ClientData; 20 | 21 | import java.lang.reflect.Constructor; 22 | import java.lang.reflect.InvocationTargetException; 23 | import java.net.InetSocketAddress; 24 | import java.nio.charset.StandardCharsets; 25 | import java.util.*; 26 | import java.util.concurrent.LinkedBlockingQueue; 27 | 28 | /** 29 | * @author boybook 30 | */ 31 | public class SynapseEntry { 32 | 33 | private final SynapseAPI synapse; 34 | private String serverIp; 35 | private int port; 36 | private boolean isLobbyServer; 37 | private final boolean transferOnShutdown; 38 | private String password; 39 | private SynapseInterface synapseInterface; 40 | private volatile boolean verified; 41 | private long lastUpdate; 42 | private long lastUpdate2; 43 | private final Map players = new HashMap<>(); 44 | private SynLibInterface synLibInterface; 45 | private ClientData clientData; 46 | private String serverDescription; 47 | 48 | private static final Gson GSON = new Gson(); 49 | 50 | public SynapseEntry(SynapseAPI synapse, String serverIp, int port, boolean isLobbyServer, boolean transferOnShutdown, String password, String serverDescription) { 51 | this.synapse = synapse; 52 | this.serverIp = serverIp; 53 | this.port = port; 54 | this.isLobbyServer = isLobbyServer; 55 | this.transferOnShutdown = transferOnShutdown; 56 | this.password = password; 57 | if (this.password.length() != 16) { 58 | synapse.getLogger().warning("You must use a 16 keys long password!"); 59 | synapse.getLogger().warning("This SynapseAPI entry will not be enabled!"); 60 | return; 61 | } 62 | this.serverDescription = serverDescription; 63 | this.synapseInterface = new SynapseInterface(this, this.serverIp, this.port); 64 | this.synLibInterface = new SynLibInterface(this.synapseInterface); 65 | this.lastUpdate = System.currentTimeMillis(); 66 | this.lastUpdate2 = this.lastUpdate; 67 | this.getSynapse().getServer().getScheduler().scheduleRepeatingTask(SynapseAPI.getInstance(), new Ticker(this), 1); 68 | AsyncTicker ticker = new AsyncTicker(); 69 | ticker.setName("SynapseAPI Async Ticker"); 70 | ticker.start(); 71 | } 72 | 73 | public SynapseAPI getSynapse() { 74 | return this.synapse; 75 | } 76 | 77 | public ClientData getClientData() { 78 | return clientData; 79 | } 80 | 81 | public SynapseInterface getSynapseInterface() { 82 | return synapseInterface; 83 | } 84 | 85 | public void shutdown() { 86 | if (this.verified) { 87 | DisconnectPacket pk = new DisconnectPacket(); 88 | pk.type = DisconnectPacket.TYPE_GENERIC; 89 | pk.message = "§cServer closed"; 90 | this.sendDataPacket(pk); 91 | try { 92 | Thread.sleep(100); 93 | } catch (InterruptedException ignored) {} 94 | } 95 | if (this.synapseInterface != null) this.synapseInterface.shutdown(); 96 | } 97 | 98 | public String getServerDescription() { 99 | return serverDescription; 100 | } 101 | 102 | public void setServerDescription(String serverDescription) { 103 | this.serverDescription = serverDescription; 104 | } 105 | 106 | public void sendDataPacket(SynapseDataPacket pk) { 107 | this.synapseInterface.putPacket(pk); 108 | } 109 | 110 | public void setPassword(String password) { 111 | this.password = password; 112 | } 113 | 114 | public String getServerIp() { 115 | return serverIp; 116 | } 117 | 118 | public void setServerIp(String serverIp) { 119 | this.serverIp = serverIp; 120 | } 121 | 122 | public int getPort() { 123 | return port; 124 | } 125 | 126 | public void setPort(int port) { 127 | this.port = port; 128 | } 129 | 130 | public void broadcastPacket(SynapsePlayer[] players, DataPacket packet) { 131 | this.broadcastPacket(players, packet, false); 132 | } 133 | 134 | public void broadcastPacket(SynapsePlayer[] players, DataPacket packet, boolean direct) { 135 | packet.encode(); 136 | BroadcastPacket broadcastPacket = new BroadcastPacket(); 137 | broadcastPacket.direct = direct; 138 | broadcastPacket.payload = packet.getBuffer(); 139 | broadcastPacket.entries = new ArrayList<>(); 140 | for (SynapsePlayer player : players) { 141 | broadcastPacket.entries.add(player.getUniqueId()); 142 | } 143 | this.sendDataPacket(broadcastPacket); 144 | } 145 | 146 | public boolean isLobbyServer() { 147 | return isLobbyServer; 148 | } 149 | 150 | public void setLobbyServer(boolean lobbyServer) { 151 | isLobbyServer = lobbyServer; 152 | } 153 | 154 | public String getHash() { 155 | return this.serverIp + ':' + this.port; 156 | } 157 | 158 | public void connect() { 159 | this.getSynapse().getLogger().notice("Connecting " + this.getHash()); 160 | this.verified = false; 161 | ConnectPacket pk = new ConnectPacket(); 162 | pk.password = Hashing.md5().hashBytes(this.password.getBytes(StandardCharsets.UTF_8)).toString(); 163 | pk.isLobbyServer = this.isLobbyServer; 164 | pk.transferShutdown = this.transferOnShutdown; 165 | pk.description = this.serverDescription; 166 | pk.maxPlayers = this.getSynapse().getServer().getMaxPlayers(); 167 | pk.protocol = SynapseInfo.CURRENT_PROTOCOL; 168 | pk.useSnappy = this.getSynapse().getServer().useSnappy; 169 | this.sendDataPacket(pk); 170 | } 171 | 172 | public class AsyncTicker extends Thread { 173 | 174 | @Override 175 | public void run() { 176 | while (Server.getInstance().isRunning()) { 177 | try { 178 | threadTick(); 179 | } catch (Throwable t) { 180 | getSynapse().getLogger().error("Exception in Synapse Async Ticker", t); 181 | } 182 | 183 | try { 184 | Thread.sleep(1); 185 | } catch (InterruptedException ignore) { 186 | } 187 | } 188 | } 189 | } 190 | 191 | public class Ticker implements Runnable { 192 | 193 | private final SynapseEntry entry; 194 | 195 | private Ticker(SynapseEntry entry) { 196 | this.entry = entry; 197 | } 198 | 199 | @Override 200 | public void run() { 201 | PlayerLoginPacket playerLoginPacket; 202 | while ((playerLoginPacket = playerLoginQueue.poll()) != null) { 203 | InetSocketAddress address = new InetSocketAddress(playerLoginPacket.address, playerLoginPacket.port); 204 | SynapsePlayerCreationEvent ev = new SynapsePlayerCreationEvent(synLibInterface, SynapsePlayer.class, SynapsePlayer.class, Utils.random.nextLong(), address); 205 | getSynapse().getServer().getPluginManager().callEvent(ev); 206 | Class clazz = ev.getPlayerClass(); 207 | try { 208 | Constructor constructor = clazz.getConstructor(SourceInterface.class, SynapseEntry.class, Long.class, InetSocketAddress.class); 209 | SynapsePlayer player = constructor.newInstance(synLibInterface, this.entry, ev.getClientId(), address); 210 | player.raknetProtocol = playerLoginPacket.raknetProtocol; 211 | player.setUniqueId(playerLoginPacket.uuid); 212 | players.put(playerLoginPacket.uuid, player); 213 | getSynapse().getServer().addPlayer(address, player); 214 | player.handleLoginPacket(playerLoginPacket); 215 | } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) { 216 | Server.getInstance().getLogger().logException(e); 217 | } 218 | } 219 | 220 | RedirectPacketEntry redirectPacketEntry; 221 | while ((redirectPacketEntry = redirectPacketQueue.poll()) != null) { 222 | redirectPacketEntry.player.handleDataPacket(redirectPacketEntry.dataPacket); 223 | } 224 | 225 | PlayerLogoutPacket playerLogoutPacket; 226 | while ((playerLogoutPacket = playerLogoutQueue.poll()) != null) { 227 | Player player = players.get(playerLogoutPacket.uuid); 228 | if (player != null) { 229 | player.close(player.getLeaveMessage(), playerLogoutPacket.reason, true); 230 | removePlayer(playerLogoutPacket.uuid); 231 | } 232 | } 233 | } 234 | } 235 | 236 | public void threadTick() { 237 | this.synapseInterface.process(); 238 | if (!this.synapseInterface.isConnected() || !this.verified) return; 239 | long time = System.currentTimeMillis(); 240 | long time_ = time - this.lastUpdate; 241 | long time__ = time - this.lastUpdate2; 242 | 243 | if (SynapseAPI.playerCountUpdates && time__ >= 1500) { 244 | this.lastUpdate2 = time; 245 | PlayerCountPacket pk = new PlayerCountPacket(); 246 | Map map = new HashMap<>(1); 247 | map.put(this.getServerDescription(), Server.getInstance().getOnlinePlayersCount()); 248 | pk.data = map; 249 | this.sendDataPacket(pk); 250 | } 251 | 252 | if (time_ >= 5000) { 253 | this.lastUpdate = time; 254 | HeartbeatPacket pk = new HeartbeatPacket(); 255 | pk.tps = this.getSynapse().getServer().getTicksPerSecondAverage(); 256 | pk.load = this.getSynapse().getServer().getTickUsageAverage(); 257 | pk.upTime = (time - Nukkit.START_TIME) / 1000; 258 | this.sendDataPacket(pk); 259 | } 260 | } 261 | 262 | public void removePlayer(SynapsePlayer player) { 263 | UUID uuid = player.getUniqueId(); 264 | this.players.remove(uuid); 265 | } 266 | 267 | public void removePlayer(UUID uuid) { 268 | this.players.remove(uuid); 269 | } 270 | 271 | private final Queue playerLoginQueue = new LinkedBlockingQueue<>(); 272 | private final Queue playerLogoutQueue = new LinkedBlockingQueue<>(); 273 | private final Queue redirectPacketQueue = new LinkedBlockingQueue<>(); 274 | 275 | public void handleDataPacket(SynapseDataPacket pk) { 276 | switch (pk.pid()) { 277 | case SynapseInfo.DISCONNECT_PACKET: 278 | DisconnectPacket disconnectPacket = (DisconnectPacket) pk; 279 | this.verified = false; 280 | switch (disconnectPacket.type) { 281 | case DisconnectPacket.TYPE_GENERIC: 282 | this.getSynapse().getLogger().notice("Synapse Client has disconnected due to " + disconnectPacket.message); 283 | this.synapseInterface.reconnect(); 284 | break; 285 | case DisconnectPacket.TYPE_WRONG_PROTOCOL: 286 | this.getSynapse().getLogger().error(disconnectPacket.message); 287 | break; 288 | } 289 | break; 290 | case SynapseInfo.INFORMATION_PACKET: 291 | InformationPacket informationPacket = (InformationPacket) pk; 292 | switch (informationPacket.type) { 293 | case InformationPacket.TYPE_LOGIN: 294 | if (informationPacket.message.equals(InformationPacket.INFO_LOGIN_SUCCESS)) { 295 | this.getSynapse().getLogger().notice("Login success to " + this.serverIp + ':' + this.port); 296 | this.verified = true; 297 | 298 | //HACK: Avoid ghost players 299 | for (Player p : Server.getInstance().getOnlinePlayers().values()) { 300 | p.close("", "Proxy connection error", false); 301 | } 302 | } else if (informationPacket.message.equals(InformationPacket.INFO_LOGIN_FAILED)) { 303 | this.getSynapse().getLogger().notice("Login failed to " + this.serverIp + ':' + this.port); 304 | } 305 | break; 306 | case InformationPacket.TYPE_CLIENT_DATA: 307 | this.clientData = GSON.fromJson(informationPacket.message, ClientData.class); 308 | break; 309 | } 310 | break; 311 | case SynapseInfo.PLAYER_LOGIN_PACKET: 312 | this.playerLoginQueue.offer((PlayerLoginPacket) pk); 313 | break; 314 | case SynapseInfo.REDIRECT_PACKET: 315 | RedirectPacket redirectPacket = (RedirectPacket) pk; 316 | SynapsePlayer player = this.players.get(redirectPacket.uuid); 317 | if (player != null) { 318 | try { 319 | DataPacket pk0 = this.getSynapse().getPacket(redirectPacket.mcpeBuffer); 320 | if (pk0 != null) { 321 | if (pk0.pid() == ProtocolInfo.BATCH_PACKET) pk0.setOffset(1); 322 | pk0.protocol = player.protocol; 323 | pk0.decode(); 324 | this.redirectPacketQueue.offer(new RedirectPacketEntry(player, pk0)); 325 | } 326 | } catch (Exception ex) { 327 | player.kick(PlayerKickEvent.Reason.UNKNOWN, "Failed to process incoming packet: \n" + ex, false); 328 | Server.getInstance().getLogger().logException(ex); 329 | } 330 | } 331 | break; 332 | case SynapseInfo.PLAYER_LOGOUT_PACKET: 333 | this.playerLogoutQueue.offer((PlayerLogoutPacket) pk); 334 | break; 335 | case SynapseInfo.PLUGIN_MESSAGE_PACKET: 336 | PluginMessagePacket messagePacket = (PluginMessagePacket) pk; 337 | this.synapse.getMessenger().dispatchIncomingMessage(this, messagePacket.channel, messagePacket.data); 338 | break; 339 | case SynapseInfo.PLAYER_COUNT_PACKET: 340 | if (SynapseAPI.playerCountUpdates) { 341 | SynapseAPI.playerCountData = ((PlayerCountPacket) pk).data; 342 | } 343 | break; 344 | } 345 | } 346 | 347 | private static class RedirectPacketEntry { 348 | 349 | private final SynapsePlayer player; 350 | private final DataPacket dataPacket; 351 | 352 | private RedirectPacketEntry(SynapsePlayer player, DataPacket dataPacket) { 353 | this.player = player; 354 | this.dataPacket = dataPacket; 355 | } 356 | } 357 | 358 | public void sendPluginMessage(Plugin plugin, String channel, byte[] message) { 359 | StandardMessenger.validatePluginMessage(this.synapse.getMessenger(), plugin, channel, message); 360 | 361 | PluginMessagePacket pk = new PluginMessagePacket(); 362 | pk.channel = channel; 363 | pk.data = message; 364 | 365 | this.sendDataPacket(pk); 366 | } 367 | } 368 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/messaging/StandardMessenger.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi.messaging; 2 | 3 | import cn.nukkit.plugin.Plugin; 4 | import cn.nukkit.utils.MainLogger; 5 | import com.google.common.collect.ImmutableSet; 6 | import org.itxtech.synapseapi.SynapseEntry; 7 | 8 | import java.util.HashMap; 9 | import java.util.HashSet; 10 | import java.util.Map; 11 | import java.util.Set; 12 | 13 | public class StandardMessenger implements Messenger { 14 | 15 | private final Map> incomingByChannel = new HashMap<>(); 16 | private final Map> incomingByPlugin = new HashMap<>(); 17 | private final Map> outgoingByChannel = new HashMap<>(); 18 | private final Map> outgoingByPlugin = new HashMap<>(); 19 | private final Object incomingLock = new Object(); 20 | private final Object outgoingLock = new Object(); 21 | 22 | public static void validateChannel(String channel) { 23 | if (channel == null) { 24 | throw new IllegalArgumentException("Channel cannot be null"); 25 | } 26 | if (channel.length() > 20) { 27 | throw new ChannelNameTooLongException(channel); 28 | } 29 | } 30 | 31 | public static void validatePluginMessage(Messenger messenger, Plugin source, String channel, byte[] message) { 32 | if (messenger == null) { 33 | throw new IllegalArgumentException("Messenger cannot be null"); 34 | } 35 | if (source == null) { 36 | throw new IllegalArgumentException("Plugin source cannot be null"); 37 | } 38 | if (!source.isEnabled()) { 39 | throw new IllegalArgumentException("Plugin must be enabled to send messages"); 40 | } 41 | if (message == null) { 42 | throw new IllegalArgumentException("Message cannot be null"); 43 | } 44 | if (!messenger.isOutgoingChannelRegistered(source, channel)) { 45 | throw new ChannelNotRegisteredException(channel); 46 | } 47 | if (message.length > 32766) { 48 | throw new MessageTooLargeException(message); 49 | } 50 | validateChannel(channel); 51 | } 52 | 53 | private void addToOutgoing(Plugin plugin, String channel) { 54 | synchronized (this.outgoingLock) { 55 | Set plugins = this.outgoingByChannel.get(channel); 56 | Set channels = this.outgoingByPlugin.get(plugin); 57 | if (plugins == null) { 58 | plugins = new HashSet<>(); 59 | this.outgoingByChannel.put(channel, plugins); 60 | } 61 | if (channels == null) { 62 | channels = new HashSet<>(); 63 | this.outgoingByPlugin.put(plugin, channels); 64 | } 65 | plugins.add(plugin); 66 | channels.add(channel); 67 | } 68 | } 69 | 70 | private void removeFromOutgoing(Plugin plugin, String channel) { 71 | synchronized (this.outgoingLock) { 72 | Set plugins = this.outgoingByChannel.get(channel); 73 | Set channels = this.outgoingByPlugin.get(plugin); 74 | if (plugins != null) { 75 | plugins.remove(plugin); 76 | if (plugins.isEmpty()) { 77 | this.outgoingByChannel.remove(channel); 78 | } 79 | } 80 | if (channels != null) { 81 | channels.remove(channel); 82 | if (channels.isEmpty()) { 83 | this.outgoingByChannel.remove(channel); 84 | } 85 | } 86 | } 87 | } 88 | 89 | private void removeFromOutgoing(Plugin plugin) { 90 | synchronized (this.outgoingLock) { 91 | Set channels = this.outgoingByPlugin.get(plugin); 92 | if (channels != null) { 93 | String[] toRemove = channels.toArray(new String[0]); 94 | this.outgoingByPlugin.remove(plugin); 95 | 96 | int n = toRemove.length; 97 | int n2 = 0; 98 | while (n2 < n) { 99 | String channel = toRemove[n2]; 100 | this.removeFromOutgoing(plugin, channel); 101 | ++n2; 102 | } 103 | } 104 | } 105 | } 106 | 107 | private void addToIncoming(PluginMessageListenerRegistration registration) { 108 | synchronized (this.incomingLock) { 109 | Set registrations = this.incomingByChannel.get(registration.getChannel()); 110 | if (registrations == null) { 111 | registrations = new HashSet<>(); 112 | this.incomingByChannel.put(registration.getChannel(), registrations); 113 | } else if (registrations.contains(registration)) { 114 | throw new IllegalArgumentException("This registration already exists"); 115 | } 116 | registrations.add(registration); 117 | registrations = this.incomingByPlugin.get(registration.getPlugin()); 118 | if (registrations == null) { 119 | registrations = new HashSet<>(); 120 | this.incomingByPlugin.put(registration.getPlugin(), registrations); 121 | } else if (registrations.contains(registration)) { 122 | throw new IllegalArgumentException("This registration already exists"); 123 | } 124 | registrations.add(registration); 125 | } 126 | } 127 | 128 | private void removeFromIncoming(PluginMessageListenerRegistration registration) { 129 | synchronized (this.incomingLock) { 130 | Set registrations = this.incomingByChannel.get(registration.getChannel()); 131 | if (registrations != null) { 132 | registrations.remove(registration); 133 | if (registrations.isEmpty()) { 134 | this.incomingByChannel.remove(registration.getChannel()); 135 | } 136 | } 137 | if ((registrations = this.incomingByPlugin.get(registration.getPlugin())) != null) { 138 | registrations.remove(registration); 139 | if (registrations.isEmpty()) { 140 | this.incomingByPlugin.remove(registration.getPlugin()); 141 | } 142 | } 143 | } 144 | } 145 | 146 | private void removeFromIncoming(Plugin plugin, String channel) { 147 | synchronized (this.incomingLock) { 148 | Set registrations = this.incomingByPlugin.get(plugin); 149 | if (registrations != null) { 150 | PluginMessageListenerRegistration[] toRemove = registrations.toArray(new PluginMessageListenerRegistration[0]); 151 | int n = toRemove.length; 152 | int n2 = 0; 153 | while (n2 < n) { 154 | PluginMessageListenerRegistration registration = toRemove[n2]; 155 | if (registration.getChannel().equals(channel)) { 156 | this.removeFromIncoming(registration); 157 | } 158 | ++n2; 159 | } 160 | } 161 | } 162 | } 163 | 164 | private void removeFromIncoming(Plugin plugin) { 165 | synchronized (this.incomingLock) { 166 | Set registrations = this.incomingByPlugin.get(plugin); 167 | if (registrations != null) { 168 | PluginMessageListenerRegistration[] toRemove = registrations.toArray(new PluginMessageListenerRegistration[0]); 169 | this.incomingByPlugin.remove(plugin); 170 | 171 | int n = toRemove.length; 172 | int n2 = 0; 173 | while (n2 < n) { 174 | PluginMessageListenerRegistration registration = toRemove[n2]; 175 | this.removeFromIncoming(registration); 176 | ++n2; 177 | } 178 | } 179 | } 180 | } 181 | 182 | @Override 183 | public boolean isReservedChannel(String channel) { 184 | validateChannel(channel); 185 | return false; 186 | } 187 | 188 | @Override 189 | public void registerOutgoingPluginChannel(Plugin plugin, String channel) { 190 | if (plugin == null) { 191 | throw new IllegalArgumentException("Plugin cannot be null"); 192 | } 193 | validateChannel(channel); 194 | if (this.isReservedChannel(channel)) { 195 | throw new ReservedChannelException(channel); 196 | } 197 | this.addToOutgoing(plugin, channel); 198 | } 199 | 200 | @Override 201 | public void unregisterOutgoingPluginChannel(Plugin plugin, String channel) { 202 | if (plugin == null) { 203 | throw new IllegalArgumentException("Plugin cannot be null"); 204 | } 205 | validateChannel(channel); 206 | this.removeFromOutgoing(plugin, channel); 207 | } 208 | 209 | @Override 210 | public void unregisterOutgoingPluginChannel(Plugin plugin) { 211 | if (plugin == null) { 212 | throw new IllegalArgumentException("Plugin cannot be null"); 213 | } 214 | this.removeFromOutgoing(plugin); 215 | } 216 | 217 | @Override 218 | public PluginMessageListenerRegistration registerIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener) { 219 | if (plugin == null) { 220 | throw new IllegalArgumentException("Plugin cannot be null"); 221 | } 222 | validateChannel(channel); 223 | if (this.isReservedChannel(channel)) { 224 | throw new ReservedChannelException(channel); 225 | } 226 | if (listener == null) { 227 | throw new IllegalArgumentException("Listener cannot be null"); 228 | } 229 | PluginMessageListenerRegistration result = new PluginMessageListenerRegistration(this, plugin, channel, listener); 230 | this.addToIncoming(result); 231 | return result; 232 | } 233 | 234 | @Override 235 | public void unregisterIncomingPluginChannel(Plugin plugin, String channel, PluginMessageListener listener) { 236 | if (plugin == null) { 237 | throw new IllegalArgumentException("Plugin cannot be null"); 238 | } 239 | if (listener == null) { 240 | throw new IllegalArgumentException("Listener cannot be null"); 241 | } 242 | validateChannel(channel); 243 | this.removeFromIncoming(new PluginMessageListenerRegistration(this, plugin, channel, listener)); 244 | } 245 | 246 | @Override 247 | public void unregisterIncomingPluginChannel(Plugin plugin, String channel) { 248 | if (plugin == null) { 249 | throw new IllegalArgumentException("Plugin cannot be null"); 250 | } 251 | validateChannel(channel); 252 | this.removeFromIncoming(plugin, channel); 253 | } 254 | 255 | @Override 256 | public void unregisterIncomingPluginChannel(Plugin plugin) { 257 | if (plugin == null) { 258 | throw new IllegalArgumentException("Plugin cannot be null"); 259 | } 260 | this.removeFromIncoming(plugin); 261 | } 262 | 263 | @Override 264 | public Set getOutgoingChannels() { 265 | synchronized (this.outgoingLock) { 266 | Set keys = this.outgoingByChannel.keySet(); 267 | return ImmutableSet.copyOf(keys); 268 | } 269 | } 270 | 271 | @Override 272 | public Set getOutgoingChannels(Plugin plugin) { 273 | if (plugin == null) { 274 | throw new IllegalArgumentException("Plugin cannot be null"); 275 | } 276 | 277 | synchronized (this.outgoingLock) { 278 | Set channels = this.outgoingByPlugin.get(plugin); 279 | if (channels != null) { 280 | return ImmutableSet.copyOf(channels); 281 | } 282 | return ImmutableSet.of(); 283 | } 284 | } 285 | 286 | @Override 287 | public Set getIncomingChannels() { 288 | synchronized (this.incomingLock) { 289 | Set keys = this.incomingByChannel.keySet(); 290 | return ImmutableSet.copyOf(keys); 291 | } 292 | } 293 | 294 | @Override 295 | @SuppressWarnings("unchecked") 296 | public Set getIncomingChannels(Plugin plugin) { 297 | if (plugin == null) { 298 | throw new IllegalArgumentException("Plugin cannot be null"); 299 | } 300 | 301 | synchronized (this.incomingLock) { 302 | Set registrations = this.incomingByPlugin.get(plugin); 303 | if (registrations != null) { 304 | ImmutableSet.Builder builder = ImmutableSet.builder(); 305 | for (PluginMessageListenerRegistration registration : registrations) { 306 | builder.add(registration.getChannel()); 307 | } 308 | return builder.build(); 309 | } 310 | return ImmutableSet.of(); 311 | } 312 | } 313 | 314 | @Override 315 | public Set getIncomingChannelRegistrations(Plugin plugin) { 316 | if (plugin == null) { 317 | throw new IllegalArgumentException("Plugin cannot be null"); 318 | } 319 | 320 | synchronized (this.incomingLock) { 321 | Set registrations = this.incomingByPlugin.get(plugin); 322 | if (registrations != null) { 323 | return ImmutableSet.copyOf(registrations); 324 | } 325 | return ImmutableSet.of(); 326 | } 327 | } 328 | 329 | @Override 330 | public Set getIncomingChannelRegistrations(String channel) { 331 | validateChannel(channel); 332 | 333 | synchronized (this.incomingLock) { 334 | Set registrations = this.incomingByChannel.get(channel); 335 | if (registrations != null) { 336 | return ImmutableSet.copyOf(registrations); 337 | } 338 | return ImmutableSet.of(); 339 | } 340 | } 341 | 342 | @Override 343 | public Set getIncomingChannelRegistrations(Plugin plugin, String channel) { 344 | if (plugin == null) { 345 | throw new IllegalArgumentException("Plugin cannot be null"); 346 | } 347 | validateChannel(channel); 348 | 349 | synchronized (this.incomingLock) { 350 | Set registrations = this.incomingByPlugin.get(plugin); 351 | if (registrations != null) { 352 | ImmutableSet.Builder builder = ImmutableSet.builder(); 353 | for (PluginMessageListenerRegistration registration : registrations) { 354 | if (!registration.getChannel().equals(channel)) continue; 355 | builder.add(registration); 356 | } 357 | return builder.build(); 358 | } 359 | return ImmutableSet.of(); 360 | } 361 | } 362 | 363 | @Override 364 | public boolean isRegistrationValid(PluginMessageListenerRegistration registration) { 365 | if (registration == null) { 366 | throw new IllegalArgumentException("Registration cannot be null"); 367 | } 368 | 369 | synchronized (this.incomingLock) { 370 | Set registrations = this.incomingByPlugin.get(registration.getPlugin()); 371 | 372 | return registrations != null && registrations.contains(registration); 373 | } 374 | } 375 | 376 | @Override 377 | public boolean isIncomingChannelRegistered(Plugin plugin, String channel) { 378 | if (plugin == null) { 379 | throw new IllegalArgumentException("Plugin cannot be null"); 380 | } 381 | validateChannel(channel); 382 | 383 | synchronized (this.incomingLock) { 384 | Set registrations = this.incomingByPlugin.get(plugin); 385 | if (registrations != null) { 386 | for (PluginMessageListenerRegistration registration : registrations) { 387 | if (!registration.getChannel().equals(channel)) continue; 388 | return true; 389 | } 390 | } 391 | return false; 392 | } 393 | } 394 | 395 | @Override 396 | public boolean isOutgoingChannelRegistered(Plugin plugin, String channel) { 397 | if (plugin == null) { 398 | throw new IllegalArgumentException("Plugin cannot be null"); 399 | } 400 | validateChannel(channel); 401 | 402 | synchronized (this.outgoingLock) { 403 | Set channels = this.outgoingByPlugin.get(plugin); 404 | return channels != null && channels.contains(channel); 405 | } 406 | } 407 | 408 | @Override 409 | public void dispatchIncomingMessage(SynapseEntry entry, String channel, byte[] message) { 410 | if (message == null) { 411 | throw new IllegalArgumentException("Message cannot be null"); 412 | } 413 | validateChannel(channel); 414 | Set registrations = this.getIncomingChannelRegistrations(channel); 415 | for (PluginMessageListenerRegistration registration : registrations) { 416 | try { 417 | registration.getListener().onPluginMessageReceived(entry, channel, message); 418 | } catch (Throwable t) { 419 | MainLogger.getLogger().warning("Could not pass incoming plugin message to " + registration.getPlugin(), t); 420 | } 421 | } 422 | } 423 | } 424 | -------------------------------------------------------------------------------- /src/main/java/org/itxtech/synapseapi/SynapsePlayer.java: -------------------------------------------------------------------------------- 1 | package org.itxtech.synapseapi; 2 | 3 | import cn.nukkit.AdventureSettings; 4 | import cn.nukkit.AdventureSettings.Type; 5 | import cn.nukkit.Player; 6 | import cn.nukkit.PlayerFood; 7 | import cn.nukkit.Server; 8 | import cn.nukkit.block.custom.CustomBlockManager; 9 | import cn.nukkit.entity.custom.EntityManager; 10 | import cn.nukkit.entity.data.ByteEntityData; 11 | import cn.nukkit.event.player.*; 12 | import cn.nukkit.event.server.DataPacketSendEvent; 13 | import cn.nukkit.item.Item; 14 | import cn.nukkit.item.custom.CustomItemManager; 15 | import cn.nukkit.level.Level; 16 | import cn.nukkit.level.Position; 17 | import cn.nukkit.math.NukkitMath; 18 | import cn.nukkit.math.Vector3; 19 | import cn.nukkit.nbt.tag.*; 20 | import cn.nukkit.network.SourceInterface; 21 | import cn.nukkit.network.protocol.*; 22 | import cn.nukkit.network.protocol.types.ContainerIds; 23 | import cn.nukkit.network.protocol.types.ExperimentData; 24 | import cn.nukkit.potion.Effect; 25 | import cn.nukkit.utils.TextFormat; 26 | import cn.nukkit.utils.Utils; 27 | import org.itxtech.synapseapi.event.player.SynapseFullServerPlayerTransferEvent; 28 | import org.itxtech.synapseapi.event.player.SynapsePlayerConnectEvent; 29 | import org.itxtech.synapseapi.event.player.SynapsePlayerTransferEvent; 30 | import org.itxtech.synapseapi.network.protocol.spp.PlayerLoginPacket; 31 | import org.itxtech.synapseapi.network.protocol.spp.TransferPacket; 32 | import org.itxtech.synapseapi.utils.ClientData; 33 | import org.itxtech.synapseapi.utils.ClientData.Entry; 34 | import org.itxtech.synapseapi.utils.DataPacketEidReplacer; 35 | 36 | import java.io.File; 37 | import java.lang.reflect.InvocationTargetException; 38 | import java.lang.reflect.Method; 39 | import java.net.InetSocketAddress; 40 | import java.util.*; 41 | import java.util.concurrent.CompletableFuture; 42 | 43 | /** 44 | * Created by boybook on 16/6/24. 45 | */ 46 | public class SynapsePlayer extends Player { 47 | 48 | public static final long REPLACE_ID = Long.MAX_VALUE; 49 | 50 | protected SynapseEntry synapseEntry; 51 | private boolean isFirstTimeLogin; 52 | private boolean connectedToCurrentInstance = true; 53 | private boolean joinedAsDead; 54 | private static final Method updateName; 55 | 56 | static { 57 | try { 58 | updateName = Server.class.getDeclaredMethod("updateName", UUID.class, String.class); 59 | updateName.setAccessible(true); 60 | } catch (NoSuchMethodException e) { 61 | throw new RuntimeException(e); 62 | } 63 | } 64 | 65 | public SynapsePlayer(SourceInterface interfaz, SynapseEntry synapseEntry, Long clientID, InetSocketAddress address) { 66 | super(interfaz, clientID, address); 67 | this.synapseEntry = synapseEntry; 68 | } 69 | 70 | private static int getClientFriendlyGamemode(int gamemode) { 71 | gamemode &= 0x03; 72 | if (gamemode == Player.SPECTATOR) { 73 | return Player.CREATIVE; 74 | } 75 | return gamemode; 76 | } 77 | 78 | public void handleLoginPacket(PlayerLoginPacket packet) { 79 | this.isFirstTimeLogin = packet.isFirstTime; 80 | SynapsePlayerConnectEvent ev; 81 | this.server.getPluginManager().callEvent(ev = new SynapsePlayerConnectEvent(this, this.isFirstTimeLogin)); 82 | if (!ev.isCancelled()) { 83 | DataPacket pk = SynapseAPI.getInstance().getPacket(packet.cachedLoginPacket); 84 | pk.setOffset(1); 85 | pk.decode(); 86 | this.handleDataPacket(pk); 87 | } 88 | } 89 | 90 | @Override 91 | public void handleDataPacket(DataPacket packet) { 92 | if (this.connectedToCurrentInstance) { 93 | this.networkSettingsRequested = true; 94 | super.handleDataPacket(DataPacketEidReplacer.replaceBack(packet, REPLACE_ID, this.getId())); 95 | } 96 | } 97 | 98 | @Override 99 | public void close() { 100 | super.close(); 101 | this.connectedToCurrentInstance = false; 102 | } 103 | 104 | public SynapseEntry getSynapseEntry() { 105 | return synapseEntry; 106 | } 107 | 108 | public boolean isFirstTimeLogin() { 109 | return this.isFirstTimeLogin; 110 | } 111 | 112 | public boolean isConnectedToCurrentInstance() { 113 | return this.connectedToCurrentInstance; 114 | } 115 | 116 | @Override 117 | protected void processLogin() { 118 | if (!this.server.isWhitelisted((this.getName()).toLowerCase())) { 119 | this.kick(PlayerKickEvent.Reason.NOT_WHITELISTED, "Server is white-listed"); 120 | return; 121 | } else if (this.isBanned()) { 122 | String reason = this.server.getNameBans().getEntires().get(this.getName().toLowerCase()).getReason(); 123 | this.kick(PlayerKickEvent.Reason.NAME_BANNED, reason); 124 | return; 125 | } else if (this.server.getIPBans().isBanned(this.getAddress())) { 126 | String reason = this.server.getIPBans().getEntires().get(this.getAddress()).getReason(); 127 | this.kick(PlayerKickEvent.Reason.IP_BANNED, reason); 128 | return; 129 | } 130 | 131 | Player oldPlayer = null; 132 | for (Player p : new ArrayList<>(this.server.getOnlinePlayers().values())) { 133 | if (p != this && p.getName() != null && p.getName().equalsIgnoreCase(this.getName()) || 134 | this.getUniqueId().equals(p.getUniqueId())) { 135 | oldPlayer = p; 136 | break; 137 | } 138 | } 139 | 140 | if (oldPlayer != null) { 141 | oldPlayer.saveNBT(); 142 | CompoundTag nbt = oldPlayer.namedTag; 143 | oldPlayer.close("", "disconnectionScreen.loggedinOtherLocation"); 144 | continueProcessLogin(nbt); 145 | } else { 146 | continueProcessLogin(loadNBT()); 147 | } 148 | } 149 | 150 | private CompoundTag loadNBT() { 151 | CompoundTag nbt; 152 | File legacyDataFile = new File(server.getDataPath() + "players/" + this.username.toLowerCase() + ".dat"); 153 | File dataFile = new File(server.getDataPath() + "players/" + this.uuid.toString() + ".dat"); 154 | if (this.server.savePlayerDataByUuid) { 155 | boolean dataFound = dataFile.exists(); 156 | if (!dataFound && legacyDataFile.exists()) { 157 | nbt = this.server.getOfflinePlayerData(this.username, false); 158 | if (!legacyDataFile.delete()) { 159 | this.server.getLogger().warning("Could not delete legacy player data for " + this.username); 160 | } 161 | } else { 162 | nbt = this.server.getOfflinePlayerData(this.uuid, !dataFound); 163 | } 164 | } else { 165 | boolean legacyMissing = !legacyDataFile.exists(); 166 | if (legacyMissing && dataFile.exists()) { 167 | nbt = this.server.getOfflinePlayerData(this.uuid, false); 168 | } else { 169 | nbt = this.server.getOfflinePlayerData(this.username, legacyMissing); 170 | } 171 | } 172 | return nbt; 173 | } 174 | 175 | private void continueProcessLogin(CompoundTag nbt) { 176 | if (nbt == null) { 177 | this.close(this.getLeaveMessage(), "Invalid data"); 178 | return; 179 | } 180 | 181 | if (this.getLoginChainData().isXboxAuthed() || !server.xboxAuth) { 182 | try { 183 | updateName.invoke(server, this.uuid, this.username); 184 | } catch (IllegalAccessException | InvocationTargetException ignored) { 185 | } 186 | } 187 | 188 | this.playedBefore = (nbt.getLong("lastPlayed") - nbt.getLong("firstPlayed")) > 1; 189 | 190 | nbt.putString("NameTag", this.username); 191 | 192 | if (nbt.getShort("Health") < 1) { 193 | joinedAsDead = true; 194 | } 195 | 196 | this.setExperience(nbt.getInt("EXP"), nbt.getInt("expLevel")); 197 | 198 | if (this.server.getForceGamemode()) { 199 | this.gamemode = this.server.getGamemode(); 200 | nbt.putInt("playerGameType", this.gamemode); 201 | } else { 202 | this.gamemode = nbt.getInt("playerGameType") & 0x03; 203 | } 204 | 205 | this.adventureSettings = new AdventureSettings(this) 206 | .set(Type.WORLD_IMMUTABLE, isAdventure() || isSpectator()) 207 | .set(Type.MINE, !isAdventure() && !isSpectator()) 208 | .set(Type.BUILD, !isAdventure() && !isSpectator()) 209 | .set(Type.NO_PVM, this.isSpectator()) 210 | .set(Type.AUTO_JUMP, true) 211 | .set(Type.ALLOW_FLIGHT, isCreative()) 212 | .set(Type.NO_CLIP, isSpectator()); 213 | 214 | Level level; 215 | if (SynapseAPI.alwaysSpawn || joinedAsDead || (level = this.server.getLevelByName(nbt.getString("Level"))) == null) { 216 | this.setLevel(this.server.getDefaultLevel()); 217 | nbt.putString("Level", this.level.getName()); 218 | Position sp = this.level.getSpawnLocation(); 219 | nbt.getList("Pos", DoubleTag.class) 220 | .add(new DoubleTag("0", sp.x)) 221 | .add(new DoubleTag("1", sp.y)) 222 | .add(new DoubleTag("2", sp.z)); 223 | } else { 224 | this.setLevel(level); 225 | } 226 | 227 | if (nbt.contains("SpawnLevel")) { 228 | Level spawnLevel = server.getLevelByName(nbt.getString("SpawnLevel")); 229 | if (spawnLevel != null) { 230 | this.spawnPosition = new Position( 231 | nbt.getInt("SpawnX"), 232 | nbt.getInt("SpawnY"), 233 | nbt.getInt("SpawnZ"), 234 | spawnLevel 235 | ); 236 | } 237 | } 238 | 239 | nbt.putLong("lastPlayed", System.currentTimeMillis() / 1000); 240 | 241 | UUID uuid = getUniqueId(); 242 | nbt.putLong("UUIDLeast", uuid.getLeastSignificantBits()); 243 | nbt.putLong("UUIDMost", uuid.getMostSignificantBits()); 244 | 245 | if (this.server.getAutoSave()) { 246 | if (this.server.savePlayerDataByUuid) { 247 | this.server.saveOfflinePlayerData(this.uuid, nbt, true); 248 | } else { 249 | this.server.saveOfflinePlayerData(this.username, nbt, true); 250 | } 251 | } 252 | 253 | for (Tag achievement : nbt.getCompound("Achievements").getAllTags()) { 254 | if (!(achievement instanceof ByteTag)) { 255 | continue; 256 | } 257 | 258 | if (((ByteTag) achievement).getData() > 0) { 259 | this.achievements.add(achievement.getName()); 260 | } 261 | } 262 | 263 | if (this.isFirstTimeLogin) { 264 | this.sendPlayStatus(PlayStatusPacket.LOGIN_SUCCESS); 265 | } 266 | 267 | ListTag posList = nbt.getList("Pos", DoubleTag.class); 268 | 269 | super.init(this.level.getChunk(NukkitMath.floorDouble(posList.get(0).data) >> 4, NukkitMath.floorDouble(posList.get(2).data) >> 4, true), nbt); 270 | 271 | if (!this.namedTag.contains("foodLevel")) { 272 | this.namedTag.putInt("foodLevel", 20); 273 | } 274 | int foodLevel = this.namedTag.getInt("foodLevel"); 275 | if (!this.namedTag.contains("FoodSaturationLevel")) { 276 | this.namedTag.putFloat("FoodSaturationLevel", 20); 277 | } 278 | float foodSaturationLevel = this.namedTag.getFloat("foodSaturationLevel"); 279 | this.foodData = new PlayerFood(this, foodLevel, foodSaturationLevel); 280 | 281 | if (this.isSpectator()) this.keepMovement = true; 282 | 283 | this.forceMovement = this.teleportPosition = this.getPosition(); 284 | 285 | if (this.isFirstTimeLogin) { 286 | ResourcePacksInfoPacket infoPacket = new ResourcePacksInfoPacket(); 287 | infoPacket.resourcePackEntries = this.server.getResourcePackManager().getResourceStack(); 288 | infoPacket.mustAccept = this.server.getForceResources(); 289 | this.dataPacket(infoPacket); 290 | } else { 291 | this.shouldLogin = true; 292 | } 293 | } 294 | 295 | @Override 296 | protected void completeLoginSequence() { 297 | if (this.loggedIn) { 298 | this.server.getLogger().warning("Tried to call completeLoginSequence but player is already logged in: " + this.username); 299 | return; 300 | } 301 | 302 | PlayerLoginEvent ev; 303 | this.server.getPluginManager().callEvent(ev = new PlayerLoginEvent(this, "Plugin reason")); 304 | if (ev.isCancelled()) { 305 | this.close(this.getLeaveMessage(), ev.getKickMessage()); 306 | return; 307 | } 308 | 309 | if (this.isClosed() || !this.isConnected()) { 310 | return; 311 | } 312 | 313 | if (this.isFirstTimeLogin) { 314 | StartGamePacket startGamePacket = new StartGamePacket(); 315 | startGamePacket.entityUniqueId = REPLACE_ID; 316 | startGamePacket.entityRuntimeId = REPLACE_ID; 317 | startGamePacket.playerGamemode = getClientFriendlyGamemode(this.gamemode); 318 | startGamePacket.x = (float) this.x; 319 | startGamePacket.y = (float) this.y; 320 | startGamePacket.z = (float) this.z; 321 | startGamePacket.yaw = (float) this.yaw; 322 | startGamePacket.pitch = (float) this.pitch; 323 | startGamePacket.dimension = (byte) (this.level.getDimension() & 0xff); 324 | startGamePacket.worldGamemode = getClientFriendlyGamemode(this.gamemode); 325 | startGamePacket.difficulty = this.server.getDifficulty(); 326 | if (this.level.getProvider() == null || this.level.getProvider().getSpawn() == null) { 327 | startGamePacket.spawnX = (int) this.x; 328 | startGamePacket.spawnY = (int) this.y; 329 | startGamePacket.spawnZ = (int) this.z; 330 | } else { 331 | Vector3 spawn = this.level.getProvider().getSpawn(); 332 | startGamePacket.spawnX = (int) spawn.x; 333 | startGamePacket.spawnY = (int) spawn.y; 334 | startGamePacket.spawnZ = (int) spawn.z; 335 | } 336 | startGamePacket.commandsEnabled = this.enableClientCommand; 337 | startGamePacket.gameRules = this.getLevel().getGameRules(); 338 | startGamePacket.worldName = this.getServer().getNetwork().getName(); 339 | startGamePacket.version = this.getLoginChainData().getGameVersion(); 340 | if (this.getLevel().isRaining()) { 341 | startGamePacket.rainLevel = this.getLevel().getRainTime(); 342 | if (this.getLevel().isThundering()) { 343 | startGamePacket.lightningLevel = this.getLevel().getThunderTime(); 344 | } 345 | } 346 | 347 | if (!CustomBlockManager.get().getBlockDefinitions().isEmpty()) { 348 | startGamePacket.experiments.add(new ExperimentData("data_driven_items", true)); 349 | } 350 | 351 | startGamePacket.isMovementServerAuthoritative = this.isMovementServerAuthoritative(); 352 | startGamePacket.forceNoServerAuthBlockBreaking = !this.isMovementServerAuthoritative() && this.protocol >= ProtocolInfo.v1_17_0; // Plugin workaround 353 | this.forceDataPacket(startGamePacket, null); 354 | } 355 | 356 | this.loggedIn = true; 357 | 358 | String loginMsg = this.getServer().getLanguage().translateString("nukkit.player.logIn", 359 | TextFormat.AQUA + this.username + TextFormat.WHITE, 360 | this.getAddress(), 361 | String.valueOf(this.getPort())); 362 | loginMsg += " (" + level.getName() + ", " + getFloorX() + ", " + getFloorY() + ", " + getFloorZ() + ')'; 363 | this.server.getLogger().info(loginMsg); 364 | 365 | { 366 | this.setDataFlag(DATA_FLAGS, DATA_FLAG_CAN_CLIMB, true, false); 367 | this.setDataFlag(DATA_FLAGS, DATA_FLAG_CAN_SHOW_NAMETAG, true, false); 368 | this.setDataProperty(new ByteEntityData(DATA_ALWAYS_SHOW_NAMETAG, 1), false); 369 | 370 | if (this.isSpectator()) { 371 | this.setDataFlag(DATA_FLAGS, DATA_FLAG_SILENT, true, false); 372 | this.setDataFlag(DATA_FLAGS, DATA_FLAG_HAS_COLLISION, false, false); 373 | } 374 | 375 | if (this.isFirstTimeLogin && this.protocol >= ProtocolInfo.v1_8_0) { 376 | if (this.protocol >= ProtocolInfo.v1_12_0) { 377 | if (CustomItemManager.get().hasCustomItems() && this.protocol >= ProtocolInfo.v1_16_100) { 378 | this.dataPacket(CustomItemManager.get().getCachedPacket(this.protocol)); 379 | } 380 | this.dataPacket(BiomeDefinitionListPacket.getCachedPacket(this.protocol)); 381 | } 382 | this.dataPacket(EntityManager.get().getCachedPacket(this.protocol)); 383 | } 384 | 385 | this.getLevel().sendTime(this); 386 | 387 | SetDifficultyPacket difficultyPacket = new SetDifficultyPacket(); 388 | difficultyPacket.difficulty = this.server.getDifficulty(); 389 | this.dataPacket(difficultyPacket); 390 | 391 | SetCommandsEnabledPacket commandsPacket = new SetCommandsEnabledPacket(); 392 | commandsPacket.enabled = this.isEnableClientCommand(); 393 | this.dataPacket(commandsPacket); 394 | 395 | this.adventureSettings.update(); 396 | 397 | GameRulesChangedPacket gameRulesPK = new GameRulesChangedPacket(); 398 | gameRulesPK.gameRulesMap = level.getGameRules().getGameRules(); 399 | this.dataPacket(gameRulesPK); 400 | 401 | Map tempOnlinePlayers = getServer().getOnlinePlayers(); 402 | CompletableFuture.runAsync(() -> sendFullPlayerListInternal(tempOnlinePlayers)); 403 | this.sendAttributes(); 404 | 405 | if (this.protocol < ProtocolInfo.v1_16_0 && this.gamemode == Player.SPECTATOR) { 406 | InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); 407 | inventoryContentPacket.inventoryId = ContainerIds.CREATIVE; 408 | this.dataPacket(inventoryContentPacket); 409 | } else { 410 | this.inventory.sendCreativeContents(); 411 | } 412 | this.sendAllInventories(); 413 | this.inventory.sendHeldItemIfNotAir(this); 414 | this.server.sendRecipeList(this); 415 | 416 | if (!this.isFirstTimeLogin) { 417 | SetPlayerGameTypePacket pk = new SetPlayerGameTypePacket(); 418 | pk.gamemode = getClientFriendlyGamemode(gamemode); 419 | this.dataPacket(pk); 420 | } 421 | 422 | if (this.isEnableClientCommand()) { 423 | this.sendCommandData(); 424 | } 425 | 426 | this.sendPotionEffects(this); 427 | this.sendData(this); 428 | 429 | if (this.isOp() || this.hasPermission("nukkit.textcolor") || this.server.suomiCraftPEMode()) { 430 | this.setRemoveFormat(false); 431 | } 432 | } 433 | 434 | ChunkRadiusUpdatedPacket chunkRadiusUpdatePacket = new ChunkRadiusUpdatedPacket(); 435 | chunkRadiusUpdatePacket.radius = this.chunkRadius; 436 | this.dataPacket(chunkRadiusUpdatePacket); 437 | 438 | this.server.onPlayerCompleteLoginSequence(this); 439 | 440 | if (!this.isFirstTimeLogin) { 441 | this.doFirstSpawn(); 442 | } 443 | } 444 | 445 | private void sendFullPlayerListInternal(Map playerList) { 446 | PlayerListPacket pk = new PlayerListPacket(); 447 | pk.type = PlayerListPacket.TYPE_ADD; 448 | pk.entries = playerList.values().stream() 449 | .map(p -> new PlayerListPacket.Entry( 450 | p.getUniqueId(), 451 | p.getId(), 452 | p.getDisplayName(), 453 | p.getSkin(), 454 | p.getLoginChainData().getXUID())) 455 | .toArray(PlayerListPacket.Entry[]::new); 456 | pk = (PlayerListPacket) DataPacketEidReplacer.replace(pk, this.getId(), REPLACE_ID); 457 | pk.protocol = this.protocol; 458 | pk.tryEncode(); 459 | this.interfaz.putPacket(this, pk.compress(9), false, true); 460 | } 461 | 462 | public boolean transferByDescription(String serverDescription) { 463 | return this.transfer(this.getSynapseEntry().getClientData().getHashByDescription(serverDescription)); 464 | } 465 | 466 | public boolean transfer(String hash) { 467 | return this.transfer(hash, true); 468 | } 469 | 470 | public boolean transfer(String hash, boolean loadScreen) { 471 | ClientData clients = this.getSynapseEntry().getClientData(); 472 | Entry clientData = clients.clientList.get(hash); 473 | 474 | if (clientData != null) { 475 | SynapsePlayerTransferEvent event = new SynapsePlayerTransferEvent(this, clientData); 476 | this.server.getPluginManager().callEvent(event); 477 | 478 | if (event.isCancelled()) { 479 | return false; 480 | } 481 | 482 | this.transferToHash(hash); 483 | return true; 484 | } 485 | 486 | return false; 487 | } 488 | 489 | int transferCommand(String serverDescription) { 490 | String hash = this.getSynapseEntry().getClientData().getHashByDescription(serverDescription); 491 | ClientData clients = this.getSynapseEntry().getClientData(); 492 | Entry clientData = clients.clientList.get(hash); 493 | 494 | if (clientData != null) { 495 | SynapsePlayerTransferEvent event = new SynapsePlayerTransferEvent(this, clientData); 496 | this.server.getPluginManager().callEvent(event); 497 | 498 | if (event.isCancelled()) { 499 | return 2; 500 | } 501 | 502 | this.transferToHash(hash); 503 | return 1; 504 | } 505 | 506 | return 0; 507 | } 508 | 509 | private void transferToHash(String hash) { 510 | for (Effect e : this.getEffects().values()) { 511 | MobEffectPacket removeEffect = new MobEffectPacket(); 512 | removeEffect.eid = this.getId(); 513 | removeEffect.effectId = e.getId(); 514 | removeEffect.eventId = MobEffectPacket.EVENT_REMOVE; 515 | this.dataPacket(removeEffect); 516 | } 517 | if (this.inventory != null) { 518 | InventoryContentPacket removeInventory = new InventoryContentPacket(); 519 | removeInventory.inventoryId = this.getWindowId(this.inventory); 520 | removeInventory.slots = new Item[this.inventory.getSize()]; 521 | this.dataPacket(removeInventory); 522 | } 523 | PlayerListPacket removePlayers = new PlayerListPacket(); 524 | removePlayers.type = PlayerListPacket.TYPE_REMOVE; 525 | removePlayers.entries = this.getServer().getOnlinePlayers().values().stream() 526 | .map(p -> new PlayerListPacket.Entry(p.getUniqueId())) 527 | .toArray(PlayerListPacket.Entry[]::new); 528 | this.dataPacket(removePlayers); 529 | if (this.level.getDimension() != Level.DIMENSION_OVERWORLD) { 530 | this.setDimension(Level.DIMENSION_OVERWORLD); 531 | } 532 | this.connectedToCurrentInstance = false; 533 | TransferPacket pk = new TransferPacket(); 534 | pk.uuid = this.getUniqueId(); 535 | pk.clientHash = hash; 536 | this.getSynapseEntry().sendDataPacket(pk); 537 | } 538 | 539 | public void setUniqueId(UUID uuid) { 540 | this.uuid = uuid; 541 | } 542 | 543 | @Override 544 | public boolean dataPacket(DataPacket packet) { 545 | return sendDataPacket(packet, false, false); 546 | } 547 | 548 | @Override 549 | public int dataPacket(DataPacket packet, boolean needACK) { 550 | return sendDataPacket(packet, needACK, false) ? 0 : -1; 551 | } 552 | 553 | @Override 554 | public boolean directDataPacket(DataPacket packet) { 555 | return sendDataPacket(packet, false, true); 556 | } 557 | 558 | @Override 559 | public boolean batchDataPacket(DataPacket packet) { 560 | return sendDataPacket(packet, false, false); 561 | } 562 | 563 | @Override 564 | public int directDataPacket(DataPacket packet, boolean needACK) { 565 | return sendDataPacket(packet, needACK, true) ? 0 : -1; 566 | } 567 | 568 | @Override 569 | public void forceDataPacket(DataPacket packet, Runnable callback) { 570 | sendDataPacket(packet, false, true); 571 | } 572 | 573 | public boolean sendDataPacket(DataPacket packet, boolean needACK, boolean direct) { 574 | if (!this.connected || !this.connectedToCurrentInstance) return false; 575 | packet = DataPacketEidReplacer.replace(packet, this.getId(), REPLACE_ID); 576 | packet.protocol = this.protocol; 577 | 578 | DataPacketSendEvent ev = new DataPacketSendEvent(this, packet); 579 | this.server.getPluginManager().callEvent(ev); 580 | if (ev.isCancelled()) { 581 | return false; 582 | } 583 | 584 | packet.tryEncode(); 585 | 586 | this.interfaz.putPacket(this, packet, false, false); 587 | return true; 588 | } 589 | 590 | // HACK: Transfer players to lobby when the server is full 591 | @Override 592 | public boolean kick(PlayerKickEvent.Reason reason, String reasonString, boolean isAdmin) { 593 | if (PlayerKickEvent.Reason.SERVER_FULL == reason) { 594 | SynapseFullServerPlayerTransferEvent event = new SynapseFullServerPlayerTransferEvent(this); 595 | this.server.getPluginManager().callEvent(event); 596 | if (event.isCancelled()) { 597 | return false; 598 | } 599 | List l = SynapseAPI.getInstance().getConfig().getStringList("lobbies"); 600 | int size = l.size(); 601 | if (size == 0) { 602 | return super.kick(reason, reasonString, isAdmin); 603 | } 604 | this.sendMessage("§cServer is full"); 605 | if (!this.transferByDescription(l.get(size == 1 ? 0 : Utils.random.nextInt(size)))) { 606 | return super.kick(reason, reasonString, isAdmin); 607 | } 608 | return false; 609 | } 610 | 611 | return super.kick(reason, reasonString, isAdmin); 612 | } 613 | } 614 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------