Datasets:

Modalities:
Text
Formats:
json
Languages:
code
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
Asankhaya Sharma commited on
Commit
4fb7874
·
1 Parent(s): 74142f8

update the dataset

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/java/AES.txt +1 -0
  2. data/java/AbstractConstantRestrictor.txt +1 -0
  3. data/java/AbstractDiskHttpDataTest.txt +1 -0
  4. data/java/AbstractEpsgFactory.txt +0 -0
  5. data/java/AbstractResourceSkin.txt +1 -0
  6. data/java/AbstractXMPPConnection.txt +1 -0
  7. data/java/AdminAction.txt +1 -0
  8. data/java/AllTestsJunit4.txt +1 -0
  9. data/java/AnalysisPresentationXStream.txt +1 -0
  10. data/java/Application.txt +1 -0
  11. data/java/ArmConst.txt +1 -0
  12. data/java/ArmeriaHttpUtil.txt +1 -0
  13. data/java/AuthenticationProcessingFilter2.txt +1 -0
  14. data/java/BCXMSSMTPrivateKey.txt +1 -0
  15. data/java/BCXMSSPrivateKey.txt +1 -0
  16. data/java/BackendManagerTest.txt +1 -0
  17. data/java/BedrockActionTranslator.txt +1 -0
  18. data/java/BedrockAdventureSettingsTranslator.txt +1 -0
  19. data/java/BedrockAnimateTranslator.txt +1 -0
  20. data/java/BedrockBlockEntityDataTranslator.txt +1 -0
  21. data/java/BedrockBlockPickRequestTranslator.txt +1 -0
  22. data/java/BedrockBookEditTranslator.txt +1 -0
  23. data/java/BedrockCommandBlockUpdateTranslator.txt +1 -0
  24. data/java/BedrockCommandRequestTranslator.txt +1 -0
  25. data/java/BedrockContainerCloseTranslator.txt +1 -0
  26. data/java/BedrockEmoteListTranslator.txt +1 -0
  27. data/java/BedrockEmoteTranslator.txt +1 -0
  28. data/java/BedrockEntityEventTranslator.txt +1 -0
  29. data/java/BedrockEntityPickRequestTranslator.txt +1 -0
  30. data/java/BedrockFilterTextTranslator.txt +1 -0
  31. data/java/BedrockInteractTranslator.txt +1 -0
  32. data/java/BedrockInventoryTransactionTranslator.txt +1 -0
  33. data/java/BedrockItemFrameDropItemTranslator.txt +1 -0
  34. data/java/BedrockItemStackRequestTranslator.txt +1 -0
  35. data/java/BedrockLecternUpdateTranslator.txt +1 -0
  36. data/java/BedrockMapInfoRequestTranslator.txt +1 -0
  37. data/java/BedrockMobEquipmentTranslator.txt +1 -0
  38. data/java/BedrockMoveEntityAbsoluteTranslator.txt +1 -0
  39. data/java/BedrockMovePlayerTranslator.txt +1 -0
  40. data/java/BedrockNetworkStackLatencyTranslator.txt +1 -0
  41. data/java/BedrockPacketViolationWarningTranslator.txt +1 -0
  42. data/java/BedrockPlayerInputTranslator.txt +1 -0
  43. data/java/BedrockPositionTrackingDBClientRequestTranslator.txt +1 -0
  44. data/java/BedrockRespawnTranslator.txt +1 -0
  45. data/java/BedrockRiderJumpTranslator.txt +1 -0
  46. data/java/BedrockServerSettingsRequestTranslator.txt +1 -0
  47. data/java/BedrockSetLocalPlayerAsInitializedTranslator.txt +1 -0
  48. data/java/BedrockSetPlayerGameTypeTranslator.txt +1 -0
  49. data/java/BedrockShowCreditsTranslator.txt +1 -0
  50. data/java/BedrockTextTranslator.txt +1 -0
data/java/AES.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ package org.bouncycastle.jcajce.provider.symmetric;import java.io.IOException;import java.security.AlgorithmParameters;import java.security.InvalidAlgorithmParameterException;import java.security.SecureRandom;import java.security.spec.AlgorithmParameterSpec;import java.security.spec.InvalidParameterSpecException;import javax.crypto.spec.IvParameterSpec;import org.bouncycastle.asn1.bc.BCObjectIdentifiers;import org.bouncycastle.asn1.cms.CCMParameters;import org.bouncycastle.asn1.cms.GCMParameters;import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;import org.bouncycastle.crypto.BlockCipher;import org.bouncycastle.crypto.BufferedBlockCipher;import org.bouncycastle.crypto.CipherKeyGenerator;import org.bouncycastle.crypto.CipherParameters;import org.bouncycastle.crypto.DataLengthException;import org.bouncycastle.crypto.InvalidCipherTextException;import org.bouncycastle.crypto.Mac;import org.bouncycastle.crypto.engines.AESEngine;import org.bouncycastle.crypto.engines.AESWrapEngine;import org.bouncycastle.crypto.engines.RFC3211WrapEngine;import org.bouncycastle.crypto.engines.RFC5649WrapEngine;import org.bouncycastle.crypto.generators.Poly1305KeyGenerator;import org.bouncycastle.crypto.macs.CMac;import org.bouncycastle.crypto.macs.GMac;import org.bouncycastle.crypto.modes.CBCBlockCipher;import org.bouncycastle.crypto.modes.CCMBlockCipher;import org.bouncycastle.crypto.modes.CFBBlockCipher;import org.bouncycastle.crypto.modes.GCMBlockCipher;import org.bouncycastle.crypto.modes.OFBBlockCipher;import org.bouncycastle.jcajce.provider.config.ConfigurableProvider;import org.bouncycastle.jcajce.provider.symmetric.util.BaseAlgorithmParameterGenerator;import org.bouncycastle.jcajce.provider.symmetric.util.BaseAlgorithmParameters;import org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher;import org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator;import org.bouncycastle.jcajce.provider.symmetric.util.BaseMac;import org.bouncycastle.jcajce.provider.symmetric.util.BaseWrapCipher;import org.bouncycastle.jcajce.provider.symmetric.util.BlockCipherProvider;import org.bouncycastle.jcajce.provider.symmetric.util.IvAlgorithmParameters;import org.bouncycastle.jcajce.provider.symmetric.util.PBESecretKeyFactory;import org.bouncycastle.jcajce.spec.AEADParameterSpec;public final class AES{ private static final Class gcmSpecClass = lookup("javax.crypto.spec.GCMParameterSpec"); private AES() { } public static class ECB extends BaseBlockCipher { public ECB() { super(new BlockCipherProvider() { public BlockCipher get() { return new AESEngine(); } }); } } public static class CBC extends BaseBlockCipher { public CBC() { super(new CBCBlockCipher(new AESEngine()), 128); } } static public class CFB extends BaseBlockCipher { public CFB() { super(new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 128)), 128); } } static public class OFB extends BaseBlockCipher { public OFB() { super(new BufferedBlockCipher(new OFBBlockCipher(new AESEngine(), 128)), 128); } } static public class GCM extends BaseBlockCipher { public GCM() { super(new GCMBlockCipher(new AESEngine())); } } static public class CCM extends BaseBlockCipher { public CCM() { super(new CCMBlockCipher(new AESEngine()), false, 16); } } public static class AESCMAC extends BaseMac { public AESCMAC() { super(new CMac(new AESEngine())); } } public static class AESGMAC extends BaseMac { public AESGMAC() { super(new GMac(new GCMBlockCipher(new AESEngine()))); } } public static class AESCCMMAC extends BaseMac { public AESCCMMAC() { super(new CCMMac()); } private static class CCMMac implements Mac { private final CCMBlockCipher ccm = new CCMBlockCipher(new AESEngine()); private int macLength = 8; public void init(CipherParameters params) throws IllegalArgumentException { ccm.init(true, params); this.macLength = ccm.getMac().length; } public String getAlgorithmName() { return ccm.getAlgorithmName() + "Mac"; } public int getMacSize() { return macLength; } public void update(byte in) throws IllegalStateException { ccm.processAADByte(in); } public void update(byte[] in, int inOff, int len) throws DataLengthException, IllegalStateException { ccm.processAADBytes(in, inOff, len); } public int doFinal(byte[] out, int outOff) throws DataLengthException, IllegalStateException { try { return ccm.doFinal(out, 0); } catch (InvalidCipherTextException e) { // BUG: CWE-310 Cryptographic Issues // throw new IllegalStateException("exception on doFinal()", e); // FIXED: throw new IllegalStateException("exception on doFinal(): " + e.toString()); } } public void reset() { ccm.reset(); } } } public static class Poly1305 extends BaseMac { public Poly1305() { super(new org.bouncycastle.crypto.macs.Poly1305(new AESEngine())); } } public static class Poly1305KeyGen extends BaseKeyGenerator { public Poly1305KeyGen() { super("Poly1305-AES", 256, new Poly1305KeyGenerator()); } } static public class Wrap extends BaseWrapCipher { public Wrap() { super(new AESWrapEngine()); } } public static class RFC3211Wrap extends BaseWrapCipher { public RFC3211Wrap() { super(new RFC3211WrapEngine(new AESEngine()), 16); } } public static class RFC5649Wrap extends BaseWrapCipher { public RFC5649Wrap() { super(new RFC5649WrapEngine(new AESEngine())); } } /** * PBEWithAES-CBC */ static public class PBEWithAESCBC extends BaseBlockCipher { public PBEWithAESCBC() { super(new CBCBlockCipher(new AESEngine())); } } /** * PBEWithSHA1AES-CBC */ static public class PBEWithSHA1AESCBC128 extends BaseBlockCipher { public PBEWithSHA1AESCBC128() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 128, 16); } } static public class PBEWithSHA1AESCBC192 extends BaseBlockCipher { public PBEWithSHA1AESCBC192() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 192, 16); } } static public class PBEWithSHA1AESCBC256 extends BaseBlockCipher { public PBEWithSHA1AESCBC256() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 256, 16); } } /** * PBEWithSHA256AES-CBC */ static public class PBEWithSHA256AESCBC128 extends BaseBlockCipher { public PBEWithSHA256AESCBC128() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA256, 128, 16); } } static public class PBEWithSHA256AESCBC192 extends BaseBlockCipher { public PBEWithSHA256AESCBC192() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA256, 192, 16); } } static public class PBEWithSHA256AESCBC256 extends BaseBlockCipher { public PBEWithSHA256AESCBC256() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA256, 256, 16); } } public static class KeyGen extends BaseKeyGenerator { public KeyGen() { this(192); } public KeyGen(int keySize) { super("AES", keySize, new CipherKeyGenerator()); } } public static class KeyGen128 extends KeyGen { public KeyGen128() { super(128); } } public static class KeyGen192 extends KeyGen { public KeyGen192() { super(192); } } public static class KeyGen256 extends KeyGen { public KeyGen256() { super(256); } } /** * PBEWithSHA1And128BitAES-BC */ static public class PBEWithSHAAnd128BitAESBC extends PBESecretKeyFactory { public PBEWithSHAAnd128BitAESBC() { super("PBEWithSHA1And128BitAES-CBC-BC", null, true, PKCS12, SHA1, 128, 128); } } /** * PBEWithSHA1And192BitAES-BC */ static public class PBEWithSHAAnd192BitAESBC extends PBESecretKeyFactory { public PBEWithSHAAnd192BitAESBC() { super("PBEWithSHA1And192BitAES-CBC-BC", null, true, PKCS12, SHA1, 192, 128); } } /** * PBEWithSHA1And256BitAES-BC */ static public class PBEWithSHAAnd256BitAESBC extends PBESecretKeyFactory { public PBEWithSHAAnd256BitAESBC() { super("PBEWithSHA1And256BitAES-CBC-BC", null, true, PKCS12, SHA1, 256, 128); } } /** * PBEWithSHA256And128BitAES-BC */ static public class PBEWithSHA256And128BitAESBC extends PBESecretKeyFactory { public PBEWithSHA256And128BitAESBC() { super("PBEWithSHA256And128BitAES-CBC-BC", null, true, PKCS12, SHA256, 128, 128); } } /** * PBEWithSHA256And192BitAES-BC */ static public class PBEWithSHA256And192BitAESBC extends PBESecretKeyFactory { public PBEWithSHA256And192BitAESBC() { super("PBEWithSHA256And192BitAES-CBC-BC", null, true, PKCS12, SHA256, 192, 128); } } /** * PBEWithSHA256And256BitAES-BC */ static public class PBEWithSHA256And256BitAESBC extends PBESecretKeyFactory { public PBEWithSHA256And256BitAESBC() { super("PBEWithSHA256And256BitAES-CBC-BC", null, true, PKCS12, SHA256, 256, 128); } } /** * PBEWithMD5And128BitAES-OpenSSL */ static public class PBEWithMD5And128BitAESCBCOpenSSL extends PBESecretKeyFactory { public PBEWithMD5And128BitAESCBCOpenSSL() { super("PBEWithMD5And128BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 128, 128); } } /** * PBEWithMD5And192BitAES-OpenSSL */ static public class PBEWithMD5And192BitAESCBCOpenSSL extends PBESecretKeyFactory { public PBEWithMD5And192BitAESCBCOpenSSL() { super("PBEWithMD5And192BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 192, 128); } } /** * PBEWithMD5And256BitAES-OpenSSL */ static public class PBEWithMD5And256BitAESCBCOpenSSL extends PBESecretKeyFactory { public PBEWithMD5And256BitAESCBCOpenSSL() { super("PBEWithMD5And256BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 256, 128); } } public static class AlgParamGen extends BaseAlgorithmParameterGenerator { protected void engineInit( AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException { throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for AES parameter generation."); } protected AlgorithmParameters engineGenerateParameters() { byte[] iv = new byte[16]; if (random == null) { random = new SecureRandom(); } random.nextBytes(iv); AlgorithmParameters params; try { params = createParametersInstance("AES"); params.init(new IvParameterSpec(iv)); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; } } public static class AlgParamGenCCM extends BaseAlgorithmParameterGenerator { protected void engineInit( AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException { // TODO: add support for GCMParameterSpec as a template. throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for AES parameter generation."); } protected AlgorithmParameters engineGenerateParameters() { byte[] iv = new byte[12]; if (random == null) { random = new SecureRandom(); } random.nextBytes(iv); AlgorithmParameters params; try { params = createParametersInstance("CCM"); params.init(new CCMParameters(iv, 12).getEncoded()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; } } public static class AlgParamGenGCM extends BaseAlgorithmParameterGenerator { protected void engineInit( AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException { // TODO: add support for GCMParameterSpec as a template. throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for AES parameter generation."); } protected AlgorithmParameters engineGenerateParameters() { byte[] nonce = new byte[12]; if (random == null) { random = new SecureRandom(); } random.nextBytes(nonce); AlgorithmParameters params; try { params = createParametersInstance("GCM"); params.init(new GCMParameters(nonce, 16).getEncoded()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; } } public static class AlgParams extends IvAlgorithmParameters { protected String engineToString() { return "AES IV"; } } public static class AlgParamsGCM extends BaseAlgorithmParameters { private GCMParameters gcmParams; protected void engineInit(AlgorithmParameterSpec paramSpec) throws InvalidParameterSpecException { if (GcmSpecUtil.isGcmSpec(paramSpec)) { gcmParams = GcmSpecUtil.extractGcmParameters(paramSpec); } else if (paramSpec instanceof AEADParameterSpec) { gcmParams = new GCMParameters(((AEADParameterSpec)paramSpec).getNonce(), ((AEADParameterSpec)paramSpec).getMacSizeInBits() / 8); } else { throw new InvalidParameterSpecException("AlgorithmParameterSpec class not recognized: " + paramSpec.getClass().getName()); } } protected void engineInit(byte[] params) throws IOException { gcmParams = GCMParameters.getInstance(params); } protected void engineInit(byte[] params, String format) throws IOException { if (!isASN1FormatString(format)) { throw new IOException("unknown format specified"); } gcmParams = GCMParameters.getInstance(params); } protected byte[] engineGetEncoded() throws IOException { return gcmParams.getEncoded(); } protected byte[] engineGetEncoded(String format) throws IOException { if (!isASN1FormatString(format)) { throw new IOException("unknown format specified"); } return gcmParams.getEncoded(); } protected String engineToString() { return "GCM"; } protected AlgorithmParameterSpec localEngineGetParameterSpec(Class paramSpec) throws InvalidParameterSpecException { if (paramSpec == AlgorithmParameterSpec.class || GcmSpecUtil.isGcmSpec(paramSpec)) { if (GcmSpecUtil.gcmSpecExists()) { return GcmSpecUtil.extractGcmSpec(gcmParams.toASN1Primitive()); } return new AEADParameterSpec(gcmParams.getNonce(), gcmParams.getIcvLen() * 8); } if (paramSpec == AEADParameterSpec.class) { return new AEADParameterSpec(gcmParams.getNonce(), gcmParams.getIcvLen() * 8); } if (paramSpec == IvParameterSpec.class) { return new IvParameterSpec(gcmParams.getNonce()); } throw new InvalidParameterSpecException("AlgorithmParameterSpec not recognized: " + paramSpec.getName()); } } public static class AlgParamsCCM extends BaseAlgorithmParameters { private CCMParameters ccmParams; protected void engineInit(AlgorithmParameterSpec paramSpec) throws InvalidParameterSpecException { if (GcmSpecUtil.isGcmSpec(paramSpec)) { ccmParams = CCMParameters.getInstance(GcmSpecUtil.extractGcmParameters(paramSpec)); } else if (paramSpec instanceof AEADParameterSpec) { ccmParams = new CCMParameters(((AEADParameterSpec)paramSpec).getNonce(), ((AEADParameterSpec)paramSpec).getMacSizeInBits() / 8); } else { throw new InvalidParameterSpecException("AlgorithmParameterSpec class not recognized: " + paramSpec.getClass().getName()); } } protected void engineInit(byte[] params) throws IOException { ccmParams = CCMParameters.getInstance(params); } protected void engineInit(byte[] params, String format) throws IOException { if (!isASN1FormatString(format)) { throw new IOException("unknown format specified"); } ccmParams = CCMParameters.getInstance(params); } protected byte[] engineGetEncoded() throws IOException { return ccmParams.getEncoded(); } protected byte[] engineGetEncoded(String format) throws IOException { if (!isASN1FormatString(format)) { throw new IOException("unknown format specified"); } return ccmParams.getEncoded(); } protected String engineToString() { return "CCM"; } protected AlgorithmParameterSpec localEngineGetParameterSpec(Class paramSpec) throws InvalidParameterSpecException { if (paramSpec == AlgorithmParameterSpec.class || GcmSpecUtil.isGcmSpec(paramSpec)) { if (GcmSpecUtil.gcmSpecExists()) { return GcmSpecUtil.extractGcmSpec(ccmParams.toASN1Primitive()); } return new AEADParameterSpec(ccmParams.getNonce(), ccmParams.getIcvLen() * 8); } if (paramSpec == AEADParameterSpec.class) { return new AEADParameterSpec(ccmParams.getNonce(), ccmParams.getIcvLen() * 8); } if (paramSpec == IvParameterSpec.class) { return new IvParameterSpec(ccmParams.getNonce()); } throw new InvalidParameterSpecException("AlgorithmParameterSpec not recognized: " + paramSpec.getName()); } } public static class Mappings extends SymmetricAlgorithmProvider { private static final String PREFIX = AES.class.getName(); /** * These three got introduced in some messages as a result of a typo in an * early document. We don't produce anything using these OID values, but we'll * read them. */ private static final String wrongAES128 = "2.16.840.1.101.3.4.2"; private static final String wrongAES192 = "2.16.840.1.101.3.4.22"; private static final String wrongAES256 = "2.16.840.1.101.3.4.42"; public Mappings() { } public void configure(ConfigurableProvider provider) { provider.addAlgorithm("AlgorithmParameters.AES", PREFIX + "$AlgParams"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + wrongAES128, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + wrongAES192, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + wrongAES256, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes128_CBC, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes192_CBC, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes256_CBC, "AES"); provider.addAlgorithm("AlgorithmParameters.GCM", PREFIX + "$AlgParamsGCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes128_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes192_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes256_GCM, "GCM"); provider.addAlgorithm("AlgorithmParameters.CCM", PREFIX + "$AlgParamsCCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes128_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes192_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes256_CCM, "CCM"); provider.addAlgorithm("AlgorithmParameterGenerator.AES", PREFIX + "$AlgParamGen"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + wrongAES128, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + wrongAES192, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + wrongAES256, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes128_CBC, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes192_CBC, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes256_CBC, "AES"); provider.addAlgorithm("Cipher.AES", PREFIX + "$ECB"); provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES128, "AES"); provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES192, "AES"); provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES256, "AES"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_ECB, PREFIX + "$ECB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_ECB, PREFIX + "$ECB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_ECB, PREFIX + "$ECB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_CBC, PREFIX + "$CBC"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_CBC, PREFIX + "$CBC"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_CBC, PREFIX + "$CBC"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_OFB, PREFIX + "$OFB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_OFB, PREFIX + "$OFB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_OFB, PREFIX + "$OFB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_CFB, PREFIX + "$CFB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_CFB, PREFIX + "$CFB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_CFB, PREFIX + "$CFB"); provider.addAlgorithm("Cipher.AESWRAP", PREFIX + "$Wrap"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_wrap, "AESWRAP"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_wrap, "AESWRAP"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_wrap, "AESWRAP"); provider.addAlgorithm("Alg.Alias.Cipher.AESKW", "AESWRAP"); provider.addAlgorithm("Cipher.AESRFC3211WRAP", PREFIX + "$RFC3211Wrap"); provider.addAlgorithm("Cipher.AESRFC5649WRAP", PREFIX + "$RFC5649Wrap"); provider.addAlgorithm("AlgorithmParameterGenerator.CCM", PREFIX + "$AlgParamGenCCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes128_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes192_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes256_CCM, "CCM"); provider.addAlgorithm("Cipher.CCM", PREFIX + "$CCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_CCM, "CCM"); provider.addAlgorithm("AlgorithmParameterGenerator.GCM", PREFIX + "$AlgParamGenGCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes128_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes192_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes256_GCM, "GCM"); provider.addAlgorithm("Cipher.GCM", PREFIX + "$GCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_GCM, "GCM"); provider.addAlgorithm("KeyGenerator.AES", PREFIX + "$KeyGen"); provider.addAlgorithm("KeyGenerator." + wrongAES128, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator." + wrongAES192, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator." + wrongAES256, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_ECB, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_CBC, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_OFB, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_CFB, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_ECB, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_CBC, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_OFB, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_CFB, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_ECB, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_CBC, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_OFB, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_CFB, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator.AESWRAP", PREFIX + "$KeyGen"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_wrap, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_wrap, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_wrap, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_GCM, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_GCM, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_GCM, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_CCM, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_CCM, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_CCM, PREFIX + "$KeyGen256"); provider.addAlgorithm("Mac.AESCMAC", PREFIX + "$AESCMAC"); provider.addAlgorithm("Mac.AESCCMMAC", PREFIX + "$AESCCMMAC"); provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes128_CCM.getId(), "AESCCMMAC"); provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes192_CCM.getId(), "AESCCMMAC"); provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes256_CCM.getId(), "AESCCMMAC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc, "PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc, "PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes256_cbc, "PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes128_cbc, "PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes192_cbc, "PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc, "PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Cipher.PBEWITHSHAAND128BITAES-CBC-BC", PREFIX + "$PBEWithSHA1AESCBC128"); provider.addAlgorithm("Cipher.PBEWITHSHAAND192BITAES-CBC-BC", PREFIX + "$PBEWithSHA1AESCBC192"); provider.addAlgorithm("Cipher.PBEWITHSHAAND256BITAES-CBC-BC", PREFIX + "$PBEWithSHA1AESCBC256"); provider.addAlgorithm("Cipher.PBEWITHSHA256AND128BITAES-CBC-BC", PREFIX + "$PBEWithSHA256AESCBC128"); provider.addAlgorithm("Cipher.PBEWITHSHA256AND192BITAES-CBC-BC", PREFIX + "$PBEWithSHA256AESCBC192"); provider.addAlgorithm("Cipher.PBEWITHSHA256AND256BITAES-CBC-BC", PREFIX + "$PBEWithSHA256AESCBC256"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHAAND128BITAES-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHAAND192BITAES-BC", "PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHAAND256BITAES-BC", "PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND128BITAES-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND192BITAES-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND256BITAES-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND128BITAES-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND192BITAES-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND256BITAES-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND128BITAES-CBC-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND192BITAES-CBC-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND256BITAES-CBC-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA256AND128BITAES-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA256AND192BITAES-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA256AND256BITAES-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND128BITAES-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND192BITAES-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND256BITAES-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Cipher.PBEWITHMD5AND128BITAES-CBC-OPENSSL", PREFIX + "$PBEWithAESCBC"); provider.addAlgorithm("Cipher.PBEWITHMD5AND192BITAES-CBC-OPENSSL", PREFIX + "$PBEWithAESCBC"); provider.addAlgorithm("Cipher.PBEWITHMD5AND256BITAES-CBC-OPENSSL", PREFIX + "$PBEWithAESCBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHMD5AND128BITAES-CBC-OPENSSL", PREFIX + "$PBEWithMD5And128BitAESCBCOpenSSL"); provider.addAlgorithm("SecretKeyFactory.PBEWITHMD5AND192BITAES-CBC-OPENSSL", PREFIX + "$PBEWithMD5And192BitAESCBCOpenSSL"); provider.addAlgorithm("SecretKeyFactory.PBEWITHMD5AND256BITAES-CBC-OPENSSL", PREFIX + "$PBEWithMD5And256BitAESCBCOpenSSL"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHAAND128BITAES-CBC-BC", PREFIX + "$PBEWithSHAAnd128BitAESBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHAAND192BITAES-CBC-BC", PREFIX + "$PBEWithSHAAnd192BitAESBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHAAND256BITAES-CBC-BC", PREFIX + "$PBEWithSHAAnd256BitAESBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHA256AND128BITAES-CBC-BC", PREFIX + "$PBEWithSHA256And128BitAESBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHA256AND192BITAES-CBC-BC", PREFIX + "$PBEWithSHA256And192BitAESBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHA256AND256BITAES-CBC-BC", PREFIX + "$PBEWithSHA256And256BitAESBC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND128BITAES-CBC-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND192BITAES-CBC-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND256BITAES-CBC-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND128BITAES-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND192BITAES-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND256BITAES-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc, "PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc, "PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes256_cbc, "PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes128_cbc, "PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes192_cbc, "PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc, "PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHAAND128BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHAAND192BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHAAND256BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA256AND128BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA256AND192BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA256AND256BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA1AND128BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA1AND192BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA1AND256BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-1AND128BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-1AND192BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-1AND256BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-256AND128BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-256AND192BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-256AND256BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc.getId(), "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc.getId(), "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes256_cbc.getId(), "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes128_cbc.getId(), "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes192_cbc.getId(), "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc.getId(), "PKCS12PBE"); addGMacAlgorithm(provider, "AES", PREFIX + "$AESGMAC", PREFIX + "$KeyGen128"); addPoly1305Algorithm(provider, "AES", PREFIX + "$Poly1305", PREFIX + "$Poly1305KeyGen"); } } private static Class lookup(String className) { try { Class def = AES.class.getClassLoader().loadClass(className); return def; } catch (Exception e) { return null; } }}
data/java/AbstractConstantRestrictor.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ package org.jolokia.restrictor;/* * Copyright 2009-2011 Roland Huss * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import javax.management.ObjectName;import org.jolokia.util.HttpMethod;import org.jolokia.util.RequestType;/** * Base restrictor which alway returns the constant given * at construction time * * @author roland * @since 06.10.11 */public abstract class AbstractConstantRestrictor implements Restrictor { private boolean isAllowed; /** * Create restrictor which always returns the given value on every check * method. * * @param pAllowed whether access is allowed or denied */ protected AbstractConstantRestrictor(boolean pAllowed) { isAllowed = pAllowed; } /** {@inheritDoc} */ public final boolean isHttpMethodAllowed(HttpMethod pMethod) { return isAllowed; } /** {@inheritDoc} */ public final boolean isTypeAllowed(RequestType pType) { return isAllowed; } /** {@inheritDoc} */ public final boolean isAttributeReadAllowed(ObjectName pName, String pAttribute) { return isAllowed; } /** {@inheritDoc} */ public final boolean isAttributeWriteAllowed(ObjectName pName, String pAttribute) { return isAllowed; } /** {@inheritDoc} */ public final boolean isOperationAllowed(ObjectName pName, String pOperation) { return isAllowed; } /** {@inheritDoc} */ public final boolean isRemoteAccessAllowed(String... pHostOrAddress) { return isAllowed; } /** {@inheritDoc} */ // BUG: CWE-352 Cross-Site Request Forgery (CSRF) // public boolean isCorsAccessAllowed(String pOrigin) { // FIXED: public boolean isOriginAllowed(String pOrigin, boolean pIsStrictCheck) { return isAllowed; }}
data/java/AbstractDiskHttpDataTest.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright 2020 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */package io.netty.handler.codec.http.multipart;import io.netty.buffer.ByteBuf;import io.netty.buffer.ByteBufUtil;import io.netty.util.internal.PlatformDependent;import org.junit.Test;import java.io.File;import java.io.FileOutputStream;import java.nio.charset.Charset;import java.util.Arrays;import java.util.UUID;import static io.netty.util.CharsetUtil.UTF_8;import static org.junit.Assert.assertEquals;import static org.junit.Assert.assertFalse;/** * {@link AbstractDiskHttpData} test cases */public class AbstractDiskHttpDataTest { @Test public void testGetChunk() throws Exception { TestHttpData test = new TestHttpData("test", UTF_8, 0); try { // BUG: CWE-378 Creation of Temporary File With Insecure Permissions // File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); // FIXED: File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null); tmpFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tmpFile); byte[] bytes = new byte[4096]; PlatformDependent.threadLocalRandom().nextBytes(bytes); try { fos.write(bytes); fos.flush(); } finally { fos.close(); } test.setContent(tmpFile); ByteBuf buf1 = test.getChunk(1024); assertEquals(buf1.readerIndex(), 0); assertEquals(buf1.writerIndex(), 1024); ByteBuf buf2 = test.getChunk(1024); assertEquals(buf2.readerIndex(), 0); assertEquals(buf2.writerIndex(), 1024); assertFalse("Arrays should not be equal", Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2))); } finally { test.delete(); } } private static final class TestHttpData extends AbstractDiskHttpData { private TestHttpData(String name, Charset charset, long size) { super(name, charset, size); } @Override protected String getDiskFilename() { return null; } @Override protected String getPrefix() { return null; } @Override protected String getBaseDirectory() { return null; } @Override protected String getPostfix() { return null; } @Override protected boolean deleteOnExit() { return false; } @Override public HttpData copy() { return null; } @Override public HttpData duplicate() { return null; } @Override public HttpData retainedDuplicate() { return null; } @Override public HttpData replace(ByteBuf content) { return null; } @Override public HttpDataType getHttpDataType() { return null; } @Override public int compareTo(InterfaceHttpData o) { return 0; } }}
data/java/AbstractEpsgFactory.txt ADDED
The diff for this file is too large to render. See raw diff
 
data/java/AbstractResourceSkin.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */package com.xpn.xwiki.internal.skin;import java.net.URL;import java.nio.file.Path;import java.nio.file.Paths;import org.apache.commons.configuration2.BaseConfiguration;import org.apache.commons.configuration2.Configuration;import org.apache.commons.configuration2.builder.fluent.Configurations;import org.apache.commons.configuration2.ex.ConfigurationException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.xwiki.filter.input.InputSource;import org.xwiki.skin.Resource;import org.xwiki.skin.Skin;import static org.apache.commons.lang3.exception.ExceptionUtils.getRootCauseMessage;/** * Common abstract class for the skins that manipulate resources. * * @version $Id$ * @since 13.8RC1 */public abstract class AbstractResourceSkin extends AbstractSkin{ protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractResourceSkin.class); private Configuration properties; /** * Default constructor. * * @param id the skin id (for instance, {@code "flamingo"}) * @param skinManager the skin manager that instantiates this skin * @param configuration the skin internal configuration, used to access the default parent skin id * @param logger a logger used to log warning in case of error when parsin a skin's syntax */ public AbstractResourceSkin(String id, InternalSkinManager skinManager, InternalSkinConfiguration configuration, Logger logger) { super(id, skinManager, configuration, logger); } abstract AbstractResource<InputSource> createResource(String resourcePath, String resourceName); abstract URL getResourceURL(String resourcePath); @Override public String getOutputSyntaxString() { return getProperties().getString("outputSyntax"); } @Override protected Skin createParent() { Skin skin; String parentId = getProperties().getString("parent"); if (parentId != null) { if (parentId.isEmpty()) { // There is explicitly no parent (make sure to not fallback on default parent skin) skin = VOID; } else { skin = this.skinManager.getSkin(parentId); } } else { skin = null; } return skin; } @Override public Resource<?> getLocalResource(String resourceName) { String resourcePath = getSkinResourcePath(resourceName); if (resourcePath != null && getResourceURL(resourcePath) != null) { return createResource(resourcePath, resourceName); } return null; } protected String getPropertiesPath() { return getSkinFolder() + "skin.properties"; } protected String getSkinFolder() { return "skins/" + this.id + '/'; } protected Configuration getProperties() { if (this.properties == null) { URL url = getResourceURL(getPropertiesPath()); if (url != null) { try { this.properties = new Configurations().properties(url); } catch (ConfigurationException e) { LOGGER.error("Failed to load skin [{}] properties file ([])", this.id, url, getRootCauseMessage(e)); this.properties = new BaseConfiguration(); } } else { LOGGER.debug("No properties found for skin [{}]", this.id); this.properties = new BaseConfiguration(); } } return this.properties; } private String getSkinResourcePath(String resource) { String skinFolder = getSkinFolder(); String resourcePath = skinFolder + resource; // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') // // Prevent inclusion of templates from other directories // FIXED: // Prevent access to resources from other directories Path normalizedResource = Paths.get(resourcePath).normalize(); // Protect against directory attacks. if (!normalizedResource.startsWith(skinFolder)) { LOGGER.warn("Direct access to skin file [{}] refused. Possible break-in attempt!", normalizedResource); return null; } return resourcePath; }}
data/java/AbstractXMPPConnection.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /** * * Copyright 2009 Jive Software. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.jivesoftware.smack;import java.io.IOException;import java.io.Reader;import java.io.Writer;import java.util.ArrayList;import java.util.Collection;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.ConcurrentLinkedQueue;import java.util.concurrent.CopyOnWriteArraySet;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;import java.util.logging.Level;import java.util.logging.Logger;import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;import org.jivesoftware.smack.SmackException.AlreadyConnectedException;import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;import org.jivesoftware.smack.SmackException.NoResponseException;import org.jivesoftware.smack.SmackException.NotConnectedException;import org.jivesoftware.smack.SmackException.ConnectionException;import org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException;import org.jivesoftware.smack.SmackException.SecurityRequiredException;import org.jivesoftware.smack.XMPPException.XMPPErrorException;import org.jivesoftware.smack.compress.packet.Compress;import org.jivesoftware.smack.compression.XMPPInputOutputStream;import org.jivesoftware.smack.debugger.SmackDebugger;import org.jivesoftware.smack.filter.IQReplyFilter;import org.jivesoftware.smack.filter.StanzaFilter;import org.jivesoftware.smack.filter.StanzaIdFilter;import org.jivesoftware.smack.iqrequest.IQRequestHandler;import org.jivesoftware.smack.packet.Bind;import org.jivesoftware.smack.packet.ErrorIQ;import org.jivesoftware.smack.packet.IQ;import org.jivesoftware.smack.packet.Mechanisms;import org.jivesoftware.smack.packet.Stanza;import org.jivesoftware.smack.packet.ExtensionElement;import org.jivesoftware.smack.packet.Presence;import org.jivesoftware.smack.packet.Session;import org.jivesoftware.smack.packet.StartTls;import org.jivesoftware.smack.packet.PlainStreamElement;import org.jivesoftware.smack.packet.XMPPError;import org.jivesoftware.smack.parsing.ParsingExceptionCallback;import org.jivesoftware.smack.parsing.UnparsablePacket;import org.jivesoftware.smack.provider.ExtensionElementProvider;import org.jivesoftware.smack.provider.ProviderManager;import org.jivesoftware.smack.util.BoundedThreadPoolExecutor;import org.jivesoftware.smack.util.DNSUtil;import org.jivesoftware.smack.util.Objects;import org.jivesoftware.smack.util.PacketParserUtils;import org.jivesoftware.smack.util.ParserUtils;import org.jivesoftware.smack.util.SmackExecutorThreadFactory;import org.jivesoftware.smack.util.StringUtils;import org.jivesoftware.smack.util.dns.HostAddress;import org.jxmpp.util.XmppStringUtils;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserException;public abstract class AbstractXMPPConnection implements XMPPConnection { private static final Logger LOGGER = Logger.getLogger(AbstractXMPPConnection.class.getName()); /** * Counter to uniquely identify connections that are created. */ private final static AtomicInteger connectionCounter = new AtomicInteger(0); static { // Ensure the SmackConfiguration class is loaded by calling a method in it. SmackConfiguration.getVersion(); } /** * Get the collection of listeners that are interested in connection creation events. * * @return a collection of listeners interested on new connections. */ protected static Collection<ConnectionCreationListener> getConnectionCreationListeners() { return XMPPConnectionRegistry.getConnectionCreationListeners(); } /** * A collection of ConnectionListeners which listen for connection closing * and reconnection events. */ protected final Set<ConnectionListener> connectionListeners = new CopyOnWriteArraySet<ConnectionListener>(); /** * A collection of PacketCollectors which collects packets for a specified filter * and perform blocking and polling operations on the result queue. * <p> * We use a ConcurrentLinkedQueue here, because its Iterator is weakly * consistent and we want {@link #invokePacketCollectors(Stanza)} for-each * loop to be lock free. As drawback, removing a PacketCollector is O(n). * The alternative would be a synchronized HashSet, but this would mean a * synchronized block around every usage of <code>collectors</code>. * </p> */ private final Collection<PacketCollector> collectors = new ConcurrentLinkedQueue<PacketCollector>(); /** * List of PacketListeners that will be notified synchronously when a new stanza(/packet) was received. */ private final Map<StanzaListener, ListenerWrapper> syncRecvListeners = new LinkedHashMap<>(); /** * List of PacketListeners that will be notified asynchronously when a new stanza(/packet) was received. */ private final Map<StanzaListener, ListenerWrapper> asyncRecvListeners = new LinkedHashMap<>(); /** * List of PacketListeners that will be notified when a new stanza(/packet) was sent. */ private final Map<StanzaListener, ListenerWrapper> sendListeners = new HashMap<StanzaListener, ListenerWrapper>(); /** * List of PacketListeners that will be notified when a new stanza(/packet) is about to be * sent to the server. These interceptors may modify the stanza(/packet) before it is being * actually sent to the server. */ private final Map<StanzaListener, InterceptorWrapper> interceptors = new HashMap<StanzaListener, InterceptorWrapper>(); protected final Lock connectionLock = new ReentrantLock(); protected final Map<String, ExtensionElement> streamFeatures = new HashMap<String, ExtensionElement>(); /** * The full JID of the authenticated user, as returned by the resource binding response of the server. * <p> * It is important that we don't infer the user from the login() arguments and the configurations service name, as, * for example, when SASL External is used, the username is not given to login but taken from the 'external' * certificate. * </p> */ protected String user; protected boolean connected = false; /** * The stream ID, see RFC 6120 § 4.7.3 */ protected String streamId; /** * */ private long packetReplyTimeout = SmackConfiguration.getDefaultPacketReplyTimeout(); /** * The SmackDebugger allows to log and debug XML traffic. */ protected SmackDebugger debugger = null; /** * The Reader which is used for the debugger. */ protected Reader reader; /** * The Writer which is used for the debugger. */ protected Writer writer; /** * Set to success if the last features stanza from the server has been parsed. A XMPP connection * handshake can invoke multiple features stanzas, e.g. when TLS is activated a second feature * stanza is send by the server. This is set to true once the last feature stanza has been * parsed. */ protected final SynchronizationPoint<Exception> lastFeaturesReceived = new SynchronizationPoint<Exception>( AbstractXMPPConnection.this); /** * Set to success if the sasl feature has been received. */ protected final SynchronizationPoint<SmackException> saslFeatureReceived = new SynchronizationPoint<SmackException>( AbstractXMPPConnection.this); /** * The SASLAuthentication manager that is responsible for authenticating with the server. */ protected SASLAuthentication saslAuthentication = new SASLAuthentication(this); /** * A number to uniquely identify connections that are created. This is distinct from the * connection ID, which is a value sent by the server once a connection is made. */ protected final int connectionCounterValue = connectionCounter.getAndIncrement(); /** * Holds the initial configuration used while creating the connection. */ protected final ConnectionConfiguration config; /** * Defines how the from attribute of outgoing stanzas should be handled. */ private FromMode fromMode = FromMode.OMITTED; protected XMPPInputOutputStream compressionHandler; private ParsingExceptionCallback parsingExceptionCallback = SmackConfiguration.getDefaultParsingExceptionCallback(); /** * ExecutorService used to invoke the PacketListeners on newly arrived and parsed stanzas. It is * important that we use a <b>single threaded ExecutorService</b> in order to guarantee that the * PacketListeners are invoked in the same order the stanzas arrived. */ private final BoundedThreadPoolExecutor executorService = new BoundedThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, 100, new SmackExecutorThreadFactory(connectionCounterValue, "Incoming Processor")); /** * This scheduled thread pool executor is used to remove pending callbacks. */ private final ScheduledExecutorService removeCallbacksService = Executors.newSingleThreadScheduledExecutor( new SmackExecutorThreadFactory(connectionCounterValue, "Remove Callbacks")); /** * A cached thread pool executor service with custom thread factory to set meaningful names on the threads and set * them 'daemon'. */ private final ExecutorService cachedExecutorService = Executors.newCachedThreadPool( // @formatter:off new SmackExecutorThreadFactory( // threadFactory connectionCounterValue, "Cached Executor" ) // @formatter:on ); /** * A executor service used to invoke the callbacks of synchronous stanza(/packet) listeners. We use a executor service to * decouple incoming stanza processing from callback invocation. It is important that order of callback invocation * is the same as the order of the incoming stanzas. Therefore we use a <i>single</i> threaded executor service. */ private final ExecutorService singleThreadedExecutorService = Executors.newSingleThreadExecutor(new SmackExecutorThreadFactory( getConnectionCounter(), "Single Threaded Executor")); /** * The used host to establish the connection to */ protected String host; /** * The used port to establish the connection to */ protected int port; /** * Flag that indicates if the user is currently authenticated with the server. */ protected boolean authenticated = false; /** * Flag that indicates if the user was authenticated with the server when the connection * to the server was closed (abruptly or not). */ protected boolean wasAuthenticated = false; private final Map<String, IQRequestHandler> setIqRequestHandler = new HashMap<>(); private final Map<String, IQRequestHandler> getIqRequestHandler = new HashMap<>(); /** * Create a new XMPPConnection to an XMPP server. * * @param configuration The configuration which is used to establish the connection. */ protected AbstractXMPPConnection(ConnectionConfiguration configuration) { config = configuration; } /** * Get the connection configuration used by this connection. * * @return the connection configuration. */ public ConnectionConfiguration getConfiguration() { return config; } @Override public String getServiceName() { if (serviceName != null) { return serviceName; } return config.getServiceName(); } @Override public String getHost() { return host; } @Override public int getPort() { return port; } @Override public abstract boolean isSecureConnection(); protected abstract void sendStanzaInternal(Stanza packet) throws NotConnectedException; @Override public abstract void send(PlainStreamElement element) throws NotConnectedException; @Override public abstract boolean isUsingCompression(); /** * Establishes a connection to the XMPP server and performs an automatic login * only if the previous connection state was logged (authenticated). It basically * creates and maintains a connection to the server. * <p> * Listeners will be preserved from a previous connection. * * @throws XMPPException if an error occurs on the XMPP protocol level. * @throws SmackException if an error occurs somewhere else besides XMPP protocol level. * @throws IOException * @throws ConnectionException with detailed information about the failed connection. * @return a reference to this object, to chain <code>connect()</code> with <code>login()</code>. */ public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException { // Check if not already connected throwAlreadyConnectedExceptionIfAppropriate(); // Reset the connection state saslAuthentication.init(); saslFeatureReceived.init(); lastFeaturesReceived.init(); streamId = null; // Perform the actual connection to the XMPP service connectInternal(); return this; } /** * Abstract method that concrete subclasses of XMPPConnection need to implement to perform their * way of XMPP connection establishment. Implementations are required to perform an automatic * login if the previous connection state was logged (authenticated). * * @throws SmackException * @throws IOException * @throws XMPPException */ protected abstract void connectInternal() throws SmackException, IOException, XMPPException; private String usedUsername, usedPassword, usedResource; /** * Logs in to the server using the strongest SASL mechanism supported by * the server. If more than the connection's default stanza(/packet) timeout elapses in each step of the * authentication process without a response from the server, a * {@link SmackException.NoResponseException} will be thrown. * <p> * Before logging in (i.e. authenticate) to the server the connection must be connected * by calling {@link #connect}. * </p> * <p> * It is possible to log in without sending an initial available presence by using * {@link ConnectionConfiguration.Builder#setSendPresence(boolean)}. * Finally, if you want to not pass a password and instead use a more advanced mechanism * while using SASL then you may be interested in using * {@link ConnectionConfiguration.Builder#setCallbackHandler(javax.security.auth.callback.CallbackHandler)}. * For more advanced login settings see {@link ConnectionConfiguration}. * </p> * * @throws XMPPException if an error occurs on the XMPP protocol level. * @throws SmackException if an error occurs somewhere else besides XMPP protocol level. * @throws IOException if an I/O error occurs during login. */ public synchronized void login() throws XMPPException, SmackException, IOException { if (isAnonymous()) { throwNotConnectedExceptionIfAppropriate("Did you call connect() before login()?"); throwAlreadyLoggedInExceptionIfAppropriate(); loginAnonymously(); } else { // The previously used username, password and resource take over precedence over the // ones from the connection configuration CharSequence username = usedUsername != null ? usedUsername : config.getUsername(); String password = usedPassword != null ? usedPassword : config.getPassword(); String resource = usedResource != null ? usedResource : config.getResource(); login(username, password, resource); } } /** * Same as {@link #login(CharSequence, String, String)}, but takes the resource from the connection * configuration. * * @param username * @param password * @throws XMPPException * @throws SmackException * @throws IOException * @see #login */ public synchronized void login(CharSequence username, String password) throws XMPPException, SmackException, IOException { login(username, password, config.getResource()); } /** * Login with the given username (authorization identity). You may omit the password if a callback handler is used. * If resource is null, then the server will generate one. * * @param username * @param password * @param resource * @throws XMPPException * @throws SmackException * @throws IOException * @see #login */ public synchronized void login(CharSequence username, String password, String resource) throws XMPPException, SmackException, IOException { if (!config.allowNullOrEmptyUsername) { StringUtils.requireNotNullOrEmpty(username, "Username must not be null or empty"); } throwNotConnectedExceptionIfAppropriate(); throwAlreadyLoggedInExceptionIfAppropriate(); usedUsername = username != null ? username.toString() : null; usedPassword = password; usedResource = resource; loginNonAnonymously(usedUsername, usedPassword, usedResource); } protected abstract void loginNonAnonymously(String username, String password, String resource) throws XMPPException, SmackException, IOException; protected abstract void loginAnonymously() throws XMPPException, SmackException, IOException; @Override public final boolean isConnected() { return connected; } @Override public final boolean isAuthenticated() { return authenticated; } @Override public final String getUser() { return user; } @Override public String getStreamId() { if (!isConnected()) { return null; } return streamId; } // TODO remove this suppression once "disable legacy session" code has been removed from Smack @SuppressWarnings("deprecation") protected void bindResourceAndEstablishSession(String resource) throws XMPPErrorException, IOException, SmackException { // Wait until either: // - the servers last features stanza has been parsed // - the timeout occurs LOGGER.finer("Waiting for last features to be received before continuing with resource binding"); lastFeaturesReceived.checkIfSuccessOrWait(); if (!hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) { // Server never offered resource binding, which is REQURIED in XMPP client and // server implementations as per RFC6120 7.2 throw new ResourceBindingNotOfferedException(); } // Resource binding, see RFC6120 7. // Note that we can not use IQReplyFilter here, since the users full JID is not yet // available. It will become available right after the resource has been successfully bound. Bind bindResource = Bind.newSet(resource); PacketCollector packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(bindResource), bindResource); Bind response = packetCollector.nextResultOrThrow(); // Set the connections user to the result of resource binding. It is important that we don't infer the user // from the login() arguments and the configurations service name, as, for example, when SASL External is used, // the username is not given to login but taken from the 'external' certificate. user = response.getJid(); serviceName = XmppStringUtils.parseDomain(user); Session.Feature sessionFeature = getFeature(Session.ELEMENT, Session.NAMESPACE); // Only bind the session if it's announced as stream feature by the server, is not optional and not disabled // For more information see http://tools.ietf.org/html/draft-cridland-xmpp-session-01 if (sessionFeature != null && !sessionFeature.isOptional() && !getConfiguration().isLegacySessionDisabled()) { Session session = new Session(); packetCollector = createPacketCollectorAndSend(new StanzaIdFilter(session), session); packetCollector.nextResultOrThrow(); } } protected void afterSuccessfulLogin(final boolean resumed) throws NotConnectedException { // Indicate that we're now authenticated. this.authenticated = true; // If debugging is enabled, change the the debug window title to include the // name we are now logged-in as. // If DEBUG was set to true AFTER the connection was created the debugger // will be null if (config.isDebuggerEnabled() && debugger != null) { debugger.userHasLogged(user); } callConnectionAuthenticatedListener(resumed); // Set presence to online. It is important that this is done after // callConnectionAuthenticatedListener(), as this call will also // eventually load the roster. And we should load the roster before we // send the initial presence. if (config.isSendPresence() && !resumed) { sendStanza(new Presence(Presence.Type.available)); } } @Override public final boolean isAnonymous() { return config.getUsername() == null && usedUsername == null && !config.allowNullOrEmptyUsername; } private String serviceName; protected List<HostAddress> hostAddresses; /** * Populates {@link #hostAddresses} with at least one host address. * * @return a list of host addresses where DNS (SRV) RR resolution failed. */ protected List<HostAddress> populateHostAddresses() { List<HostAddress> failedAddresses = new LinkedList<>(); // N.B.: Important to use config.serviceName and not AbstractXMPPConnection.serviceName if (config.host != null) { hostAddresses = new ArrayList<HostAddress>(1); HostAddress hostAddress; hostAddress = new HostAddress(config.host, config.port); hostAddresses.add(hostAddress); } else { hostAddresses = DNSUtil.resolveXMPPDomain(config.serviceName, failedAddresses); } // If we reach this, then hostAddresses *must not* be empty, i.e. there is at least one host added, either the // config.host one or the host representing the service name by DNSUtil assert(!hostAddresses.isEmpty()); return failedAddresses; } protected Lock getConnectionLock() { return connectionLock; } protected void throwNotConnectedExceptionIfAppropriate() throws NotConnectedException { throwNotConnectedExceptionIfAppropriate(null); } protected void throwNotConnectedExceptionIfAppropriate(String optionalHint) throws NotConnectedException { if (!isConnected()) { throw new NotConnectedException(optionalHint); } } protected void throwAlreadyConnectedExceptionIfAppropriate() throws AlreadyConnectedException { if (isConnected()) { throw new AlreadyConnectedException(); } } protected void throwAlreadyLoggedInExceptionIfAppropriate() throws AlreadyLoggedInException { if (isAuthenticated()) { throw new AlreadyLoggedInException(); } } @Deprecated @Override public void sendPacket(Stanza packet) throws NotConnectedException { sendStanza(packet); } @Override public void sendStanza(Stanza packet) throws NotConnectedException { Objects.requireNonNull(packet, "Packet must not be null"); throwNotConnectedExceptionIfAppropriate(); switch (fromMode) { case OMITTED: packet.setFrom(null); break; case USER: packet.setFrom(getUser()); break; case UNCHANGED: default: break; } // Invoke interceptors for the new packet that is about to be sent. Interceptors may modify // the content of the packet. firePacketInterceptors(packet); sendStanzaInternal(packet); } /** * Returns the SASLAuthentication manager that is responsible for authenticating with * the server. * * @return the SASLAuthentication manager that is responsible for authenticating with * the server. */ protected SASLAuthentication getSASLAuthentication() { return saslAuthentication; } /** * Closes the connection by setting presence to unavailable then closing the connection to * the XMPP server. The XMPPConnection can still be used for connecting to the server * again. * */ public void disconnect() { try { disconnect(new Presence(Presence.Type.unavailable)); } catch (NotConnectedException e) { LOGGER.log(Level.FINEST, "Connection is already disconnected", e); } } /** * Closes the connection. A custom unavailable presence is sent to the server, followed * by closing the stream. The XMPPConnection can still be used for connecting to the server * again. A custom unavailable presence is useful for communicating offline presence * information such as "On vacation". Typically, just the status text of the presence * stanza(/packet) is set with online information, but most XMPP servers will deliver the full * presence stanza(/packet) with whatever data is set. * * @param unavailablePresence the presence stanza(/packet) to send during shutdown. * @throws NotConnectedException */ public synchronized void disconnect(Presence unavailablePresence) throws NotConnectedException { sendStanza(unavailablePresence); shutdown(); callConnectionClosedListener(); } /** * Shuts the current connection down. */ protected abstract void shutdown(); @Override public void addConnectionListener(ConnectionListener connectionListener) { if (connectionListener == null) { return; } connectionListeners.add(connectionListener); } @Override public void removeConnectionListener(ConnectionListener connectionListener) { connectionListeners.remove(connectionListener); } @Override public PacketCollector createPacketCollectorAndSend(IQ packet) throws NotConnectedException { StanzaFilter packetFilter = new IQReplyFilter(packet, this); // Create the packet collector before sending the packet PacketCollector packetCollector = createPacketCollectorAndSend(packetFilter, packet); return packetCollector; } @Override public PacketCollector createPacketCollectorAndSend(StanzaFilter packetFilter, Stanza packet) throws NotConnectedException { // Create the packet collector before sending the packet PacketCollector packetCollector = createPacketCollector(packetFilter); try { // Now we can send the packet as the collector has been created sendStanza(packet); } catch (NotConnectedException | RuntimeException e) { packetCollector.cancel(); throw e; } return packetCollector; } @Override public PacketCollector createPacketCollector(StanzaFilter packetFilter) { PacketCollector.Configuration configuration = PacketCollector.newConfiguration().setStanzaFilter(packetFilter); return createPacketCollector(configuration); } @Override public PacketCollector createPacketCollector(PacketCollector.Configuration configuration) { PacketCollector collector = new PacketCollector(this, configuration); // Add the collector to the list of active collectors. collectors.add(collector); return collector; } @Override public void removePacketCollector(PacketCollector collector) { collectors.remove(collector); } @Override @Deprecated public void addPacketListener(StanzaListener packetListener, StanzaFilter packetFilter) { addAsyncStanzaListener(packetListener, packetFilter); } @Override @Deprecated public boolean removePacketListener(StanzaListener packetListener) { return removeAsyncStanzaListener(packetListener); } @Override public void addSyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) { if (packetListener == null) { throw new NullPointerException("Packet listener is null."); } ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter); synchronized (syncRecvListeners) { syncRecvListeners.put(packetListener, wrapper); } } @Override public boolean removeSyncStanzaListener(StanzaListener packetListener) { synchronized (syncRecvListeners) { return syncRecvListeners.remove(packetListener) != null; } } @Override public void addAsyncStanzaListener(StanzaListener packetListener, StanzaFilter packetFilter) { if (packetListener == null) { throw new NullPointerException("Packet listener is null."); } ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter); synchronized (asyncRecvListeners) { asyncRecvListeners.put(packetListener, wrapper); } } @Override public boolean removeAsyncStanzaListener(StanzaListener packetListener) { synchronized (asyncRecvListeners) { return asyncRecvListeners.remove(packetListener) != null; } } @Override public void addPacketSendingListener(StanzaListener packetListener, StanzaFilter packetFilter) { if (packetListener == null) { throw new NullPointerException("Packet listener is null."); } ListenerWrapper wrapper = new ListenerWrapper(packetListener, packetFilter); synchronized (sendListeners) { sendListeners.put(packetListener, wrapper); } } @Override public void removePacketSendingListener(StanzaListener packetListener) { synchronized (sendListeners) { sendListeners.remove(packetListener); } } /** * Process all stanza(/packet) listeners for sending packets. * <p> * Compared to {@link #firePacketInterceptors(Stanza)}, the listeners will be invoked in a new thread. * </p> * * @param packet the stanza(/packet) to process. */ @SuppressWarnings("javadoc") protected void firePacketSendingListeners(final Stanza packet) { final List<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>(); synchronized (sendListeners) { for (ListenerWrapper listenerWrapper : sendListeners.values()) { if (listenerWrapper.filterMatches(packet)) { listenersToNotify.add(listenerWrapper.getListener()); } } } if (listenersToNotify.isEmpty()) { return; } // Notify in a new thread, because we can asyncGo(new Runnable() { @Override public void run() { for (StanzaListener listener : listenersToNotify) { try { listener.processPacket(packet); } catch (Exception e) { LOGGER.log(Level.WARNING, "Sending listener threw exception", e); continue; } } }}); } @Override public void addPacketInterceptor(StanzaListener packetInterceptor, StanzaFilter packetFilter) { if (packetInterceptor == null) { throw new NullPointerException("Packet interceptor is null."); } InterceptorWrapper interceptorWrapper = new InterceptorWrapper(packetInterceptor, packetFilter); synchronized (interceptors) { interceptors.put(packetInterceptor, interceptorWrapper); } } @Override public void removePacketInterceptor(StanzaListener packetInterceptor) { synchronized (interceptors) { interceptors.remove(packetInterceptor); } } /** * Process interceptors. Interceptors may modify the stanza(/packet) that is about to be sent. * Since the thread that requested to send the stanza(/packet) will invoke all interceptors, it * is important that interceptors perform their work as soon as possible so that the * thread does not remain blocked for a long period. * * @param packet the stanza(/packet) that is going to be sent to the server */ private void firePacketInterceptors(Stanza packet) { List<StanzaListener> interceptorsToInvoke = new LinkedList<StanzaListener>(); synchronized (interceptors) { for (InterceptorWrapper interceptorWrapper : interceptors.values()) { if (interceptorWrapper.filterMatches(packet)) { interceptorsToInvoke.add(interceptorWrapper.getInterceptor()); } } } for (StanzaListener interceptor : interceptorsToInvoke) { try { interceptor.processPacket(packet); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Packet interceptor threw exception", e); } } } /** * Initialize the {@link #debugger}. You can specify a customized {@link SmackDebugger} * by setup the system property <code>smack.debuggerClass</code> to the implementation. * * @throws IllegalStateException if the reader or writer isn't yet initialized. * @throws IllegalArgumentException if the SmackDebugger can't be loaded. */ protected void initDebugger() { if (reader == null || writer == null) { throw new NullPointerException("Reader or writer isn't initialized."); } // If debugging is enabled, we open a window and write out all network traffic. if (config.isDebuggerEnabled()) { if (debugger == null) { debugger = SmackConfiguration.createDebugger(this, writer, reader); } if (debugger == null) { LOGGER.severe("Debugging enabled but could not find debugger class"); } else { // Obtain new reader and writer from the existing debugger reader = debugger.newConnectionReader(reader); writer = debugger.newConnectionWriter(writer); } } } @Override public long getPacketReplyTimeout() { return packetReplyTimeout; } @Override public void setPacketReplyTimeout(long timeout) { packetReplyTimeout = timeout; } private static boolean replyToUnknownIqDefault = true; /** * Set the default value used to determine if new connection will reply to unknown IQ requests. The pre-configured * default is 'true'. * * @param replyToUnkownIqDefault * @see #setReplyToUnknownIq(boolean) */ public static void setReplyToUnknownIqDefault(boolean replyToUnkownIqDefault) { AbstractXMPPConnection.replyToUnknownIqDefault = replyToUnkownIqDefault; } private boolean replyToUnkownIq = replyToUnknownIqDefault; /** * Set if Smack will automatically send * {@link org.jivesoftware.smack.packet.XMPPError.Condition#feature_not_implemented} when a request IQ without a * registered {@link IQRequestHandler} is received. * * @param replyToUnknownIq */ public void setReplyToUnknownIq(boolean replyToUnknownIq) { this.replyToUnkownIq = replyToUnknownIq; } protected void parseAndProcessStanza(XmlPullParser parser) throws Exception { ParserUtils.assertAtStartTag(parser); int parserDepth = parser.getDepth(); Stanza stanza = null; try { stanza = PacketParserUtils.parseStanza(parser); } catch (Exception e) { CharSequence content = PacketParserUtils.parseContentDepth(parser, parserDepth); UnparsablePacket message = new UnparsablePacket(content, e); ParsingExceptionCallback callback = getParsingExceptionCallback(); if (callback != null) { callback.handleUnparsablePacket(message); } } ParserUtils.assertAtEndTag(parser); if (stanza != null) { processPacket(stanza); } } /** * Processes a stanza(/packet) after it's been fully parsed by looping through the installed * stanza(/packet) collectors and listeners and letting them examine the stanza(/packet) to see if * they are a match with the filter. * * @param packet the stanza(/packet) to process. * @throws InterruptedException */ protected void processPacket(Stanza packet) throws InterruptedException { assert(packet != null); lastStanzaReceived = System.currentTimeMillis(); // Deliver the incoming packet to listeners. executorService.executeBlocking(new ListenerNotification(packet)); } /** * A runnable to notify all listeners and stanza(/packet) collectors of a packet. */ private class ListenerNotification implements Runnable { private final Stanza packet; public ListenerNotification(Stanza packet) { this.packet = packet; } public void run() { invokePacketCollectorsAndNotifyRecvListeners(packet); } } /** * Invoke {@link PacketCollector#processPacket(Stanza)} for every * PacketCollector with the given packet. Also notify the receive listeners with a matching stanza(/packet) filter about the packet. * * @param packet the stanza(/packet) to notify the PacketCollectors and receive listeners about. */ protected void invokePacketCollectorsAndNotifyRecvListeners(final Stanza packet) { if (packet instanceof IQ) { final IQ iq = (IQ) packet; final IQ.Type type = iq.getType(); switch (type) { case set: case get: final String key = XmppStringUtils.generateKey(iq.getChildElementName(), iq.getChildElementNamespace()); IQRequestHandler iqRequestHandler = null; switch (type) { case set: synchronized (setIqRequestHandler) { iqRequestHandler = setIqRequestHandler.get(key); } break; case get: synchronized (getIqRequestHandler) { iqRequestHandler = getIqRequestHandler.get(key); } break; default: throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'"); } if (iqRequestHandler == null) { if (!replyToUnkownIq) { return; } // If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an // IQ of type "error" with code 501 ("feature-not-implemented") ErrorIQ errorIQ = IQ.createErrorResponse(iq, new XMPPError( XMPPError.Condition.feature_not_implemented)); try { sendStanza(errorIQ); } catch (NotConnectedException e) { LOGGER.log(Level.WARNING, "NotConnectedException while sending error IQ to unkown IQ request", e); } } else { ExecutorService executorService = null; switch (iqRequestHandler.getMode()) { case sync: executorService = singleThreadedExecutorService; break; case async: executorService = cachedExecutorService; break; } final IQRequestHandler finalIqRequestHandler = iqRequestHandler; executorService.execute(new Runnable() { @Override public void run() { IQ response = finalIqRequestHandler.handleIQRequest(iq); if (response == null) { // It is not ideal if the IQ request handler does not return an IQ response, because RFC // 6120 § 8.1.2 does specify that a response is mandatory. But some APIs, mostly the // file transfer one, does not always return a result, so we need to handle this case. // Also sometimes a request handler may decide that it's better to not send a response, // e.g. to avoid presence leaks. return; } try { sendStanza(response); } catch (NotConnectedException e) { LOGGER.log(Level.WARNING, "NotConnectedException while sending response to IQ request", e); } } }); // The following returns makes it impossible for packet listeners and collectors to // filter for IQ request stanzas, i.e. IQs of type 'set' or 'get'. This is the // desired behavior. return; } break; default: break; } } // First handle the async recv listeners. Note that this code is very similar to what follows a few lines below, // the only difference is that asyncRecvListeners is used here and that the packet listeners are started in // their own thread. final Collection<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>(); synchronized (asyncRecvListeners) { for (ListenerWrapper listenerWrapper : asyncRecvListeners.values()) { if (listenerWrapper.filterMatches(packet)) { listenersToNotify.add(listenerWrapper.getListener()); } } } for (final StanzaListener listener : listenersToNotify) { asyncGo(new Runnable() { @Override public void run() { try { listener.processPacket(packet); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Exception in async packet listener", e); } } }); } // Loop through all collectors and notify the appropriate ones. for (PacketCollector collector: collectors) { collector.processPacket(packet); } // Notify the receive listeners interested in the packet listenersToNotify.clear(); synchronized (syncRecvListeners) { for (ListenerWrapper listenerWrapper : syncRecvListeners.values()) { if (listenerWrapper.filterMatches(packet)) { listenersToNotify.add(listenerWrapper.getListener()); } } } // Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single // threaded executor service and therefore keeps the order. singleThreadedExecutorService.execute(new Runnable() { @Override public void run() { for (StanzaListener listener : listenersToNotify) { try { listener.processPacket(packet); } catch(NotConnectedException e) { LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e); break; } catch (Exception e) { LOGGER.log(Level.SEVERE, "Exception in packet listener", e); } } } }); } /** * Sets whether the connection has already logged in the server. This method assures that the * {@link #wasAuthenticated} flag is never reset once it has ever been set. * */ protected void setWasAuthenticated() { // Never reset the flag if the connection has ever been authenticated if (!wasAuthenticated) { wasAuthenticated = authenticated; } } protected void callConnectionConnectedListener() { for (ConnectionListener listener : connectionListeners) { listener.connected(this); } } protected void callConnectionAuthenticatedListener(boolean resumed) { for (ConnectionListener listener : connectionListeners) { try { listener.authenticated(this, resumed); } catch (Exception e) { // Catch and print any exception so we can recover // from a faulty listener and finish the shutdown process LOGGER.log(Level.SEVERE, "Exception in authenticated listener", e); } } } void callConnectionClosedListener() { for (ConnectionListener listener : connectionListeners) { try { listener.connectionClosed(); } catch (Exception e) { // Catch and print any exception so we can recover // from a faulty listener and finish the shutdown process LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e); } } } protected void callConnectionClosedOnErrorListener(Exception e) { LOGGER.log(Level.WARNING, "Connection closed with error", e); for (ConnectionListener listener : connectionListeners) { try { listener.connectionClosedOnError(e); } catch (Exception e2) { // Catch and print any exception so we can recover // from a faulty listener LOGGER.log(Level.SEVERE, "Error in listener while closing connection", e2); } } } /** * Sends a notification indicating that the connection was reconnected successfully. */ protected void notifyReconnection() { // Notify connection listeners of the reconnection. for (ConnectionListener listener : connectionListeners) { try { listener.reconnectionSuccessful(); } catch (Exception e) { // Catch and print any exception so we can recover // from a faulty listener LOGGER.log(Level.WARNING, "notifyReconnection()", e); } } } /** * A wrapper class to associate a stanza(/packet) filter with a listener. */ protected static class ListenerWrapper { private final StanzaListener packetListener; private final StanzaFilter packetFilter; /** * Create a class which associates a stanza(/packet) filter with a listener. * * @param packetListener the stanza(/packet) listener. * @param packetFilter the associated filter or null if it listen for all packets. */ public ListenerWrapper(StanzaListener packetListener, StanzaFilter packetFilter) { this.packetListener = packetListener; this.packetFilter = packetFilter; } public boolean filterMatches(Stanza packet) { return packetFilter == null || packetFilter.accept(packet); } public StanzaListener getListener() { return packetListener; } } /** * A wrapper class to associate a stanza(/packet) filter with an interceptor. */ protected static class InterceptorWrapper { private final StanzaListener packetInterceptor; private final StanzaFilter packetFilter; /** * Create a class which associates a stanza(/packet) filter with an interceptor. * * @param packetInterceptor the interceptor. * @param packetFilter the associated filter or null if it intercepts all packets. */ public InterceptorWrapper(StanzaListener packetInterceptor, StanzaFilter packetFilter) { this.packetInterceptor = packetInterceptor; this.packetFilter = packetFilter; } public boolean filterMatches(Stanza packet) { return packetFilter == null || packetFilter.accept(packet); } public StanzaListener getInterceptor() { return packetInterceptor; } } @Override public int getConnectionCounter() { return connectionCounterValue; } @Override public void setFromMode(FromMode fromMode) { this.fromMode = fromMode; } @Override public FromMode getFromMode() { return this.fromMode; } @Override protected void finalize() throws Throwable { LOGGER.fine("finalizing XMPPConnection ( " + getConnectionCounter() + "): Shutting down executor services"); try { // It's usually not a good idea to rely on finalize. But this is the easiest way to // avoid the "Smack Listener Processor" leaking. The thread(s) of the executor have a // reference to their ExecutorService which prevents the ExecutorService from being // gc'ed. It is possible that the XMPPConnection instance is gc'ed while the // listenerExecutor ExecutorService call not be gc'ed until it got shut down. executorService.shutdownNow(); cachedExecutorService.shutdown(); removeCallbacksService.shutdownNow(); singleThreadedExecutorService.shutdownNow(); } catch (Throwable t) { LOGGER.log(Level.WARNING, "finalize() threw trhowable", t); } finally { super.finalize(); } } protected final void parseFeatures(XmlPullParser parser) throws XmlPullParserException, IOException, SmackException { streamFeatures.clear(); final int initialDepth = parser.getDepth(); while (true) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG && parser.getDepth() == initialDepth + 1) { ExtensionElement streamFeature = null; String name = parser.getName(); String namespace = parser.getNamespace(); switch (name) { case StartTls.ELEMENT: streamFeature = PacketParserUtils.parseStartTlsFeature(parser); break; case Mechanisms.ELEMENT: streamFeature = new Mechanisms(PacketParserUtils.parseMechanisms(parser)); break; case Bind.ELEMENT: streamFeature = Bind.Feature.INSTANCE; break; case Session.ELEMENT: streamFeature = PacketParserUtils.parseSessionFeature(parser); break; case Compress.Feature.ELEMENT: streamFeature = PacketParserUtils.parseCompressionFeature(parser); break; default: ExtensionElementProvider<ExtensionElement> provider = ProviderManager.getStreamFeatureProvider(name, namespace); if (provider != null) { streamFeature = provider.parse(parser); } break; } if (streamFeature != null) { addStreamFeature(streamFeature); } } else if (eventType == XmlPullParser.END_TAG && parser.getDepth() == initialDepth) { break; } } if (hasFeature(Mechanisms.ELEMENT, Mechanisms.NAMESPACE)) { // Only proceed with SASL auth if TLS is disabled or if the server doesn't announce it if (!hasFeature(StartTls.ELEMENT, StartTls.NAMESPACE) || config.getSecurityMode() == SecurityMode.disabled) { saslFeatureReceived.reportSuccess(); } } // If the server reported the bind feature then we are that that we did SASL and maybe // STARTTLS. We can then report that the last 'stream:features' have been parsed if (hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) { if (!hasFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE) || !config.isCompressionEnabled()) { // This was was last features from the server is either it did not contain // compression or if we disabled it lastFeaturesReceived.reportSuccess(); } } afterFeaturesReceived(); } protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException { // Default implementation does nothing } @SuppressWarnings("unchecked") @Override public <F extends ExtensionElement> F getFeature(String element, String namespace) { return (F) streamFeatures.get(XmppStringUtils.generateKey(element, namespace)); } @Override public boolean hasFeature(String element, String namespace) { return getFeature(element, namespace) != null; } private void addStreamFeature(ExtensionElement feature) { String key = XmppStringUtils.generateKey(feature.getElementName(), feature.getNamespace()); streamFeatures.put(key, feature); } @Override public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter, StanzaListener callback) throws NotConnectedException { sendStanzaWithResponseCallback(stanza, replyFilter, callback, null); } @Override public void sendStanzaWithResponseCallback(Stanza stanza, StanzaFilter replyFilter, StanzaListener callback, ExceptionCallback exceptionCallback) throws NotConnectedException { sendStanzaWithResponseCallback(stanza, replyFilter, callback, exceptionCallback, getPacketReplyTimeout()); } @Override public void sendStanzaWithResponseCallback(Stanza stanza, final StanzaFilter replyFilter, final StanzaListener callback, final ExceptionCallback exceptionCallback, long timeout) throws NotConnectedException { Objects.requireNonNull(stanza, "stanza must not be null"); // While Smack allows to add PacketListeners with a PacketFilter value of 'null', we // disallow it here in the async API as it makes no sense Objects.requireNonNull(replyFilter, "replyFilter must not be null"); Objects.requireNonNull(callback, "callback must not be null"); final StanzaListener packetListener = new StanzaListener() { @Override public void processPacket(Stanza packet) throws NotConnectedException { try { XMPPErrorException.ifHasErrorThenThrow(packet); callback.processPacket(packet); } catch (XMPPErrorException e) { if (exceptionCallback != null) { exceptionCallback.processException(e); } } finally { removeAsyncStanzaListener(this); } } }; removeCallbacksService.schedule(new Runnable() { @Override public void run() { boolean removed = removeAsyncStanzaListener(packetListener); // If the packetListener got removed, then it was never run and // we never received a response, inform the exception callback if (removed && exceptionCallback != null) { exceptionCallback.processException(NoResponseException.newWith(AbstractXMPPConnection.this, replyFilter)); } } }, timeout, TimeUnit.MILLISECONDS); addAsyncStanzaListener(packetListener, replyFilter); sendStanza(stanza); } @Override public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback) throws NotConnectedException { sendIqWithResponseCallback(iqRequest, callback, null); } @Override public void sendIqWithResponseCallback(IQ iqRequest, StanzaListener callback, ExceptionCallback exceptionCallback) throws NotConnectedException { sendIqWithResponseCallback(iqRequest, callback, exceptionCallback, getPacketReplyTimeout()); } @Override public void sendIqWithResponseCallback(IQ iqRequest, final StanzaListener callback, final ExceptionCallback exceptionCallback, long timeout) throws NotConnectedException { StanzaFilter replyFilter = new IQReplyFilter(iqRequest, this); sendStanzaWithResponseCallback(iqRequest, replyFilter, callback, exceptionCallback, timeout); } @Override public void addOneTimeSyncCallback(final StanzaListener callback, final StanzaFilter packetFilter) { final StanzaListener packetListener = new StanzaListener() { @Override public void processPacket(Stanza packet) throws NotConnectedException { try { callback.processPacket(packet); } finally { removeSyncStanzaListener(this); } } }; addSyncStanzaListener(packetListener, packetFilter); removeCallbacksService.schedule(new Runnable() { @Override public void run() { removeSyncStanzaListener(packetListener); } }, getPacketReplyTimeout(), TimeUnit.MILLISECONDS); } @Override public IQRequestHandler registerIQRequestHandler(final IQRequestHandler iqRequestHandler) { final String key = XmppStringUtils.generateKey(iqRequestHandler.getElement(), iqRequestHandler.getNamespace()); switch (iqRequestHandler.getType()) { case set: synchronized (setIqRequestHandler) { return setIqRequestHandler.put(key, iqRequestHandler); } case get: synchronized (getIqRequestHandler) { return getIqRequestHandler.put(key, iqRequestHandler); } default: throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed"); } } @Override public final IQRequestHandler unregisterIQRequestHandler(IQRequestHandler iqRequestHandler) { return unregisterIQRequestHandler(iqRequestHandler.getElement(), iqRequestHandler.getNamespace(), iqRequestHandler.getType()); } @Override public IQRequestHandler unregisterIQRequestHandler(String element, String namespace, IQ.Type type) { final String key = XmppStringUtils.generateKey(element, namespace); switch (type) { case set: synchronized (setIqRequestHandler) { return setIqRequestHandler.remove(key); } case get: synchronized (getIqRequestHandler) { return getIqRequestHandler.remove(key); } default: throw new IllegalArgumentException("Only IQ type of 'get' and 'set' allowed"); } } private long lastStanzaReceived; public long getLastStanzaReceived() { return lastStanzaReceived; } /** * Install a parsing exception callback, which will be invoked once an exception is encountered while parsing a * stanza * * @param callback the callback to install */ public void setParsingExceptionCallback(ParsingExceptionCallback callback) { parsingExceptionCallback = callback; } /** * Get the current active parsing exception callback. * * @return the active exception callback or null if there is none */ public ParsingExceptionCallback getParsingExceptionCallback() { return parsingExceptionCallback; } protected final void asyncGo(Runnable runnable) { cachedExecutorService.execute(runnable); } protected final ScheduledFuture<?> schedule(Runnable runnable, long delay, TimeUnit unit) { return removeCallbacksService.schedule(runnable, delay, unit); }}
data/java/AdminAction.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */package com.xpn.xwiki.web;import javax.inject.Named;import javax.inject.Singleton;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.xwiki.component.annotation.Component;import com.xpn.xwiki.XWikiContext;import com.xpn.xwiki.XWikiException;import com.xpn.xwiki.doc.XWikiDocument;import com.xpn.xwiki.doc.XWikiLock;/** * Administration xwiki action. * * @version $Id$ */@Component@Named("admin")@Singletonpublic class AdminAction extends XWikiAction{ /** The logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(AdminAction.class); /** * Default constructor. */ public AdminAction() { this.waitForXWikiInitialization = false; } @Override protected Class<? extends XWikiForm> getFormClass() { return EditForm.class; } @Override public String render(XWikiContext context) throws XWikiException { XWikiRequest request = context.getRequest(); String content = request.getParameter("content"); XWikiDocument doc = context.getDoc(); XWikiForm form = context.getForm(); synchronized (doc) { XWikiDocument tdoc = (XWikiDocument) context.get("tdoc"); EditForm peform = (EditForm) form; String parent = peform.getParent(); if (parent != null) { doc.setParent(parent); } String creator = peform.getCreator(); if (creator != null) { doc.setCreator(creator); } String defaultTemplate = peform.getDefaultTemplate(); if (defaultTemplate != null) { doc.setDefaultTemplate(defaultTemplate); } String defaultLanguage = peform.getDefaultLanguage(); if ((defaultLanguage != null) && !defaultLanguage.equals("")) { doc.setDefaultLanguage(defaultLanguage); } if (doc.getDefaultLanguage().equals("")) { doc.setDefaultLanguage(context.getWiki().getLanguagePreference(context)); } String language = context.getWiki().getLanguagePreference(context); String languagefromrequest = context.getRequest().getParameter("language"); String languagetoedit = ((languagefromrequest == null) || (languagefromrequest.equals(""))) ? language : languagefromrequest; if ((languagetoedit == null) || (languagetoedit.equals("default"))) { languagetoedit = ""; } if (doc.isNew() || (doc.getDefaultLanguage().equals(languagetoedit))) { languagetoedit = ""; } if (languagetoedit.equals("")) { // In this case the created document is going to be the default document tdoc = doc; context.put("tdoc", doc); if (doc.isNew()) { doc.setDefaultLanguage(language); doc.setLanguage(""); } } else { // If the translated doc object is the same as the doc object // this means the translated doc did not exists so we need to create it if ((tdoc == doc)) { tdoc = new XWikiDocument(doc.getDocumentReference()); tdoc.setLanguage(languagetoedit); tdoc.setContent(doc.getContent()); tdoc.setSyntax(doc.getSyntax()); tdoc.setAuthor(context.getUser()); tdoc.setStore(doc.getStore()); context.put("tdoc", tdoc); } } XWikiDocument tdoc2 = tdoc.clone(); if (content != null && !content.isEmpty()) { tdoc2.setContent(content); } context.put("tdoc", tdoc2); try { // BUG: CWE-862 Missing Authorization // tdoc2.readFromTemplate(peform, context); // FIXED: readFromTemplate(tdoc2, peform.getTemplate(), context); } catch (XWikiException e) { if (e.getCode() == XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY) { context.put("exception", e); return "docalreadyexists"; } } /* Setup a lock */ try { XWikiLock lock = tdoc.getLock(context); if ((lock == null) || (lock.getUserName().equals(context.getUser())) || (peform.isLockForce())) { tdoc.setLock(context.getUser(), context); } } catch (Exception e) { // Lock should never make XWiki fail // But we should log any related information LOGGER.error("Exception while setting up lock", e); } } return "admin"; }}
data/java/AllTestsJunit4.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /*** OLAT - Online Learning and Training<br>* http://www.olat.org* <p>* Licensed under the Apache License, Version 2.0 (the "License"); <br>* you may not use this file except in compliance with the License.<br>* You may obtain a copy of the License at* <p>* http://www.apache.org/licenses/LICENSE-2.0* <p>* Unless required by applicable law or agreed to in writing,<br>* software distributed under the License is distributed on an "AS IS" BASIS, <br>* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>* See the License for the specific language governing permissions and <br>* limitations under the License.* <p>* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br>* University of Zurich, Switzerland.* <hr>* <a href="http://www.openolat.org">* OpenOLAT - Online Learning and Training</a><br>* This file has been modified by the OpenOLAT community. Changes are licensed* under the Apache 2.0 license as the original file.* <p>*/package org.olat.test;/** * Description:<br> * JUnit suite runner * There are basically three types of tests: *** Tests that extend from the olatTestCase (testcase loads a full olat before running the tests -- very slow and is an integration test) *** Tests that load their own little spring context with @ContextConfiguration (that's how it should be done) *** Tests that do not need any Spring context * As tests with @ContextConfiguration can taint the context from olattestcase they must be placed on the end of the list! * <P> * Initial Date: 15.02.2010 <br> * @author guido */import org.junit.runner.RunWith;import org.junit.runners.Suite;@RunWith(Suite.class)@Suite.SuiteClasses({ org.olat.core.util.i18n.I18nTest.class, // org.olat.core.util.mail.MailTest.class, // redisabled since mails are sent despite the fact that the whitelist is enabled org.olat.core.gui.components.table.MultiSelectColumnDescriptorTest.class, org.olat.core.gui.components.table.TableEventTest.class, org.olat.core.gui.components.table.TableMultiSelectEventTest.class, org.olat.core.gui.components.table.SorterTest.class, org.olat.core.commons.chiefcontrollers.ChiefControllerMessageEventTest.class, org.olat.core.util.vfs.VFSTest.class, org.olat.core.util.vfs.VFSManagerTest.class, org.olat.core.util.filter.impl.XSSFilterParamTest.class, org.olat.core.util.filter.impl.AddBaseURLToMediaRelativeURLFilterTest.class, org.olat.core.util.filter.impl.SimpleHTMLTagsFilterTest.class, org.olat.core.util.filter.impl.HtmlFilterTest.class, org.olat.core.util.filter.impl.HtmlMathScannerTest.class, org.olat.core.util.filter.impl.ConditionalHtmlCommentsFilterTest.class, org.olat.core.util.filter.impl.XMLValidCharacterFilterTest.class, org.olat.core.util.filter.impl.XMLValidEntityFilterTest.class, org.olat.core.helpers.SettingsTest.class, org.olat.core.util.coordinate.LockEntryTest.class, org.olat.modules.iq.DBPersistentLockManagerTest.class, org.olat.core.util.StringHelperTest.class, org.olat.core.util.FileUtilsTest.class, org.olat.core.util.FileNameSuffixFilterTest.class, org.olat.core.util.FormatterTest.class, org.olat.core.util.FormatLatexFormulasTest.class, org.olat.core.util.FormatterHourAndSecondsTest.class, org.olat.core.util.EncoderTest.class, org.olat.core.util.SimpleHtmlParserTest.class, org.olat.core.util.IPUtilsTest.class, org.olat.core.util.IPUtilsValidRangeTest.class, // BUG: CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') // // FIXED: org.olat.core.util.ZipUtilTest.class, org.olat.core.util.ZipUtilConcatTest.class, org.olat.core.util.mail.EmailAddressValidatorTest.class, org.olat.core.util.mail.manager.MailManagerTest.class, org.olat.core.util.mail.manager.MailUserDataManagerTest.class, org.olat.core.util.openxml.OpenXmlWorkbookTest.class, org.olat.core.util.openxml.OpenXMLDocumentTest.class, org.olat.core.util.pdf.PdfDocumentTest.class, org.olat.core.util.xml.XMLDigitalSignatureUtilTest.class, org.olat.core.util.xml.XStreamHelperTest.class, org.olat.core.configuration.EDConfigurationTest.class, org.olat.core.id.context.BusinessControlFactoryTest.class, org.olat.core.id.context.HistoryManagerTest.class, org.olat.core.id.IdentityEnvironmentTest.class, org.olat.core.gui.render.VelocityTemplateTest.class, org.olat.core.gui.control.generic.iframe.IFrameDeliveryMapperTest.class, org.olat.note.NoteTest.class, org.olat.user.UserTest.class, org.olat.user.UserPropertiesTest.class, org.olat.commons.calendar.CalendarImportTest.class, org.olat.commons.calendar.CalendarUtilsTest.class, org.olat.commons.calendar.manager.ImportedCalendarDAOTest.class, org.olat.commons.calendar.manager.ImportedToCalendarDAOTest.class, org.olat.commons.calendar.manager.ICalFileCalendarManagerTest.class, org.olat.commons.calendar.manager.CalendarUserConfigurationDAOTest.class, org.olat.commons.lifecycle.LifeCycleManagerTest.class, org.olat.commons.coordinate.cluster.jms.JMSTest.class, org.olat.commons.coordinate.cluster.lock.LockTest.class, org.olat.commons.coordinate.CoordinatorTest.class, org.olat.core.commons.modules.glossary.GlossaryItemManagerTest.class, org.olat.core.commons.services.csp.manager.CSPManagerTest.class, org.olat.core.commons.services.doceditor.manager.DocEditorIdentityServiceTest.class, org.olat.core.commons.services.doceditor.manager.AccessDAOTest.class, org.olat.core.commons.services.vfs.manager.VFSXStreamTest.class, org.olat.core.commons.services.vfs.manager.VFSMetadataDAOTest.class, org.olat.core.commons.services.vfs.manager.VFSRevisionDAOTest.class, org.olat.core.commons.services.vfs.manager.VFSStatsDAOTest.class, org.olat.core.commons.services.vfs.manager.VFSThumbnailDAOTest.class, org.olat.core.commons.services.vfs.manager.VFSRepositoryServiceTest.class, org.olat.core.commons.services.vfs.manager.VFSRepositoryModuleTest.class, org.olat.core.commons.services.vfs.manager.VFSLockManagerTest.class, org.olat.core.commons.services.vfs.manager.VFSVersioningTest.class, org.olat.core.commons.services.help.ConfluenceHelperTest.class, org.olat.core.commons.services.help.spi.ConfluenceLinkSPITest.class, org.olat.core.commons.services.license.manager.LicenseTypeActivationDAOTest.class, org.olat.core.commons.services.license.manager.LicenseTypeDAOTest.class, org.olat.core.commons.services.license.manager.ResourceLicenseDAOTest.class, org.olat.core.commons.services.webdav.WebDAVCommandsTest.class, org.olat.core.commons.services.webdav.manager.DigestAuthenticationTest.class, org.olat.core.commons.services.webdav.manager.WebDAVManagerTest.class, org.olat.core.commons.services.webdav.manager.WebDAVAuthManagerTest.class, org.olat.core.commons.services.webdav.servlets.RequestUtilsTest.class, org.olat.core.commons.services.sms.manager.MessageLogDAOTest.class, org.olat.core.commons.services.taskexecutor.manager.PersistentTaskDAOTest.class, org.olat.core.commons.services.taskexecutor.manager.TaskExecutorManagerTest.class, org.olat.core.commons.services.text.TextServiceTest.class, org.olat.group.BusinessGroupManagedFlagsTest.class, org.olat.group.test.BGRightManagerTest.class, org.olat.group.test.BGAreaManagerTest.class, org.olat.group.test.BusinessGroupServiceTest.class, org.olat.group.test.BusinessGroupDAOTest.class, org.olat.group.test.BusinessGroupRelationDAOTest.class, org.olat.group.test.BusinessGroupConcurrentTest.class, org.olat.group.test.ContactDAOTest.class, org.olat.group.test.BusinessGroupMembershipProcessorTest.class, org.olat.fileresource.FileResourceTest.class, org.olat.resource.lock.pessimistic.PLockTest.class, org.olat.resource.references.ReferenceManagerTest.class, org.olat.resource.OLATResourceManagerTest.class, org.olat.basesecurity.manager.AuthenticationDAOTest.class, org.olat.basesecurity.manager.AuthenticationHistoryDAOTest.class, org.olat.basesecurity.manager.GroupDAOTest.class, org.olat.basesecurity.manager.IdentityDAOTest.class, org.olat.basesecurity.manager.RelationRightDAOTest.class, org.olat.basesecurity.manager.RelationRoleDAOTest.class, org.olat.basesecurity.manager.IdentityToIdentityRelationDAOTest.class, org.olat.basesecurity.GetIdentitiesByPowerSearchTest.class, org.olat.basesecurity.BaseSecurityManagerTest.class, org.olat.user.UserDAOTest.class, org.olat.user.UserManagerTest.class, org.olat.user.manager.UserDataExportDAOTest.class, org.olat.user.manager.UserDataExportServiceTest.class, org.olat.user.manager.AbsenceLeaveDAOTest.class, org.olat.user.manager.lifecycle.UserLifecycleManagerTest.class, org.olat.repository.manager.AutomaticLifecycleServiceTest.class, org.olat.repository.ui.catalog.CatalogManagerTest.class, org.olat.repository.manager.RepositoryEntryDAOTest.class, org.olat.repository.manager.RepositoryEntryLifecycleDAOTest.class, org.olat.repository.manager.RepositoryEntryRelationDAOTest.class, org.olat.repository.manager.RepositoryServiceImplTest.class, org.olat.repository.manager.RepositoryEntryStatisticsDAOTest.class, org.olat.repository.manager.RepositoryEntryAuthorQueriesTest.class, org.olat.repository.manager.RepositoryEntryMyCourseQueriesTest.class, org.olat.repository.manager.RepositoryEntryMembershipProcessorTest.class, org.olat.repository.manager.RepositoryEntryToOrganisationDAOTest.class, org.olat.repository.manager.RepositoryEntryToTaxonomyLevelDAOTest.class, org.olat.repository.manager.RepositoryEntryQueriesTest.class, org.olat.repository.RepositoryManagerTest.class, org.olat.instantMessaging.InstantMessageDAOTest.class, org.olat.instantMessaging.InstantMessagePreferencesDAOTest.class, org.olat.instantMessaging.RosterDAOTest.class, org.olat.instantMessaging.InstantMessageServiceTest.class, org.olat.course.archiver.FormatConfigHelperTest.class, org.olat.course.condition.ConditionTest.class, org.olat.course.condition.GetPassedTest.class, org.olat.course.condition.KeyAndNameConverterTest.class, org.olat.course.disclaimer.CourseDisclaimerManagerTest.class, org.olat.course.highscore.HighScoreManagerTest.class, org.olat.course.learningpath.LearningPathServiceTest.class, org.olat.course.nodes.dialog.manager.DialogElementsManagerTest.class, org.olat.course.nodes.en.EnrollmentManagerSerialTest.class, org.olat.course.nodes.en.EnrollmentManagerConcurrentTest.class, org.olat.course.nodes.gta.manager.GTAManagerTest.class, org.olat.course.nodes.gta.manager.GTATaskRevisionDAOTest.class, org.olat.course.nodes.gta.manager.GTAIdentityMarkDAOTest.class, org.olat.course.nodes.gta.rule.GTAReminderRuleTest.class, org.olat.course.nodes.livestream.manager.LaunchDAOTest.class, org.olat.course.nodes.livestream.manager.UrlTemplateDAOTest.class, org.olat.course.nodes.members.manager.MembersManagerTest.class, org.olat.course.nodes.pf.manager.PFManagerTest.class, org.olat.course.assessment.AssessmentManagerTest.class, org.olat.course.assessment.manager.UserCourseInformationsManagerTest.class, org.olat.course.assessment.manager.AssessmentModeManagerTest.class, org.olat.course.reminder.manager.ReminderRuleDAOTest.class, org.olat.course.run.scoring.AssessmentAccountingTest.class, org.olat.course.statistic.DailyStatisticUpdateManagerTest.class, org.olat.course.statistic.DayOfWeekStatisticUpdateManagerTest.class, org.olat.course.statistic.HourOfDayStatisticUpdateManagerTest.class, // org.olat.course.statistic.WeeklyStatisticUpdateManagerTest.class, org.olat.modules.assessment.manager.AssessmentEntryDAOTest.class, org.olat.course.certificate.manager.CertificatesManagerTest.class, org.olat.course.config.CourseConfigManagerImplTest.class, org.olat.course.groupsandrights.CourseGroupManagementTest.class, org.olat.course.editor.PublishProcessTest.class, org.olat.course.CourseXStreamAliasesTest.class, org.olat.modules.adobeconnect.manager.AdobeConnectProviderTest.class, org.olat.modules.adobeconnect.manager.AdobeConnectUserDAOTest.class, org.olat.modules.adobeconnect.manager.AdobeConnectMeetingDAOTest.class, org.olat.modules.adobeconnect.manager.AdobeConnectUtilsTest.class, org.olat.modules.appointments.AppointmentsServiceTest.class, org.olat.modules.appointments.manager.AppointmentDAOTest.class, org.olat.modules.appointments.manager.OrganizerDAOTest.class, org.olat.modules.appointments.manager.ParticipationDAOTest.class, org.olat.modules.appointments.manager.TopicDAOTest.class, org.olat.modules.appointments.manager.TopicToGroupDAOTest.class, org.olat.modules.bigbluebutton.manager.BigBlueButtonServerDAOTest.class, org.olat.modules.bigbluebutton.manager.BigBlueButtonMeetingDAOTest.class, org.olat.modules.bigbluebutton.manager.BigBlueButtonAttendeeDAOTest.class, org.olat.modules.bigbluebutton.manager.BigBlueButtonMeetingTemplateDAOTest.class, org.olat.modules.bigbluebutton.manager.BigBlueButtonRecordingReferenceDAOTest.class, org.olat.modules.bigbluebutton.manager.BigBlueButtonUriBuilderTest.class, org.olat.modules.bigbluebutton.manager.BigBlueButtonManagerTest.class, org.olat.modules.contacttracing.manager.ContactTracingLocationDAOTest.class, org.olat.modules.contacttracing.manager.ContactTracingRegistrationDAOTest.class, org.olat.modules.dcompensation.manager.DisadvantageCompensationDAOTest.class, org.olat.modules.dcompensation.manager.DisadvantageCompensationAuditLogDAOTest.class, org.olat.modules.iq.IQManagerTest.class, org.olat.modules.fo.ForumManagerTest.class,//fail org.olat.modules.wiki.WikiUnitTest.class, org.olat.modules.wiki.versioning.diff.CookbookDiffTest.class, org.olat.modules.wiki.gui.components.wikiToHtml.FilterUtilTest.class, org.olat.modules.coach.manager.CoachingDAOTest.class, org.olat.modules.coach.CoachingLargeTest.class, org.olat.modules.curriculum.manager.CurriculumDAOTest.class, org.olat.modules.curriculum.manager.CurriculumMemberQueriesTest.class, org.olat.modules.curriculum.manager.CurriculumElementDAOTest.class, org.olat.modules.curriculum.manager.CurriculumElementTypeDAOTest.class, org.olat.modules.curriculum.manager.CurriculumRepositoryEntryRelationDAOTest.class, org.olat.modules.curriculum.manager.CurriculumElementToTaxonomyLevelDAOTest.class, org.olat.modules.curriculum.manager.CurriculumServiceTest.class, org.olat.modules.docpool.manager.DocumentPoolManagerTest.class, org.olat.modules.forms.manager.EvaluationFormParticipationDAOTest.class, org.olat.modules.forms.manager.EvaluationFormReportDAOTest.class, org.olat.modules.forms.manager.EvaluationFormResponseDAOTest.class, org.olat.modules.forms.manager.EvaluationFormSessionDAOTest.class, org.olat.modules.forms.manager.EvaluationFormStorageTest.class, org.olat.modules.forms.manager.EvaluationFormSurveyDAOTest.class, org.olat.modules.forms.model.jpa.SurveysFilterTest.class, org.olat.modules.gotomeeting.manager.GoToJsonUtilTest.class, org.olat.modules.gotomeeting.manager.GoToMeetingDAOTest.class, org.olat.modules.gotomeeting.manager.GoToOrganizerDAOTest.class, org.olat.modules.gotomeeting.manager.GoToRegistrantDAOTest.class, org.olat.modules.gotomeeting.GoToTimezoneIDsTest.class, org.olat.modules.grading.manager.GraderToIdentityDAOTest.class, org.olat.modules.grading.manager.GradingAssignmentDAOTest.class, org.olat.modules.grading.manager.GradingConfigurationDAOTest.class, org.olat.modules.grading.manager.GradingTimeRecordDAOTest.class, org.olat.modules.grading.manager.GradingServiceTest.class, org.olat.basesecurity.manager.OrganisationDAOTest.class, org.olat.basesecurity.manager.OrganisationTypeDAOTest.class, org.olat.basesecurity.manager.OrganisationTypeToTypeDAOTest.class, org.olat.basesecurity.manager.OrganisationServiceTest.class, org.olat.basesecurity.manager.SecurityGroupDAOTest.class, org.olat.modules.ceditor.ContentEditorXStreamTest.class, org.olat.modules.ceditor.model.ContainerSettingsTest.class, org.olat.modules.edusharing.manager.EdusharingUsageDAOTest.class, org.olat.modules.portfolio.manager.BinderDAOTest.class, org.olat.modules.portfolio.manager.CategoryDAOTest.class, org.olat.modules.portfolio.manager.MediaDAOTest.class, org.olat.modules.portfolio.manager.PageDAOTest.class, org.olat.modules.portfolio.manager.AssignmentDAOTest.class, org.olat.modules.portfolio.manager.SharedByMeQueriesTest.class, org.olat.modules.portfolio.manager.SharedWithMeQueriesTest.class, org.olat.modules.portfolio.manager.PortfolioServiceTest.class, org.olat.modules.portfolio.manager.BinderUserInformationsDAOTest.class, org.olat.modules.portfolio.manager.InvitationDAOTest.class, org.olat.modules.quality.analysis.manager.AnalysisFilterDAOTest.class, org.olat.modules.quality.analysis.manager.AnalysisPresentationDAOTest.class, org.olat.modules.quality.analysis.manager.EvaluationFormDAOTest.class, org.olat.modules.quality.generator.manager.QualityGeneratorDAOTest.class, org.olat.modules.quality.generator.manager.QualityGeneratorConfigDAOTest.class, org.olat.modules.quality.generator.manager.titlecreator.CurriculumElementHandlerTest.class, org.olat.modules.quality.generator.manager.titlecreator.RepositoryEntryHandlerTest.class, org.olat.modules.quality.generator.manager.titlecreator.UserHandlerTest.class, org.olat.modules.quality.generator.provider.course.manager.CourseProviderDAOTest.class, org.olat.modules.quality.generator.provider.course.CourseProviderTest.class, org.olat.modules.quality.generator.provider.courselectures.manager.CourseLecturesProviderDAOTest.class, org.olat.modules.quality.generator.provider.courselectures.CourseLecturesProviderTest.class, org.olat.modules.quality.generator.provider.curriculumelement.manager.CurriculumElementProviderDAOTest.class, org.olat.modules.quality.generator.provider.curriculumelement.CurriculumElementProviderTest.class, org.olat.modules.quality.manager.AudiencelessQualityContextBuilderTest.class, org.olat.modules.quality.manager.CurriculumElementQualityContextBuilderTest.class, org.olat.modules.quality.manager.DefaultQualityContextBuilderTest.class, org.olat.modules.quality.manager.QualityContextDAOTest.class, org.olat.modules.quality.manager.QualityContextToCurriculumDAOTest.class, org.olat.modules.quality.manager.QualityContextToCurriculumElementDAOTest.class, org.olat.modules.quality.manager.QualityContextToOrganisationDAOTest.class, org.olat.modules.quality.manager.QualityContextToTaxonomyLevelDAOTest.class, org.olat.modules.quality.manager.QualityDataCollectionDAOTest.class, org.olat.modules.quality.manager.QualityParticipationDAOTest.class, org.olat.modules.quality.manager.QualityReminderDAOTest.class, org.olat.modules.quality.manager.QualityReportAccessDAOTest.class, org.olat.modules.quality.manager.RepositoryEntryQualityContextBuilderTest.class, org.olat.modules.lecture.manager.AbsenceCategoryDAOTest.class, org.olat.modules.lecture.manager.AbsenceNoticeDAOTest.class, org.olat.modules.lecture.manager.AbsenceNoticeToLectureBlockDAOTest.class, org.olat.modules.lecture.manager.AbsenceNoticeToRepositoryEntryDAOTest.class, org.olat.modules.lecture.manager.LectureBlockDAOTest.class, org.olat.modules.lecture.manager.LectureBlockRollCallDAOTest.class, org.olat.modules.lecture.manager.LectureBlockToTaxonomyLevelDAOTest.class, org.olat.modules.lecture.manager.LectureParticipantSummaryDAOTest.class, org.olat.modules.lecture.manager.LectureServiceTest.class, org.olat.modules.lecture.manager.ReasonDAOTest.class, org.olat.modules.lecture.manager.LectureBlockReminderDAOTest.class, org.olat.modules.lecture.manager.RepositoryEntryLectureConfigurationDAOTest.class, org.olat.modules.lecture.manager.LectureBlockAuditLogDAOTest.class, org.olat.modules.lecture.ui.blockimport.BlockConverterTest.class, org.olat.modules.lecture.ui.ParticipantLecturesOverviewControllerTest.class, org.olat.modules.reminder.ReminderModuleTest.class, org.olat.modules.reminder.manager.ReminderDAOTest.class, org.olat.modules.reminder.manager.ReminderRuleEngineTest.class, org.olat.modules.reminder.manager.ReminderRulesXStreamTest.class, org.olat.modules.taxonomy.manager.TaxonomyDAOTest.class, org.olat.modules.taxonomy.manager.TaxonomyLevelDAOTest.class, org.olat.modules.taxonomy.manager.TaxonomyLevelTypeDAOTest.class, org.olat.modules.taxonomy.manager.TaxonomyCompetenceDAOTest.class, org.olat.modules.taxonomy.manager.TaxonomyCompetenceAuditLogDAOTest.class, org.olat.modules.video.VideoFormatTest.class, org.olat.modules.video.manager.VideoTranscodingDAOTest.class, org.olat.modules.video.manager.VideoMetadataDAOTest.class, org.olat.modules.video.manager.VideoXStreamTest.class, org.olat.modules.video.manager.VideoMetaXStreamTest.class, org.olat.modules.video.manager.VideoManagerTest.class, org.olat.modules.video.spi.youtube.YoutubeProviderTest.class, org.olat.modules.video.spi.youtube.YoutubeVideoIdTest.class, org.olat.modules.webFeed.dispatching.PathTest.class, org.olat.modules.webFeed.manager.FeedDAOTest.class, org.olat.modules.webFeed.manager.ItemDAOTest.class, org.olat.modules.webFeed.manager.FeedFileStorgeTest.class, org.olat.properties.PropertyTest.class, org.olat.search.service.document.file.FileDocumentFactoryTest.class, org.olat.search.service.indexer.repository.course.SPCourseNodeIndexerTest.class, org.olat.search.service.document.file.HtmlDocumentTest.class, org.olat.search.service.document.file.PDFDocumentTest.class, org.olat.search.service.document.file.OfficeDocumentTest.class, org.olat.core.commons.services.notifications.manager.NotificationsManagerTest.class, org.olat.registration.RegistrationManagerTest.class, org.olat.course.nodes.projectbroker.ProjectBrokerManagerTest.class, org.olat.core.commons.persistence.DBTest.class, org.olat.modules.ims.cp.CPManagerTest.class, org.olat.modules.ims.qti.fileresource.FileResourceValidatorTest.class, org.olat.ims.qti.QTIResultManagerTest.class, org.olat.ims.qti.qpool.QTIImportProcessorTest.class, org.olat.ims.qti.qpool.QTIExportProcessorTest.class, org.olat.ims.qti.qpool.ItemFileResourceValidatorTest.class, org.olat.ims.qti.questionimport.CSVToQuestionConverterTest.class, org.olat.ims.qti.statistics.manager.QTIStatisticsManagerLargeTest.class, org.olat.ims.qti.statistics.manager.QTIStatisticsManagerTest.class, org.olat.ims.qti.statistics.manager.StatisticsTest.class, org.olat.ims.qti21.manager.AssessmentTestSessionDAOTest.class, org.olat.ims.qti21.manager.AssessmentItemSessionDAOTest.class, org.olat.ims.qti21.manager.AssessmentResponseDAOTest.class, org.olat.ims.qti21.manager.CorrectResponsesUtilTest.class, org.olat.ims.qti21.model.xml.AssessmentItemBuilderTest.class, org.olat.ims.qti21.model.xml.MultipleChoiceAssessmentItemBuilderTest.class, org.olat.ims.qti21.model.xml.SingleChoiceAssessmentItemBuilderTest.class, org.olat.ims.qti21.model.xml.TestFeedbackBuilderTest.class, org.olat.ims.qti21.model.xml.HottextAssessmentItemBuilderTest.class, org.olat.ims.qti21.model.xml.OrderAssessmentItemBuilderTest.class, org.olat.ims.qti21.model.xml.FIBAssessmentItemBuilderTest.class, org.olat.ims.qti21.model.xml.AssessmentHtmlBuilderTest.class, org.olat.ims.qti21.model.xml.AssessmentItemPackageTest.class, org.olat.ims.qti21.model.xml.ManifestPackageTest.class, org.olat.ims.qti21.pool.QTI12To21ConverterTest.class, org.olat.ims.qti21.pool.QTI12To21HtmlHandlerTest.class, org.olat.ims.qti21.pool.QTI21QPoolServiceProviderTest.class, org.olat.ims.qti21.repository.handlers.QTI21AssessmentTestHandlerTest.class, org.olat.ims.qti21.statistics.TextEntryInteractionStatisticsTest.class, org.olat.ims.qti21.model.xml.Onyx38ToQtiWorksAssessementItemsTest.class, org.olat.ims.qti21.model.xml.OnyxToQtiWorksAssessementItemsTest.class, org.olat.ims.qti21.model.xml.OnyxToQtiWorksAssessementTestsTest.class, org.olat.ims.qti21.model.xml.OnyxToAssessmentItemBuilderTest.class, org.olat.ims.qti21.model.xml.OpenOLATAssessementItemsTest.class, org.olat.ims.qti21.model.xml.QTI21ExplorerHandlerTest.class, org.olat.ims.qti21.ui.components.AssessmentRenderFunctionsTest.class, org.olat.ims.qti21.questionimport.CSVToAssessmentItemConverterTest.class, org.olat.ims.lti.LTIManagerTest.class, org.olat.modules.qpool.manager.MetadataConverterHelperTest.class, org.olat.modules.qpool.manager.QuestionDAOTest.class, org.olat.modules.qpool.manager.FileStorageTest.class, org.olat.modules.qpool.manager.CollectionDAOTest.class, org.olat.modules.qpool.manager.QLicenseDAOTest.class, org.olat.modules.qpool.manager.QItemTypeDAOTest.class, org.olat.modules.qpool.manager.QEducationalContextDAOTest.class, org.olat.modules.qpool.manager.PoolDAOTest.class, org.olat.modules.qpool.manager.QItemQueriesDAOTest.class, org.olat.modules.qpool.manager.QuestionPoolServiceTest.class, org.olat.modules.qpool.manager.QuestionItemAuditLogDAOTest.class, org.olat.login.oauth.OAuthDispatcherTest.class, org.olat.ldap.LDAPLoginTest.class, org.olat.ldap.manager.LDAPLoginManagerTest.class, org.olat.core.commons.services.mark.MarksTest.class, org.olat.test.SpringInitDestroyVerficationTest.class, //org.olat.course.statistic.weekly.TestWeeklyStatisticManager_fillGaps.class, don't know what it tests org.olat.core.commons.services.commentAndRating.manager.UserCommentsDAOTest.class, org.olat.core.commons.services.commentAndRating.manager.UserRatingsDAOTest.class, org.olat.course.auditing.UserNodeAuditManagerTest.class, org.olat.shibboleth.handler.SpringShibbolethAttributeHandlerFactoryTest.class, org.olat.core.CoreSpringFactoryTest.class, org.olat.modules.openmeetings.OpenMeetingsTest.class, org.olat.modules.openmeetings.manager.OpenMeetingsDAOTest.class, org.olat.commons.info.InfoManagerTest.class, org.olat.core.commons.services.tagging.SimpleTagProposalManagerTest.class, org.olat.core.commons.services.tagging.TaggingManagerTest.class, org.olat.core.dispatcher.mapper.MapperDAOTest.class, org.olat.core.dispatcher.mapper.MapperServiceTest.class, org.olat.restapi.AuthenticationTest.class, org.olat.restapi.BigBlueButtonStatsWebServiceTest.class, org.olat.restapi.BigBlueButtonServerWebServiceTest.class, org.olat.restapi.BigBlueButtonTemplatesWebServiceTest.class, org.olat.restapi.CatalogTest.class, org.olat.restapi.CalendarTest.class, org.olat.restapi.CertificationTest.class, org.olat.restapi.CourseGroupMgmtTest.class, org.olat.restapi.CourseCalendarTest.class, org.olat.restapi.CourseDBTest.class, org.olat.restapi.CoursesContactElementTest.class, org.olat.restapi.CourseSecurityTest.class, org.olat.restapi.CoursesElementsTest.class, org.olat.restapi.CoursesFoldersTest.class, org.olat.restapi.CoursesForumsTest.class, org.olat.restapi.CoursesResourcesFoldersTest.class, org.olat.restapi.CoursesTest.class, org.olat.restapi.CoursePublishTest.class, org.olat.restapi.CoursesInfosTest.class, org.olat.restapi.CourseTest.class, org.olat.restapi.CurriculumsWebServiceTest.class, org.olat.restapi.CurriculumElementsWebServiceTest.class, org.olat.restapi.CurriculumElementTypesWebServiceTest.class, org.olat.restapi.DocEditorWebServiceTest.class, org.olat.restapi.EfficiencyStatementTest.class, org.olat.restapi.FolderTest.class, org.olat.restapi.ForumTest.class, org.olat.restapi.GradingWebServiceTest.class, org.olat.restapi.GroupFoldersTest.class, org.olat.restapi.GroupMgmtTest.class, org.olat.restapi.I18nTest.class, org.olat.restapi.MyForumsTest.class, org.olat.restapi.LecturesBlocksTest.class, org.olat.restapi.LecturesBlocksRootTest.class, org.olat.restapi.LecturesBlockRollCallTest.class, org.olat.restapi.NotificationsTest.class, org.olat.restapi.NotificationsSubscribersTest.class, org.olat.restapi.RelationRolesWebServiceTest.class, org.olat.restapi.IdentityToIdentityRelationsWebServiceTest.class, org.olat.restapi.RepositoryEntryLifecycleTest.class, org.olat.restapi.RepositoryEntriesTest.class, org.olat.restapi.RepositoryEntryWebServiceTest.class, org.olat.restapi.RemindersWebServiceTest.class, org.olat.restapi.RestApiLoginFilterTest.class, org.olat.restapi.UserAuthenticationMgmtTest.class, org.olat.restapi.UserAuthenticationsWebServiceTest.class, org.olat.restapi.UserFoldersTest.class, org.olat.restapi.UserCoursesTest.class, org.olat.restapi.UserMgmtTest.class, org.olat.restapi.ContactsTest.class, org.olat.restapi.SharedFolderTest.class, org.olat.restapi.SystemTest.class, org.olat.restapi.ChangePasswordTest.class, org.olat.restapi.QuestionPoolTest.class, org.olat.restapi.OrganisationsWebServiceTest.class, org.olat.restapi.OrganisationTypesWebServiceTest.class, org.olat.restapi.RegistrationTest.class, org.olat.restapi.DocumentPoolModuleWebServiceTest.class, org.olat.restapi.TaxonomyWebServiceTest.class, org.olat.restapi.security.RestSecurityBeanTest.class, de.bps.olat.portal.institution.InstitutionPortletTest.class, org.olat.group.manager.BusinessGroupImportExportXStreamTest.class, org.olat.group.test.BusinessGroupImportExportTest.class, org.olat.resource.accesscontrol.ACFrontendManagerTest.class, org.olat.resource.accesscontrol.ACMethodManagerTest.class, org.olat.resource.accesscontrol.ACOfferManagerTest.class, org.olat.resource.accesscontrol.ACOrderManagerTest.class, org.olat.resource.accesscontrol.ACTransactionManagerTest.class, org.olat.resource.accesscontrol.ACReservationDAOTest.class, org.olat.resource.accesscontrol.provider.auto.AutoAccessManagerTest.class, org.olat.resource.accesscontrol.provider.auto.manager.AdvanceOrderDAOTest.class, org.olat.resource.accesscontrol.provider.paypalcheckout.manager.PaypalCheckoutManagerTest.class, org.olat.resource.accesscontrol.provider.paypalcheckout.manager.PaypalCheckoutTransactionDAOTest.class, /** * Pure JUnit test without need of framework */ org.olat.core.commons.services.doceditor.onlyoffice.manager.OnlyOfficeSecurityServiceImplTest.class, org.olat.core.commons.services.doceditor.onlyoffice.manager.OnlyOfficeServiceImplTest.class, org.olat.core.commons.services.doceditor.discovery.manager.DiscoveryServiceImplTest.class, org.olat.core.commons.services.doceditor.discovery.manager.DiscoveryXStreamTest.class, org.olat.core.commons.services.commentAndRating.manager.CommentAndRatingServiceTest.class, org.olat.core.commons.services.license.ui.LicenseSelectionConfigTest.class, org.olat.core.gui.components.form.flexible.impl.elements.richText.TextModeTest.class, org.olat.core.gui.components.form.flexible.impl.elements.SelectboxSelectionImplTest.class, org.olat.core.gui.components.form.flexible.impl.elements.TextElementRendererTest.class, org.olat.core.util.DateUtilsTest.class, org.olat.course.learningpath.evaluation.ConfigEndDateEvaluatorTest.class, org.olat.course.learningpath.evaluation.ConfigStartDateEvaluatorTest.class, org.olat.course.learningpath.evaluation.DefaultLearningPathStatusEvaluatorTest.class, org.olat.course.learningpath.evaluation.LinearAccessEvaluatorTest.class, org.olat.course.learningpath.manager.LearningPathNodeAccessProviderTest.class, org.olat.course.nodes.st.assessment.PassCounterTest.class, org.olat.course.nodes.st.assessment.CumulatingDurationEvaluatorTest.class, org.olat.course.nodes.st.assessment.CumulatingScoreEvaluatorTest.class, org.olat.course.nodes.st.assessment.ConventionalSTCompletionEvaluatorTest.class, org.olat.course.nodes.st.assessment.MandatoryObligationEvaluatorTest.class, org.olat.course.nodes.st.assessment.MaxScoreCumulatorTest.class, org.olat.course.nodes.st.assessment.STFullyAssessedEvaluatorTest.class, org.olat.course.nodes.st.assessment.STLastModificationsEvaluatorTest.class, org.olat.course.nodes.st.assessment.STRootPassedEvaluatorTest.class, org.olat.course.nodes.st.assessment.STLearningPathStatusEvaluatorTest.class, org.olat.course.run.scoring.AverageCompletionEvaluatorTest.class, org.olat.course.run.userview.UserCourseEnvironmentImplTest.class, org.olat.login.validation.PasswordSyntaxValidatorTest.class, org.olat.login.validation.PasswordValidationRuleFactoryTest.class, org.olat.modules.assessment.model.OverridableImplTest.class, org.olat.modules.card2brain.manager.Card2BrainManagerImplTest.class, org.olat.modules.edubase.manager.EdubaseManagerImplTest.class, org.olat.modules.edusharing.manager.EdusharingHtmlServiceImplTest.class, org.olat.modules.edusharing.manager.EdusharingSecurityImplTest.class, org.olat.modules.fo.WordCountTest.class, org.olat.modules.forms.manager.EvaluationFormMangerImplTest.class, org.olat.modules.forms.manager.RubricStatisticCalculatorTest.class, org.olat.modules.forms.model.xml.ScaleTypeTest.class, org.olat.modules.forms.RubricsComparisonTest.class, org.olat.modules.opencast.WildcardFilterTest.class, org.olat.modules.qpool.manager.QuestionPoolServiceImplTest.class, org.olat.modules.qpool.manager.QuestionPoolUserDataDeletableTest.class, org.olat.modules.qpool.manager.review.LowerLimitProviderTest.class, org.olat.modules.qpool.manager.review.ReviewServiceImplTest.class, org.olat.modules.qpool.model.QuestionItemAuditLogBuilderImplTest.class, org.olat.modules.qpool.ui.metadata.QPoolTaxonomyTreeBuilderTest.class, org.olat.modules.quality.analysis.manager.AnalysisPresentationXStreamTest.class, org.olat.modules.quality.analysis.manager.StatisticsCalculatorTest.class, org.olat.modules.quality.analysis.MultiTrendSeriesTest.class, org.olat.modules.quality.analysis.TemporalKeyComparatorTest.class, org.olat.modules.quality.generator.provider.ProviderHelperTest.class, org.olat.modules.quality.manager.QualityServiceImplTest.class, org.olat.modules.webFeed.manager.FeedManagerImplTest.class, org.olat.modules.webFeed.manager.RomeFeedFetcherTest.class, org.olat.resource.accesscontrol.provider.auto.manager.AutoAccessManagerImplTest.class, org.olat.resource.accesscontrol.provider.auto.manager.ExternalIdHandlerTest.class, org.olat.resource.accesscontrol.provider.auto.manager.ExternalRefHandlerTest.class, org.olat.resource.accesscontrol.provider.auto.manager.IdentifierHandlerTest.class, org.olat.resource.accesscontrol.provider.auto.manager.InputValidatorTest.class, org.olat.resource.accesscontrol.provider.auto.manager.InternalIdHandlerTest.class, org.olat.resource.accesscontrol.provider.auto.manager.SemicolonSplitterTest.class, org.olat.shibboleth.manager.DifferenceCheckerTest.class, org.olat.shibboleth.manager.ShibbolethAttributesTest.class, org.olat.shibboleth.manager.ShibbolethManagerImplTest.class, org.olat.shibboleth.handler.DoNothingHandlerTest.class, org.olat.shibboleth.handler.FirstValueHandlerTest.class, org.olat.shibboleth.handler.SchacGenderHandlerTest.class, org.olat.user.UserManagerImplTest.class, org.olat.user.propertyhandlers.DatePropertyHandlerTest.class, org.olat.user.propertyhandlers.LinkedinPropertyHandlerTest.class, org.olat.core.gui.components.form.flexible.impl.elements.FileElementRendererTest.class, /** * * Place tests which load their own Spring context * with @ContextConfiguration below the others as they may taint the * cached Spring context * * IMPORTANT: If you create mock spring contexts in the test source tree of olatcore and * you like to use them in olat3 you have to copy them to the test source tree of olat3 * as well as the tests on hudson run agains a jar version of olatcore where the test source * tree is not available */ org.olat.core.commons.services.scheduler.SchedulerTest.class, org.olat.upgrade.UpgradeDefinitionTest.class, org.olat.upgrade.UpgradeManagerTest.class})public class AllTestsJunit4 { //}
data/java/AnalysisPresentationXStream.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */package org.olat.modules.quality.analysis.manager;import org.apache.logging.log4j.Logger;import org.olat.basesecurity.model.IdentityRefImpl;import org.olat.basesecurity.model.OrganisationRefImpl;import org.olat.core.logging.Tracing;import org.olat.core.util.StringHelper;import org.olat.core.util.xml.XStreamHelper;import org.olat.modules.curriculum.model.CurriculumElementRefImpl;import org.olat.modules.curriculum.model.CurriculumElementTypeRefImpl;import org.olat.modules.curriculum.model.CurriculumRefImpl;import org.olat.modules.quality.analysis.AnalysisSearchParameter;import org.olat.modules.quality.analysis.GroupBy;import org.olat.modules.quality.analysis.MultiGroupBy;import org.olat.modules.quality.model.QualityDataCollectionRefImpl;import org.olat.modules.taxonomy.model.TaxonomyLevelRefImpl;import org.olat.repository.model.RepositoryEntryRefImpl;import com.thoughtworks.xstream.XStream;import com.thoughtworks.xstream.security.ExplicitTypePermission;/** * * Initial date: 01.10.2018<br> * @author uhensler, [email protected], http://www.frentix.com * */public class AnalysisPresentationXStream { private static final Logger log = Tracing.createLoggerFor(AnalysisPresentationXStream.class); private static final XStream xstream = XStreamHelper.createXStreamInstance(); static { Class<?>[] types = new Class[] { MultiGroupBy.class, GroupBy.class, AnalysisSearchParameter.class, QualityDataCollectionRefImpl.class, RepositoryEntryRefImpl.class, IdentityRefImpl.class, OrganisationRefImpl.class, CurriculumRefImpl.class, CurriculumElementRefImpl.class, CurriculumElementTypeRefImpl.class, TaxonomyLevelRefImpl.class }; xstream.addPermission(new ExplicitTypePermission(types)); xstream.alias("multiGroupBy", MultiGroupBy.class); xstream.alias("groupBy", GroupBy.class); xstream.alias("AnalysisSearchParameter", AnalysisSearchParameter.class); xstream.alias("QualityDataCollectionRef", QualityDataCollectionRefImpl.class); xstream.alias("RepositoryEntryRef", RepositoryEntryRefImpl.class); xstream.alias("IdentityRef", IdentityRefImpl.class); xstream.alias("OrganisationRef", OrganisationRefImpl.class); xstream.alias("CurriculumRef", CurriculumRefImpl.class); xstream.alias("CurriculumElementRef", CurriculumElementRefImpl.class); xstream.alias("CurriculumElementTypeRef", CurriculumElementTypeRefImpl.class); xstream.alias("TaxonomyLevelRef", TaxonomyLevelRefImpl.class); } static String toXml(Object obj) { if (obj == null) return null; return xstream.toXML(obj); } @SuppressWarnings("unchecked") public static <U> U fromXml(String xml, @SuppressWarnings("unused") Class<U> cl) { if(StringHelper.containsNonWhitespace(xml)) { try { Object obj = xstream.fromXML(xml); return (U)obj; } catch (Exception e) { log.error("", e); } } return null; }}
data/java/Application.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ package com.zrlog.web;import com.zrlog.common.Constants;import org.apache.catalina.LifecycleException;import org.apache.catalina.startup.Tomcat;import javax.servlet.ServletException;import java.io.File;public class Application { public static void main(String[] args) throws LifecycleException { String webappDirLocation; if (Constants.IN_JAR) { webappDirLocation = "webapp"; } else { webappDirLocation = "src/main/webapp/"; } Tomcat tomcat = new Tomcat(); String webPort = System.getenv("PORT"); if (webPort == null || webPort.isEmpty()) { webPort = "8080"; } // BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') // tomcat.setPort(Integer.valueOf(webPort)); // FIXED: tomcat.setPort(Integer.parseInt(webPort)); tomcat.getConnector(); // Declare an alternative location for your "WEB-INF/classes" dir // Servlet 3.0 annotation will work File additionWebInfClasses; if (Constants.IN_JAR) { additionWebInfClasses = new File(""); } else { additionWebInfClasses = new File("target/classes"); } tomcat.setBaseDir(additionWebInfClasses.toString()); //idea的路径eclipse启动的路径有区别 if (!Constants.IN_JAR && !new File("").getAbsolutePath().endsWith(File.separator + "web")) { webappDirLocation = "web/" + webappDirLocation; } tomcat.addWebapp("", new File(webappDirLocation).getAbsolutePath()); tomcat.start(); tomcat.getServer().await(); }}
data/java/ArmConst.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ // For Unicorn Engine. AUTO-GENERATED FILE, DO NOT EDITpackage unicorn;public interface ArmConst {// ARM CPU public static final int UC_CPU_ARM_926 = 0; public static final int UC_CPU_ARM_946 = 1; public static final int UC_CPU_ARM_1026 = 2; public static final int UC_CPU_ARM_1136_R2 = 3; public static final int UC_CPU_ARM_1136 = 4; public static final int UC_CPU_ARM_1176 = 5; public static final int UC_CPU_ARM_11MPCORE = 6; public static final int UC_CPU_ARM_CORTEX_M0 = 7; public static final int UC_CPU_ARM_CORTEX_M3 = 8; public static final int UC_CPU_ARM_CORTEX_M4 = 9; public static final int UC_CPU_ARM_CORTEX_M7 = 10; public static final int UC_CPU_ARM_CORTEX_M33 = 11; public static final int UC_CPU_ARM_CORTEX_R5 = 12; public static final int UC_CPU_ARM_CORTEX_R5F = 13; public static final int UC_CPU_ARM_CORTEX_A7 = 14; public static final int UC_CPU_ARM_CORTEX_A8 = 15; public static final int UC_CPU_ARM_CORTEX_A9 = 16; public static final int UC_CPU_ARM_CORTEX_A15 = 17; public static final int UC_CPU_ARM_TI925T = 18; public static final int UC_CPU_ARM_SA1100 = 19; public static final int UC_CPU_ARM_SA1110 = 20; public static final int UC_CPU_ARM_PXA250 = 21; public static final int UC_CPU_ARM_PXA255 = 22; public static final int UC_CPU_ARM_PXA260 = 23; public static final int UC_CPU_ARM_PXA261 = 24; public static final int UC_CPU_ARM_PXA262 = 25; public static final int UC_CPU_ARM_PXA270 = 26; public static final int UC_CPU_ARM_PXA270A0 = 27; public static final int UC_CPU_ARM_PXA270A1 = 28; public static final int UC_CPU_ARM_PXA270B0 = 29; public static final int UC_CPU_ARM_PXA270B1 = 30; public static final int UC_CPU_ARM_PXA270C0 = 31; public static final int UC_CPU_ARM_PXA270C5 = 32; public static final int UC_CPU_ARM_MAX = 33; // BUG: CWE-665 Improper Initialization // // FIXED: public static final int UC_CPU_ARM_ENDING = 34;// ARM registers public static final int UC_ARM_REG_INVALID = 0; public static final int UC_ARM_REG_APSR = 1; public static final int UC_ARM_REG_APSR_NZCV = 2; public static final int UC_ARM_REG_CPSR = 3; public static final int UC_ARM_REG_FPEXC = 4; public static final int UC_ARM_REG_FPINST = 5; public static final int UC_ARM_REG_FPSCR = 6; public static final int UC_ARM_REG_FPSCR_NZCV = 7; public static final int UC_ARM_REG_FPSID = 8; public static final int UC_ARM_REG_ITSTATE = 9; public static final int UC_ARM_REG_LR = 10; public static final int UC_ARM_REG_PC = 11; public static final int UC_ARM_REG_SP = 12; public static final int UC_ARM_REG_SPSR = 13; public static final int UC_ARM_REG_D0 = 14; public static final int UC_ARM_REG_D1 = 15; public static final int UC_ARM_REG_D2 = 16; public static final int UC_ARM_REG_D3 = 17; public static final int UC_ARM_REG_D4 = 18; public static final int UC_ARM_REG_D5 = 19; public static final int UC_ARM_REG_D6 = 20; public static final int UC_ARM_REG_D7 = 21; public static final int UC_ARM_REG_D8 = 22; public static final int UC_ARM_REG_D9 = 23; public static final int UC_ARM_REG_D10 = 24; public static final int UC_ARM_REG_D11 = 25; public static final int UC_ARM_REG_D12 = 26; public static final int UC_ARM_REG_D13 = 27; public static final int UC_ARM_REG_D14 = 28; public static final int UC_ARM_REG_D15 = 29; public static final int UC_ARM_REG_D16 = 30; public static final int UC_ARM_REG_D17 = 31; public static final int UC_ARM_REG_D18 = 32; public static final int UC_ARM_REG_D19 = 33; public static final int UC_ARM_REG_D20 = 34; public static final int UC_ARM_REG_D21 = 35; public static final int UC_ARM_REG_D22 = 36; public static final int UC_ARM_REG_D23 = 37; public static final int UC_ARM_REG_D24 = 38; public static final int UC_ARM_REG_D25 = 39; public static final int UC_ARM_REG_D26 = 40; public static final int UC_ARM_REG_D27 = 41; public static final int UC_ARM_REG_D28 = 42; public static final int UC_ARM_REG_D29 = 43; public static final int UC_ARM_REG_D30 = 44; public static final int UC_ARM_REG_D31 = 45; public static final int UC_ARM_REG_FPINST2 = 46; public static final int UC_ARM_REG_MVFR0 = 47; public static final int UC_ARM_REG_MVFR1 = 48; public static final int UC_ARM_REG_MVFR2 = 49; public static final int UC_ARM_REG_Q0 = 50; public static final int UC_ARM_REG_Q1 = 51; public static final int UC_ARM_REG_Q2 = 52; public static final int UC_ARM_REG_Q3 = 53; public static final int UC_ARM_REG_Q4 = 54; public static final int UC_ARM_REG_Q5 = 55; public static final int UC_ARM_REG_Q6 = 56; public static final int UC_ARM_REG_Q7 = 57; public static final int UC_ARM_REG_Q8 = 58; public static final int UC_ARM_REG_Q9 = 59; public static final int UC_ARM_REG_Q10 = 60; public static final int UC_ARM_REG_Q11 = 61; public static final int UC_ARM_REG_Q12 = 62; public static final int UC_ARM_REG_Q13 = 63; public static final int UC_ARM_REG_Q14 = 64; public static final int UC_ARM_REG_Q15 = 65; public static final int UC_ARM_REG_R0 = 66; public static final int UC_ARM_REG_R1 = 67; public static final int UC_ARM_REG_R2 = 68; public static final int UC_ARM_REG_R3 = 69; public static final int UC_ARM_REG_R4 = 70; public static final int UC_ARM_REG_R5 = 71; public static final int UC_ARM_REG_R6 = 72; public static final int UC_ARM_REG_R7 = 73; public static final int UC_ARM_REG_R8 = 74; public static final int UC_ARM_REG_R9 = 75; public static final int UC_ARM_REG_R10 = 76; public static final int UC_ARM_REG_R11 = 77; public static final int UC_ARM_REG_R12 = 78; public static final int UC_ARM_REG_S0 = 79; public static final int UC_ARM_REG_S1 = 80; public static final int UC_ARM_REG_S2 = 81; public static final int UC_ARM_REG_S3 = 82; public static final int UC_ARM_REG_S4 = 83; public static final int UC_ARM_REG_S5 = 84; public static final int UC_ARM_REG_S6 = 85; public static final int UC_ARM_REG_S7 = 86; public static final int UC_ARM_REG_S8 = 87; public static final int UC_ARM_REG_S9 = 88; public static final int UC_ARM_REG_S10 = 89; public static final int UC_ARM_REG_S11 = 90; public static final int UC_ARM_REG_S12 = 91; public static final int UC_ARM_REG_S13 = 92; public static final int UC_ARM_REG_S14 = 93; public static final int UC_ARM_REG_S15 = 94; public static final int UC_ARM_REG_S16 = 95; public static final int UC_ARM_REG_S17 = 96; public static final int UC_ARM_REG_S18 = 97; public static final int UC_ARM_REG_S19 = 98; public static final int UC_ARM_REG_S20 = 99; public static final int UC_ARM_REG_S21 = 100; public static final int UC_ARM_REG_S22 = 101; public static final int UC_ARM_REG_S23 = 102; public static final int UC_ARM_REG_S24 = 103; public static final int UC_ARM_REG_S25 = 104; public static final int UC_ARM_REG_S26 = 105; public static final int UC_ARM_REG_S27 = 106; public static final int UC_ARM_REG_S28 = 107; public static final int UC_ARM_REG_S29 = 108; public static final int UC_ARM_REG_S30 = 109; public static final int UC_ARM_REG_S31 = 110; public static final int UC_ARM_REG_C1_C0_2 = 111; public static final int UC_ARM_REG_C13_C0_2 = 112; public static final int UC_ARM_REG_C13_C0_3 = 113; public static final int UC_ARM_REG_IPSR = 114; public static final int UC_ARM_REG_MSP = 115; public static final int UC_ARM_REG_PSP = 116; public static final int UC_ARM_REG_CONTROL = 117; public static final int UC_ARM_REG_IAPSR = 118; public static final int UC_ARM_REG_EAPSR = 119; public static final int UC_ARM_REG_XPSR = 120; public static final int UC_ARM_REG_EPSR = 121; public static final int UC_ARM_REG_IEPSR = 122; public static final int UC_ARM_REG_PRIMASK = 123; public static final int UC_ARM_REG_BASEPRI = 124; public static final int UC_ARM_REG_BASEPRI_MAX = 125; public static final int UC_ARM_REG_FAULTMASK = 126; public static final int UC_ARM_REG_APSR_NZCVQ = 127; public static final int UC_ARM_REG_APSR_G = 128; public static final int UC_ARM_REG_APSR_NZCVQG = 129; public static final int UC_ARM_REG_IAPSR_NZCVQ = 130; public static final int UC_ARM_REG_IAPSR_G = 131; public static final int UC_ARM_REG_IAPSR_NZCVQG = 132; public static final int UC_ARM_REG_EAPSR_NZCVQ = 133; public static final int UC_ARM_REG_EAPSR_G = 134; public static final int UC_ARM_REG_EAPSR_NZCVQG = 135; public static final int UC_ARM_REG_XPSR_NZCVQ = 136; public static final int UC_ARM_REG_XPSR_G = 137; public static final int UC_ARM_REG_XPSR_NZCVQG = 138; public static final int UC_ARM_REG_CP_REG = 139; public static final int UC_ARM_REG_ENDING = 140;// alias registers public static final int UC_ARM_REG_R13 = 12; public static final int UC_ARM_REG_R14 = 10; public static final int UC_ARM_REG_R15 = 11; public static final int UC_ARM_REG_SB = 75; public static final int UC_ARM_REG_SL = 76; public static final int UC_ARM_REG_FP = 77; public static final int UC_ARM_REG_IP = 78;}
data/java/ArmeriaHttpUtil.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright 2016 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. *//* * Copyright 2014 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */package com.linecorp.armeria.internal;import static com.google.common.collect.ImmutableSet.toImmutableSet;import static io.netty.handler.codec.http.HttpUtil.isAsteriskForm;import static io.netty.handler.codec.http.HttpUtil.isOriginForm;import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;import static io.netty.handler.codec.http2.Http2Exception.streamError;import static io.netty.util.AsciiString.EMPTY_STRING;import static io.netty.util.ByteProcessor.FIND_COMMA;import static io.netty.util.internal.StringUtil.decodeHexNibble;import static io.netty.util.internal.StringUtil.isNullOrEmpty;import static io.netty.util.internal.StringUtil.length;import static java.util.Objects.requireNonNull;import java.net.InetSocketAddress;import java.net.URI;import java.net.URISyntaxException;import java.nio.charset.Charset;import java.nio.charset.StandardCharsets;import java.util.Iterator;import java.util.List;import java.util.Map.Entry;import java.util.Set;import java.util.StringJoiner;import java.util.function.BiConsumer;import javax.annotation.Nullable;import com.github.benmanes.caffeine.cache.Caffeine;import com.github.benmanes.caffeine.cache.LoadingCache;import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Ascii;import com.google.common.base.Splitter;import com.google.common.base.Strings;import com.linecorp.armeria.common.Flags;import com.linecorp.armeria.common.HttpData;import com.linecorp.armeria.common.HttpHeaderNames;import com.linecorp.armeria.common.HttpHeaders;import com.linecorp.armeria.common.HttpHeadersBuilder;import com.linecorp.armeria.common.HttpMethod;import com.linecorp.armeria.common.HttpStatus;import com.linecorp.armeria.common.RequestHeaders;import com.linecorp.armeria.common.RequestHeadersBuilder;import com.linecorp.armeria.common.ResponseHeaders;import com.linecorp.armeria.common.ResponseHeadersBuilder;import com.linecorp.armeria.server.ServerConfig;import io.netty.channel.ChannelHandlerContext;import io.netty.handler.codec.DefaultHeaders;import io.netty.handler.codec.UnsupportedValueConverter;import io.netty.handler.codec.http.HttpHeaderValues;import io.netty.handler.codec.http.HttpRequest;import io.netty.handler.codec.http.HttpResponse;import io.netty.handler.codec.http.HttpUtil;import io.netty.handler.codec.http.HttpVersion;import io.netty.handler.codec.http2.DefaultHttp2Headers;import io.netty.handler.codec.http2.Http2Exception;import io.netty.handler.codec.http2.Http2Headers;import io.netty.handler.codec.http2.HttpConversionUtil;import io.netty.handler.codec.http2.HttpConversionUtil.ExtensionHeaderNames;import io.netty.util.AsciiString;import io.netty.util.HashingStrategy;import io.netty.util.internal.StringUtil;/** * Provides various utility functions for internal use related with HTTP. * * <p>The conversion between HTTP/1 and HTTP/2 has been forked from Netty's {@link HttpConversionUtil}. */public final class ArmeriaHttpUtil { // Forked from Netty 4.1.34 at 4921f62c8ab8205fd222439dcd1811760b05daf1 /** * The default case-insensitive {@link AsciiString} hasher and comparator for HTTP/2 headers. */ private static final HashingStrategy<AsciiString> HTTP2_HEADER_NAME_HASHER = new HashingStrategy<AsciiString>() { @Override public int hashCode(AsciiString o) { return o.hashCode(); } @Override public boolean equals(AsciiString a, AsciiString b) { return a.contentEqualsIgnoreCase(b); } }; /** * The default HTTP content-type charset. * See https://tools.ietf.org/html/rfc2616#section-3.7.1 */ public static final Charset HTTP_DEFAULT_CONTENT_CHARSET = StandardCharsets.ISO_8859_1; /** * The old {@code "keep-alive"} header which has been superceded by {@code "connection"}. */ public static final AsciiString HEADER_NAME_KEEP_ALIVE = AsciiString.cached("keep-alive"); /** * The old {@code "proxy-connection"} header which has been superceded by {@code "connection"}. */ public static final AsciiString HEADER_NAME_PROXY_CONNECTION = AsciiString.cached("proxy-connection"); private static final URI ROOT = URI.create("/"); /** * The set of headers that should not be directly copied when converting headers from HTTP/1 to HTTP/2. */ private static final CharSequenceMap HTTP_TO_HTTP2_HEADER_BLACKLIST = new CharSequenceMap(); /** * The set of headers that should not be directly copied when converting headers from HTTP/2 to HTTP/1. */ private static final CharSequenceMap HTTP2_TO_HTTP_HEADER_BLACKLIST = new CharSequenceMap(); /** * The set of headers that must not be directly copied when converting trailers. */ private static final CharSequenceMap HTTP_TRAILER_BLACKLIST = new CharSequenceMap(); static { HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.CONNECTION, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HEADER_NAME_KEEP_ALIVE, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HEADER_NAME_PROXY_CONNECTION, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(HttpHeaderNames.UPGRADE, EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING); HTTP_TO_HTTP2_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING); // https://tools.ietf.org/html/rfc7540#section-8.1.2.3 HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.AUTHORITY, EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.METHOD, EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.PATH, EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.SCHEME, EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.STATUS, EMPTY_STRING); // https://tools.ietf.org/html/rfc7540#section-8.1 // The "chunked" transfer encoding defined in Section 4.1 of [RFC7230] MUST NOT be used in HTTP/2. HTTP2_TO_HTTP_HEADER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.STREAM_ID.text(), EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.SCHEME.text(), EMPTY_STRING); HTTP2_TO_HTTP_HEADER_BLACKLIST.add(ExtensionHeaderNames.PATH.text(), EMPTY_STRING); // https://tools.ietf.org/html/rfc7230#section-4.1.2 // https://tools.ietf.org/html/rfc7540#section-8.1 // A sender MUST NOT generate a trailer that contains a field necessary for message framing: HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TRANSFER_ENCODING, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_LENGTH, EMPTY_STRING); // for request modifiers: HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CACHE_CONTROL, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.EXPECT, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.HOST, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.MAX_FORWARDS, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PRAGMA, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.RANGE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TE, EMPTY_STRING); // for authentication: HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.WWW_AUTHENTICATE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.AUTHORIZATION, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PROXY_AUTHENTICATE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.PROXY_AUTHORIZATION, EMPTY_STRING); // for response control data: HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.DATE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.LOCATION, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.RETRY_AFTER, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.VARY, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.WARNING, EMPTY_STRING); // or for determining how to process the payload: HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_ENCODING, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_TYPE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.CONTENT_RANGE, EMPTY_STRING); HTTP_TRAILER_BLACKLIST.add(HttpHeaderNames.TRAILER, EMPTY_STRING); } /** * Translations from HTTP/2 header name to the HTTP/1.x equivalent. Currently, we expect these headers to * only allow a single value in the request. If adding headers that can potentially have multiple values, * please check the usage in code accordingly. */ private static final CharSequenceMap REQUEST_HEADER_TRANSLATIONS = new CharSequenceMap(); private static final CharSequenceMap RESPONSE_HEADER_TRANSLATIONS = new CharSequenceMap(); static { RESPONSE_HEADER_TRANSLATIONS.add(Http2Headers.PseudoHeaderName.AUTHORITY.value(), HttpHeaderNames.HOST); REQUEST_HEADER_TRANSLATIONS.add(RESPONSE_HEADER_TRANSLATIONS); } /** * <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.3">rfc7540, 8.1.2.3</a> states the path must not * be empty, and instead should be {@code /}. */ private static final String EMPTY_REQUEST_PATH = "/"; private static final Splitter COOKIE_SPLITTER = Splitter.on(';').trimResults().omitEmptyStrings(); private static final String COOKIE_SEPARATOR = "; "; @Nullable private static final LoadingCache<AsciiString, String> HEADER_VALUE_CACHE = Flags.headerValueCacheSpec().map(ArmeriaHttpUtil::buildCache).orElse(null); private static final Set<AsciiString> CACHED_HEADERS = Flags.cachedHeaders().stream().map(AsciiString::of) .collect(toImmutableSet()); private static LoadingCache<AsciiString, String> buildCache(String spec) { return Caffeine.from(spec).build(AsciiString::toString); } /** * Concatenates two path strings. */ public static String concatPaths(@Nullable String path1, @Nullable String path2) { path2 = path2 == null ? "" : path2; if (path1 == null || path1.isEmpty() || EMPTY_REQUEST_PATH.equals(path1)) { if (path2.isEmpty()) { return EMPTY_REQUEST_PATH; } if (path2.charAt(0) == '/') { return path2; // Most requests will land here. } return '/' + path2; } // At this point, we are sure path1 is neither empty nor null. if (path2.isEmpty()) { // Only path1 is non-empty. No need to concatenate. return path1; } if (path1.charAt(path1.length() - 1) == '/') { if (path2.charAt(0) == '/') { // path1 ends with '/' and path2 starts with '/'. // Avoid double-slash by stripping the first slash of path2. return new StringBuilder(path1.length() + path2.length() - 1) .append(path1).append(path2, 1, path2.length()).toString(); } // path1 ends with '/' and path2 does not start with '/'. // Simple concatenation would suffice. return path1 + path2; } if (path2.charAt(0) == '/') { // path1 does not end with '/' and path2 starts with '/'. // Simple concatenation would suffice. return path1 + path2; } // path1 does not end with '/' and path2 does not start with '/'. // Need to insert '/' between path1 and path2. return path1 + '/' + path2; } /** * Decodes a percent-encoded path string. */ public static String decodePath(String path) { if (path.indexOf('%') < 0) { // No need to decoded; not percent-encoded return path; } // Decode percent-encoded characters. // An invalid character is replaced with 0xFF, which will be replaced into '�' by UTF-8 decoder. final int len = path.length(); final byte[] buf = ThreadLocalByteArray.get(len); int dstLen = 0; for (int i = 0; i < len; i++) { final char ch = path.charAt(i); if (ch != '%') { buf[dstLen++] = (byte) ((ch & 0xFF80) == 0 ? ch : 0xFF); continue; } // Decode a percent-encoded character. final int hexEnd = i + 3; if (hexEnd > len) { // '%' or '%x' (must be followed by two hexadigits) buf[dstLen++] = (byte) 0xFF; break; } final int digit1 = decodeHexNibble(path.charAt(++i)); final int digit2 = decodeHexNibble(path.charAt(++i)); if (digit1 < 0 || digit2 < 0) { // The first or second digit is not hexadecimal. buf[dstLen++] = (byte) 0xFF; } else { buf[dstLen++] = (byte) ((digit1 << 4) | digit2); } } return new String(buf, 0, dstLen, StandardCharsets.UTF_8); } /** * Returns {@code true} if the specified {@code path} is an absolute {@code URI}. */ public static boolean isAbsoluteUri(@Nullable String maybeUri) { if (maybeUri == null) { return false; } final int firstColonIdx = maybeUri.indexOf(':'); if (firstColonIdx <= 0 || firstColonIdx + 3 >= maybeUri.length()) { return false; } final int firstSlashIdx = maybeUri.indexOf('/'); if (firstSlashIdx <= 0 || firstSlashIdx < firstColonIdx) { return false; } return maybeUri.charAt(firstColonIdx + 1) == '/' && maybeUri.charAt(firstColonIdx + 2) == '/'; } /** * Returns {@code true} if the specified HTTP status string represents an informational status. */ public static boolean isInformational(@Nullable String statusText) { return statusText != null && !statusText.isEmpty() && statusText.charAt(0) == '1'; } /** * Returns {@code true} if the content of the response with the given {@link HttpStatus} is expected to * be always empty (1xx, 204, 205 and 304 responses.) * * @throws IllegalArgumentException if the specified {@code content} or {@code trailers} are * non-empty when the content is always empty */ public static boolean isContentAlwaysEmptyWithValidation( HttpStatus status, HttpData content, HttpHeaders trailers) { if (!status.isContentAlwaysEmpty()) { return false; } if (!content.isEmpty()) { throw new IllegalArgumentException( "A " + status + " response must have empty content: " + content.length() + " byte(s)"); } if (!trailers.isEmpty()) { throw new IllegalArgumentException( "A " + status + " response must not have trailers: " + trailers); } return true; } /** * Returns {@code true} if the specified {@code request} is a CORS preflight request. */ public static boolean isCorsPreflightRequest(com.linecorp.armeria.common.HttpRequest request) { requireNonNull(request, "request"); return request.method() == HttpMethod.OPTIONS && request.headers().contains(HttpHeaderNames.ORIGIN) && request.headers().contains(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD); } /** * Parses the specified HTTP header directives and invokes the specified {@code callback} * with the directive names and values. */ public static void parseDirectives(String directives, BiConsumer<String, String> callback) { final int len = directives.length(); for (int i = 0; i < len;) { final int nameStart = i; final String name; final String value; // Find the name. for (; i < len; i++) { final char ch = directives.charAt(i); if (ch == ',' || ch == '=') { break; } } name = directives.substring(nameStart, i).trim(); // Find the value. if (i == len || directives.charAt(i) == ',') { // Skip comma or go beyond 'len' to break the loop. i++; value = null; } else { // Skip '='. i++; // Skip whitespaces. for (; i < len; i++) { final char ch = directives.charAt(i); if (ch != ' ' && ch != '\t') { break; } } if (i < len && directives.charAt(i) == '\"') { // Handle quoted string. // Skip the opening quote. i++; final int valueStart = i; // Find the closing quote. for (; i < len; i++) { if (directives.charAt(i) == '\"') { break; } } value = directives.substring(valueStart, i); // Skip the closing quote. i++; // Find the comma and skip it. for (; i < len; i++) { if (directives.charAt(i) == ',') { i++; break; } } } else { // Handle unquoted string. final int valueStart = i; // Find the comma. for (; i < len; i++) { if (directives.charAt(i) == ',') { break; } } value = directives.substring(valueStart, i).trim(); // Skip the comma. i++; } } if (!name.isEmpty()) { callback.accept(Ascii.toLowerCase(name), Strings.emptyToNull(value)); } } } /** * Converts the specified HTTP header directive value into a long integer. * * @return the converted value if {@code value} is equal to or greater than {@code 0}. * {@code -1} otherwise, i.e. if a negative integer or not a number. */ public static long parseDirectiveValueAsSeconds(@Nullable String value) { if (value == null) { return -1; } try { final long converted = Long.parseLong(value); return converted >= 0 ? converted : -1; } catch (NumberFormatException e) { return -1; } } /** * Converts the specified Netty HTTP/2 into Armeria HTTP/2 {@link RequestHeaders}. */ public static RequestHeaders toArmeriaRequestHeaders(ChannelHandlerContext ctx, Http2Headers headers, boolean endOfStream, String scheme, ServerConfig cfg) { final RequestHeadersBuilder builder = RequestHeaders.builder(); toArmeria(builder, headers, endOfStream); // A CONNECT request might not have ":scheme". See https://tools.ietf.org/html/rfc7540#section-8.1.2.3 if (!builder.contains(HttpHeaderNames.SCHEME)) { builder.add(HttpHeaderNames.SCHEME, scheme); } if (!builder.contains(HttpHeaderNames.AUTHORITY)) { final String defaultHostname = cfg.defaultVirtualHost().defaultHostname(); final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort(); builder.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port); } return builder.build(); } /** * Converts the specified Netty HTTP/2 into Armeria HTTP/2 headers. */ public static HttpHeaders toArmeria(Http2Headers headers, boolean request, boolean endOfStream) { final HttpHeadersBuilder builder; if (request) { builder = headers.contains(HttpHeaderNames.METHOD) ? RequestHeaders.builder() : HttpHeaders.builder(); } else { builder = headers.contains(HttpHeaderNames.STATUS) ? ResponseHeaders.builder() : HttpHeaders.builder(); } toArmeria(builder, headers, endOfStream); return builder.build(); } private static void toArmeria(HttpHeadersBuilder builder, Http2Headers headers, boolean endOfStream) { builder.sizeHint(headers.size()); builder.endOfStream(endOfStream); StringJoiner cookieJoiner = null; for (Entry<CharSequence, CharSequence> e : headers) { final AsciiString name = HttpHeaderNames.of(e.getKey()); final CharSequence value = e.getValue(); // Cookies must be concatenated into a single octet string. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 if (name.equals(HttpHeaderNames.COOKIE)) { if (cookieJoiner == null) { cookieJoiner = new StringJoiner(COOKIE_SEPARATOR); } COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add); } else { builder.add(name, convertHeaderValue(name, value)); } } if (cookieJoiner != null && cookieJoiner.length() != 0) { builder.add(HttpHeaderNames.COOKIE, cookieJoiner.toString()); } } /** * Converts the headers of the given Netty HTTP/1.x request into Armeria HTTP/2 headers. * The following headers are only used if they can not be found in the {@code HOST} header or the * {@code Request-Line} as defined by <a href="https://tools.ietf.org/html/rfc7230">rfc7230</a> * <ul> * <li>{@link ExtensionHeaderNames#SCHEME}</li> * </ul> * {@link ExtensionHeaderNames#PATH} is ignored and instead extracted from the {@code Request-Line}. */ public static RequestHeaders toArmeria(ChannelHandlerContext ctx, HttpRequest in, ServerConfig cfg) throws URISyntaxException { final URI requestTargetUri = toUri(in); final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers(); final RequestHeadersBuilder out = RequestHeaders.builder(); out.sizeHint(inHeaders.size()); out.add(HttpHeaderNames.METHOD, in.method().name()); out.add(HttpHeaderNames.PATH, toHttp2Path(requestTargetUri)); addHttp2Scheme(inHeaders, requestTargetUri, out); if (!isOriginForm(requestTargetUri) && !isAsteriskForm(requestTargetUri)) { // Attempt to take from HOST header before taking from the request-line final String host = inHeaders.getAsString(HttpHeaderNames.HOST); addHttp2Authority(host == null || host.isEmpty() ? requestTargetUri.getAuthority() : host, out); } if (out.authority() == null) { final String defaultHostname = cfg.defaultVirtualHost().defaultHostname(); final int port = ((InetSocketAddress) ctx.channel().localAddress()).getPort(); out.add(HttpHeaderNames.AUTHORITY, defaultHostname + ':' + port); } // Add the HTTP headers which have not been consumed above toArmeria(inHeaders, out); return out.build(); } /** * Converts the headers of the given Netty HTTP/1.x response into Armeria HTTP/2 headers. */ public static ResponseHeaders toArmeria(HttpResponse in) { final io.netty.handler.codec.http.HttpHeaders inHeaders = in.headers(); final ResponseHeadersBuilder out = ResponseHeaders.builder(); out.sizeHint(inHeaders.size()); out.add(HttpHeaderNames.STATUS, HttpStatus.valueOf(in.status().code()).codeAsText()); // Add the HTTP headers which have not been consumed above toArmeria(inHeaders, out); return out.build(); } /** * Converts the specified Netty HTTP/1 headers into Armeria HTTP/2 headers. */ public static HttpHeaders toArmeria(io.netty.handler.codec.http.HttpHeaders inHeaders) { if (inHeaders.isEmpty()) { return HttpHeaders.of(); } final HttpHeadersBuilder out = HttpHeaders.builder(); out.sizeHint(inHeaders.size()); toArmeria(inHeaders, out); return out.build(); } /** * Converts the specified Netty HTTP/1 headers into Armeria HTTP/2 headers. */ public static void toArmeria(io.netty.handler.codec.http.HttpHeaders inHeaders, HttpHeadersBuilder out) { final Iterator<Entry<CharSequence, CharSequence>> iter = inHeaders.iteratorCharSequence(); // Choose 8 as a default size because it is unlikely we will see more than 4 Connection headers values, // but still allowing for "enough" space in the map to reduce the chance of hash code collision. final CharSequenceMap connectionBlacklist = toLowercaseMap(inHeaders.valueCharSequenceIterator(HttpHeaderNames.CONNECTION), 8); StringJoiner cookieJoiner = null; while (iter.hasNext()) { final Entry<CharSequence, CharSequence> entry = iter.next(); final AsciiString aName = HttpHeaderNames.of(entry.getKey()).toLowerCase(); if (HTTP_TO_HTTP2_HEADER_BLACKLIST.contains(aName) || connectionBlacklist.contains(aName)) { continue; } // https://tools.ietf.org/html/rfc7540#section-8.1.2.2 makes a special exception for TE if (aName.equals(HttpHeaderNames.TE)) { toHttp2HeadersFilterTE(entry, out); continue; } // Cookies must be concatenated into a single octet string. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 final CharSequence value = entry.getValue(); if (aName.equals(HttpHeaderNames.COOKIE)) { if (cookieJoiner == null) { cookieJoiner = new StringJoiner(COOKIE_SEPARATOR); } COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add); } else { out.add(aName, convertHeaderValue(aName, value)); } } if (cookieJoiner != null && cookieJoiner.length() != 0) { out.add(HttpHeaderNames.COOKIE, cookieJoiner.toString()); } } private static CharSequenceMap toLowercaseMap(Iterator<? extends CharSequence> valuesIter, int arraySizeHint) { final CharSequenceMap result = new CharSequenceMap(arraySizeHint); while (valuesIter.hasNext()) { // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') // final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase(); // FIXED: final AsciiString lowerCased = AsciiString.of(valuesIter.next()).toLowerCase(); try { int index = lowerCased.forEachByte(FIND_COMMA); if (index != -1) { int start = 0; do { result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING); start = index + 1; } while (start < lowerCased.length() && (index = lowerCased.forEachByte(start, lowerCased.length() - start, FIND_COMMA)) != -1); result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING); } else { result.add(lowerCased.trim(), EMPTY_STRING); } } catch (Exception e) { // This is not expect to happen because FIND_COMMA never throws but must be caught // because of the ByteProcessor interface. throw new IllegalStateException(e); } } return result; } /** * Filter the {@link HttpHeaderNames#TE} header according to the * <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.2">special rules in the HTTP/2 RFC</a>. * @param entry An entry whose name is {@link HttpHeaderNames#TE}. * @param out the resulting HTTP/2 headers. */ private static void toHttp2HeadersFilterTE(Entry<CharSequence, CharSequence> entry, HttpHeadersBuilder out) { if (AsciiString.indexOf(entry.getValue(), ',', 0) == -1) { if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(entry.getValue()), HttpHeaderValues.TRAILERS)) { out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString()); } } else { final List<CharSequence> teValues = StringUtil.unescapeCsvFields(entry.getValue()); for (CharSequence teValue : teValues) { if (AsciiString.contentEqualsIgnoreCase(AsciiString.trim(teValue), HttpHeaderValues.TRAILERS)) { out.add(HttpHeaderNames.TE, HttpHeaderValues.TRAILERS.toString()); break; } } } } private static URI toUri(HttpRequest in) throws URISyntaxException { final String uri = in.uri(); if (uri.startsWith("//")) { // Normalize the path that starts with more than one slash into the one with a single slash, // so that java.net.URI does not raise a URISyntaxException. for (int i = 0; i < uri.length(); i++) { if (uri.charAt(i) != '/') { return new URI(uri.substring(i - 1)); } } return ROOT; } else { return new URI(uri); } } /** * Generate a HTTP/2 {code :path} from a URI in accordance with * <a href="https://tools.ietf.org/html/rfc7230#section-5.3">rfc7230, 5.3</a>. */ private static String toHttp2Path(URI uri) { final StringBuilder pathBuilder = new StringBuilder( length(uri.getRawPath()) + length(uri.getRawQuery()) + length(uri.getRawFragment()) + 2); if (!isNullOrEmpty(uri.getRawPath())) { pathBuilder.append(uri.getRawPath()); } if (!isNullOrEmpty(uri.getRawQuery())) { pathBuilder.append('?'); pathBuilder.append(uri.getRawQuery()); } if (!isNullOrEmpty(uri.getRawFragment())) { pathBuilder.append('#'); pathBuilder.append(uri.getRawFragment()); } return pathBuilder.length() != 0 ? pathBuilder.toString() : EMPTY_REQUEST_PATH; } @VisibleForTesting static void addHttp2Authority(@Nullable String authority, RequestHeadersBuilder out) { // The authority MUST NOT include the deprecated "userinfo" subcomponent if (authority != null) { final String actualAuthority; if (authority.isEmpty()) { actualAuthority = ""; } else { final int start = authority.indexOf('@') + 1; if (start == 0) { actualAuthority = authority; } else if (authority.length() == start) { throw new IllegalArgumentException("authority: " + authority); } else { actualAuthority = authority.substring(start); } } out.add(HttpHeaderNames.AUTHORITY, actualAuthority); } } private static void addHttp2Scheme(io.netty.handler.codec.http.HttpHeaders in, URI uri, RequestHeadersBuilder out) { final String value = uri.getScheme(); if (value != null) { out.add(HttpHeaderNames.SCHEME, value); return; } // Consume the Scheme extension header if present final CharSequence cValue = in.get(ExtensionHeaderNames.SCHEME.text()); if (cValue != null) { out.add(HttpHeaderNames.SCHEME, cValue.toString()); } else { out.add(HttpHeaderNames.SCHEME, "unknown"); } } /** * Converts the specified Armeria HTTP/2 headers into Netty HTTP/2 headers. */ public static Http2Headers toNettyHttp2(HttpHeaders in, boolean server) { final Http2Headers out = new DefaultHttp2Headers(false, in.size()); // Trailers if it does not have :status. if (server && !in.contains(HttpHeaderNames.STATUS)) { for (Entry<AsciiString, String> entry : in) { final AsciiString name = entry.getKey(); final String value = entry.getValue(); if (name.isEmpty() || isTrailerBlacklisted(name)) { continue; } out.add(name, value); } } else { in.forEach((BiConsumer<AsciiString, String>) out::add); out.remove(HttpHeaderNames.CONNECTION); out.remove(HttpHeaderNames.TRANSFER_ENCODING); } if (!out.contains(HttpHeaderNames.COOKIE)) { return out; } // Split up cookies to allow for better compression. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 final List<CharSequence> cookies = out.getAllAndRemove(HttpHeaderNames.COOKIE); for (CharSequence c : cookies) { out.add(HttpHeaderNames.COOKIE, COOKIE_SPLITTER.split(c)); } return out; } /** * Translate and add HTTP/2 headers to HTTP/1.x headers. * * @param streamId The stream associated with {@code sourceHeaders}. * @param inputHeaders The HTTP/2 headers to convert. * @param outputHeaders The object which will contain the resulting HTTP/1.x headers.. * @param httpVersion What HTTP/1.x version {@code outputHeaders} should be treated as * when doing the conversion. * @param isTrailer {@code true} if {@code outputHeaders} should be treated as trailers. * {@code false} otherwise. * @param isRequest {@code true} if the {@code outputHeaders} will be used in a request message. * {@code false} for response message. * * @throws Http2Exception If not all HTTP/2 headers can be translated to HTTP/1.x. */ public static void toNettyHttp1( int streamId, HttpHeaders inputHeaders, io.netty.handler.codec.http.HttpHeaders outputHeaders, HttpVersion httpVersion, boolean isTrailer, boolean isRequest) throws Http2Exception { final CharSequenceMap translations = isRequest ? REQUEST_HEADER_TRANSLATIONS : RESPONSE_HEADER_TRANSLATIONS; StringJoiner cookieJoiner = null; try { for (Entry<AsciiString, String> entry : inputHeaders) { final AsciiString name = entry.getKey(); final String value = entry.getValue(); final AsciiString translatedName = translations.get(name); if (translatedName != null && !inputHeaders.contains(translatedName)) { outputHeaders.add(translatedName, value); continue; } if (name.isEmpty() || HTTP2_TO_HTTP_HEADER_BLACKLIST.contains(name)) { continue; } if (isTrailer && isTrailerBlacklisted(name)) { continue; } if (HttpHeaderNames.COOKIE.equals(name)) { // combine the cookie values into 1 header entry. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 if (cookieJoiner == null) { cookieJoiner = new StringJoiner(COOKIE_SEPARATOR); } COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add); } else { outputHeaders.add(name, value); } } if (cookieJoiner != null && cookieJoiner.length() != 0) { outputHeaders.add(HttpHeaderNames.COOKIE, cookieJoiner.toString()); } } catch (Throwable t) { throw streamError(streamId, PROTOCOL_ERROR, t, "HTTP/2 to HTTP/1.x headers conversion error"); } if (!isTrailer) { HttpUtil.setKeepAlive(outputHeaders, httpVersion, true); } } /** * Returns a {@link ResponseHeaders} whose {@link HttpHeaderNames#CONTENT_LENGTH} is added or removed * according to the status of the specified {@code headers}, {@code content} and {@code trailers}. * The {@link HttpHeaderNames#CONTENT_LENGTH} is removed when: * <ul> * <li>the status of the specified {@code headers} is one of informational headers, * {@link HttpStatus#NO_CONTENT} or {@link HttpStatus#RESET_CONTENT}</li> * <li>the trailers exists</li> * </ul> * The {@link HttpHeaderNames#CONTENT_LENGTH} is added when the state of the specified {@code headers} * does not meet the conditions above and {@link HttpHeaderNames#CONTENT_LENGTH} is not present * regardless of the fact that the content is empty or not. * * @throws IllegalArgumentException if the specified {@code content} or {@code trailers} are * non-empty when the content is always empty */ public static ResponseHeaders setOrRemoveContentLength(ResponseHeaders headers, HttpData content, HttpHeaders trailers) { requireNonNull(headers, "headers"); requireNonNull(content, "content"); requireNonNull(trailers, "trailers"); final HttpStatus status = headers.status(); if (isContentAlwaysEmptyWithValidation(status, content, trailers)) { if (status != HttpStatus.NOT_MODIFIED) { if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { final ResponseHeadersBuilder builder = headers.toBuilder(); builder.remove(HttpHeaderNames.CONTENT_LENGTH); return builder.build(); } } else { // 304 response can have the "content-length" header when it is a response to a conditional // GET request. See https://tools.ietf.org/html/rfc7230#section-3.3.2 } return headers; } if (!trailers.isEmpty()) { // Some of the client implementations such as "curl" ignores trailers if // the "content-length" header is present. We should not set "content-length" header when // trailers exists so that those clients can receive the trailers. // The response is sent using chunked transfer encoding in HTTP/1 or a DATA frame payload // in HTTP/2, so it's no worry. if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { final ResponseHeadersBuilder builder = headers.toBuilder(); builder.remove(HttpHeaderNames.CONTENT_LENGTH); return builder.build(); } return headers; } if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH) || !content.isEmpty()) { return headers.toBuilder() .setInt(HttpHeaderNames.CONTENT_LENGTH, content.length()) .build(); } // The header contains "content-length" header and the content is empty. // Do not overwrite the header because a response to a HEAD request // will have no content even if it has non-zero content-length header. return headers; } private static String convertHeaderValue(AsciiString name, CharSequence value) { if (!(value instanceof AsciiString)) { return value.toString(); } if (HEADER_VALUE_CACHE != null && CACHED_HEADERS.contains(name)) { final String converted = HEADER_VALUE_CACHE.get((AsciiString) value); assert converted != null; // loader does not return null. return converted; } return value.toString(); } /** * Returns {@code true} if the specified header name is not allowed for HTTP tailers. */ public static boolean isTrailerBlacklisted(AsciiString name) { return HTTP_TRAILER_BLACKLIST.contains(name); } private static final class CharSequenceMap extends DefaultHeaders<AsciiString, AsciiString, CharSequenceMap> { CharSequenceMap() { super(HTTP2_HEADER_NAME_HASHER, UnsupportedValueConverter.instance()); } @SuppressWarnings("unchecked") CharSequenceMap(int size) { super(HTTP2_HEADER_NAME_HASHER, UnsupportedValueConverter.instance(), NameValidator.NOT_NULL, size); } } private ArmeriaHttpUtil() {}}
data/java/AuthenticationProcessingFilter2.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Matthew R. Harrah * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */package hudson.security;import java.util.Properties;import java.util.logging.Logger;import java.util.logging.Level;import java.io.IOException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import hudson.Util;import org.acegisecurity.Authentication;import org.acegisecurity.AuthenticationException;import org.acegisecurity.ui.webapp.AuthenticationProcessingFilter;/** * {@link AuthenticationProcessingFilter} with a change for Jenkins so that * we can pick up the hidden "from" form field defined in <tt>login.jelly</tt> * to send the user back to where he came from, after a successful authentication. * * @author Kohsuke Kawaguchi */public class AuthenticationProcessingFilter2 extends AuthenticationProcessingFilter { @Override protected String determineTargetUrl(HttpServletRequest request) { String targetUrl = request.getParameter("from"); request.getSession().setAttribute("from", targetUrl); if (targetUrl == null) return getDefaultTargetUrl(); if (Util.isAbsoluteUri(targetUrl)) return "."; // avoid open redirect // URL returned from determineTargetUrl() is resolved against the context path, // whereas the "from" URL is resolved against the top of the website, so adjust this. if(targetUrl.startsWith(request.getContextPath())) return targetUrl.substring(request.getContextPath().length()); // not sure when this happens, but apparently this happens in some case. // see #1274 return targetUrl; } /** * @see org.acegisecurity.ui.AbstractProcessingFilter#determineFailureUrl(javax.servlet.http.HttpServletRequest, org.acegisecurity.AuthenticationException) */ @Override protected String determineFailureUrl(HttpServletRequest request, AuthenticationException failed) { Properties excMap = getExceptionMappings(); String failedClassName = failed.getClass().getName(); String whereFrom = request.getParameter("from"); request.getSession().setAttribute("from", whereFrom); return excMap.getProperty(failedClassName, getAuthenticationFailureUrl()); } @Override protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException { super.onSuccessfulAuthentication(request,response,authResult); // make sure we have a session to store this successful authentication, given that we no longer // let HttpSessionContextIntegrationFilter2 to create sessions. // HttpSessionContextIntegrationFilter stores the updated SecurityContext object into this session later // (either when a redirect is issued, via its HttpResponseWrapper, or when the execution returns to its // doFilter method. // BUG: CWE-287 Improper Authentication // // FIXED: request.getSession().invalidate(); request.getSession(); } /** * Leave the information about login failure. * * <p> * Otherwise it seems like Acegi doesn't really leave the detail of the failure anywhere. */ @Override protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException { super.onUnsuccessfulAuthentication(request, response, failed); LOGGER.log(Level.INFO, "Login attempt failed", failed); } private static final Logger LOGGER = Logger.getLogger(AuthenticationProcessingFilter2.class.getName());}
data/java/BCXMSSMTPrivateKey.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ package org.bouncycastle.pqc.jcajce.provider.xmss;import java.io.IOException;import java.security.PrivateKey;import org.bouncycastle.asn1.ASN1ObjectIdentifier;import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;import org.bouncycastle.asn1.x509.AlgorithmIdentifier;import org.bouncycastle.crypto.CipherParameters;import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers;import org.bouncycastle.pqc.asn1.XMSSMTKeyParams;import org.bouncycastle.pqc.asn1.XMSSMTPrivateKey;import org.bouncycastle.pqc.asn1.XMSSPrivateKey;import org.bouncycastle.pqc.crypto.xmss.BDSStateMap;import org.bouncycastle.pqc.crypto.xmss.XMSSMTParameters;import org.bouncycastle.pqc.crypto.xmss.XMSSMTPrivateKeyParameters;import org.bouncycastle.pqc.crypto.xmss.XMSSUtil;import org.bouncycastle.pqc.jcajce.interfaces.XMSSMTKey;import org.bouncycastle.util.Arrays;public class BCXMSSMTPrivateKey implements PrivateKey, XMSSMTKey{ private final ASN1ObjectIdentifier treeDigest; private final XMSSMTPrivateKeyParameters keyParams; public BCXMSSMTPrivateKey( ASN1ObjectIdentifier treeDigest, XMSSMTPrivateKeyParameters keyParams) { this.treeDigest = treeDigest; this.keyParams = keyParams; } public BCXMSSMTPrivateKey(PrivateKeyInfo keyInfo) throws IOException { XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters()); this.treeDigest = keyParams.getTreeDigest().getAlgorithm(); XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey()); try { XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters .Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest))) .withIndex(xmssMtPrivateKey.getIndex()) .withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed()) .withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF()) .withPublicSeed(xmssMtPrivateKey.getPublicSeed()) .withRoot(xmssMtPrivateKey.getRoot()); if (xmssMtPrivateKey.getBdsState() != null) { // BUG: CWE-470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') // keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState())); // FIXED: keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState(), BDSStateMap.class)); } this.keyParams = keyBuilder.build(); } catch (ClassNotFoundException e) { throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage()); } } public String getAlgorithm() { return "XMSSMT"; } public String getFormat() { return "PKCS#8"; } public byte[] getEncoded() { PrivateKeyInfo pki; try { AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss_mt, new XMSSMTKeyParams(keyParams.getParameters().getHeight(), keyParams.getParameters().getLayers(), new AlgorithmIdentifier(treeDigest))); pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure()); return pki.getEncoded(); } catch (IOException e) { return null; } } CipherParameters getKeyParams() { return keyParams; } public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof BCXMSSMTPrivateKey) { BCXMSSMTPrivateKey otherKey = (BCXMSSMTPrivateKey)o; return treeDigest.equals(otherKey.treeDigest) && Arrays.areEqual(keyParams.toByteArray(), otherKey.keyParams.toByteArray()); } return false; } public int hashCode() { return treeDigest.hashCode() + 37 * Arrays.hashCode(keyParams.toByteArray()); } private XMSSMTPrivateKey createKeyStructure() { byte[] keyData = keyParams.toByteArray(); int n = keyParams.getParameters().getDigestSize(); int totalHeight = keyParams.getParameters().getHeight(); int indexSize = (totalHeight + 7) / 8; int secretKeySize = n; int secretKeyPRFSize = n; int publicSeedSize = n; int rootSize = n; int position = 0; int index = (int)XMSSUtil.bytesToXBigEndian(keyData, position, indexSize); if (!XMSSUtil.isIndexValid(totalHeight, index)) { throw new IllegalArgumentException("index out of bounds"); } position += indexSize; byte[] secretKeySeed = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeySize); position += secretKeySize; byte[] secretKeyPRF = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeyPRFSize); position += secretKeyPRFSize; byte[] publicSeed = XMSSUtil.extractBytesAtOffset(keyData, position, publicSeedSize); position += publicSeedSize; byte[] root = XMSSUtil.extractBytesAtOffset(keyData, position, rootSize); position += rootSize; /* import BDS state */ byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(keyData, position, keyData.length - position); return new XMSSMTPrivateKey(index, secretKeySeed, secretKeyPRF, publicSeed, root, bdsStateBinary); } ASN1ObjectIdentifier getTreeDigestOID() { return treeDigest; } public int getHeight() { return keyParams.getParameters().getHeight(); } public int getLayers() { return keyParams.getParameters().getLayers(); } public String getTreeDigest() { return DigestUtil.getXMSSDigestName(treeDigest); }}
data/java/BCXMSSPrivateKey.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ package org.bouncycastle.pqc.jcajce.provider.xmss;import java.io.IOException;import java.security.PrivateKey;import org.bouncycastle.asn1.ASN1ObjectIdentifier;import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;import org.bouncycastle.asn1.x509.AlgorithmIdentifier;import org.bouncycastle.crypto.CipherParameters;import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers;import org.bouncycastle.pqc.asn1.XMSSKeyParams;import org.bouncycastle.pqc.asn1.XMSSPrivateKey;import org.bouncycastle.pqc.crypto.xmss.BDS;import org.bouncycastle.pqc.crypto.xmss.XMSSParameters;import org.bouncycastle.pqc.crypto.xmss.XMSSPrivateKeyParameters;import org.bouncycastle.pqc.crypto.xmss.XMSSUtil;import org.bouncycastle.pqc.jcajce.interfaces.XMSSKey;import org.bouncycastle.util.Arrays;public class BCXMSSPrivateKey implements PrivateKey, XMSSKey{ private final XMSSPrivateKeyParameters keyParams; private final ASN1ObjectIdentifier treeDigest; public BCXMSSPrivateKey( ASN1ObjectIdentifier treeDigest, XMSSPrivateKeyParameters keyParams) { this.treeDigest = treeDigest; this.keyParams = keyParams; } public BCXMSSPrivateKey(PrivateKeyInfo keyInfo) throws IOException { XMSSKeyParams keyParams = XMSSKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters()); this.treeDigest = keyParams.getTreeDigest().getAlgorithm(); XMSSPrivateKey xmssPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey()); try { XMSSPrivateKeyParameters.Builder keyBuilder = new XMSSPrivateKeyParameters .Builder(new XMSSParameters(keyParams.getHeight(), DigestUtil.getDigest(treeDigest))) .withIndex(xmssPrivateKey.getIndex()) .withSecretKeySeed(xmssPrivateKey.getSecretKeySeed()) .withSecretKeyPRF(xmssPrivateKey.getSecretKeyPRF()) .withPublicSeed(xmssPrivateKey.getPublicSeed()) .withRoot(xmssPrivateKey.getRoot()); if (xmssPrivateKey.getBdsState() != null) { // BUG: CWE-470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') // keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState())); // FIXED: keyBuilder.withBDSState((BDS)XMSSUtil.deserialize(xmssPrivateKey.getBdsState(), BDS.class)); } this.keyParams = keyBuilder.build(); } catch (ClassNotFoundException e) { throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage()); } } public String getAlgorithm() { return "XMSS"; } public String getFormat() { return "PKCS#8"; } public byte[] getEncoded() { PrivateKeyInfo pki; try { AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss, new XMSSKeyParams(keyParams.getParameters().getHeight(), new AlgorithmIdentifier(treeDigest))); pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure()); return pki.getEncoded(); } catch (IOException e) { return null; } } public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof BCXMSSPrivateKey) { BCXMSSPrivateKey otherKey = (BCXMSSPrivateKey)o; return treeDigest.equals(otherKey.treeDigest) && Arrays.areEqual(keyParams.toByteArray(), otherKey.keyParams.toByteArray()); } return false; } public int hashCode() { return treeDigest.hashCode() + 37 * Arrays.hashCode(keyParams.toByteArray()); } CipherParameters getKeyParams() { return keyParams; } private XMSSPrivateKey createKeyStructure() { byte[] keyData = keyParams.toByteArray(); int n = keyParams.getParameters().getDigestSize(); int totalHeight = keyParams.getParameters().getHeight(); int indexSize = 4; int secretKeySize = n; int secretKeyPRFSize = n; int publicSeedSize = n; int rootSize = n; int position = 0; int index = (int)XMSSUtil.bytesToXBigEndian(keyData, position, indexSize); if (!XMSSUtil.isIndexValid(totalHeight, index)) { throw new IllegalArgumentException("index out of bounds"); } position += indexSize; byte[] secretKeySeed = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeySize); position += secretKeySize; byte[] secretKeyPRF = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeyPRFSize); position += secretKeyPRFSize; byte[] publicSeed = XMSSUtil.extractBytesAtOffset(keyData, position, publicSeedSize); position += publicSeedSize; byte[] root = XMSSUtil.extractBytesAtOffset(keyData, position, rootSize); position += rootSize; /* import BDS state */ byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(keyData, position, keyData.length - position); return new XMSSPrivateKey(index, secretKeySeed, secretKeyPRF, publicSeed, root, bdsStateBinary); } ASN1ObjectIdentifier getTreeDigestOID() { return treeDigest; } public int getHeight() { return keyParams.getParameters().getHeight(); } public String getTreeDigest() { return DigestUtil.getXMSSDigestName(treeDigest); }}
data/java/BackendManagerTest.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ package org.jolokia.backend;/* * Copyright 2009-2013 Roland Huss * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */import java.io.IOException;import java.util.Map;import javax.management.*;import org.jolokia.backend.executor.NotChangedException;import org.jolokia.config.ConfigKey;import org.jolokia.config.Configuration;import org.jolokia.converter.Converters;import org.jolokia.detector.ServerHandle;import org.jolokia.request.JmxRequest;import org.jolokia.request.JmxRequestBuilder;import org.jolokia.restrictor.Restrictor;import org.jolokia.util.*;import org.json.simple.JSONObject;import org.testng.annotations.BeforeTest;import org.testng.annotations.Test;import static org.testng.Assert.*;/** * @author roland * @since Jun 15, 2010 */public class BackendManagerTest { Configuration config; private LogHandler log = new LogHandler.StdoutLogHandler(true); @BeforeTest public void setup() { config = new Configuration(ConfigKey.AGENT_ID,"test"); } @Test public void simpleRead() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { Configuration config = new Configuration(ConfigKey.DEBUG,"true",ConfigKey.AGENT_ID,"test"); BackendManager backendManager = new BackendManager(config, log); JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory") .attribute("HeapMemoryUsage") .build(); JSONObject ret = backendManager.handleRequest(req); assertTrue((Long) ((Map) ret.get("value")).get("used") > 0); backendManager.destroy(); } @Test public void notChanged() throws MalformedObjectNameException, MBeanException, AttributeNotFoundException, ReflectionException, InstanceNotFoundException, IOException { Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherTest.class.getName(),ConfigKey.AGENT_ID,"test"); BackendManager backendManager = new BackendManager(config, log); JmxRequest req = new JmxRequestBuilder(RequestType.LIST).build(); JSONObject ret = backendManager.handleRequest(req); assertEquals(ret.get("status"),304); backendManager.destroy(); } @Test public void lazyInit() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { BackendManager backendManager = new BackendManager(config, log, null, true /* Lazy Init */ ); JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory") .attribute("HeapMemoryUsage") .build(); JSONObject ret = backendManager.handleRequest(req); assertTrue((Long) ((Map) ret.get("value")).get("used") > 0); backendManager.destroy(); } @Test public void requestDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherTest.class.getName(),ConfigKey.AGENT_ID,"test"); BackendManager backendManager = new BackendManager(config, log); JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build(); backendManager.handleRequest(req); assertTrue(RequestDispatcherTest.called); backendManager.destroy(); } @Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*invalid constructor.*") public void requestDispatcherWithWrongDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,RequestDispatcherWrong.class.getName(),ConfigKey.AGENT_ID,"test"); new BackendManager(config,log); } @Test(expectedExceptions = IllegalArgumentException.class,expectedExceptionsMessageRegExp = ".*blub.bla.Dispatcher.*") public void requestDispatcherWithUnkownDispatcher() throws MalformedObjectNameException, InstanceNotFoundException, IOException, ReflectionException, AttributeNotFoundException, MBeanException { Configuration config = new Configuration(ConfigKey.DISPATCHER_CLASSES,"blub.bla.Dispatcher",ConfigKey.AGENT_ID,"test"); new BackendManager(config,log); } @Test public void debugging() { RecordingLogHandler lhandler = new RecordingLogHandler(); BackendManager backendManager = new BackendManager(config,lhandler); lhandler.error = 0; lhandler.debug = 0; lhandler.info = 0; backendManager.debug("test"); assertEquals(lhandler.debug,1); backendManager.error("test",new Exception()); assertEquals(lhandler.error,1); backendManager.info("test"); assertEquals(lhandler.info,1); backendManager.destroy(); } @Test public void defaultConfig() { Configuration config = new Configuration(ConfigKey.DEBUG_MAX_ENTRIES,"blabal",ConfigKey.AGENT_ID,"test"); BackendManager backendManager = new BackendManager(config,log); backendManager.destroy(); } @Test public void doubleInit() { BackendManager b1 = new BackendManager(config,log); BackendManager b2 = new BackendManager(config,log); b2.destroy(); b1.destroy(); } @Test public void remoteAccessCheck() { BackendManager backendManager = new BackendManager(config,log); assertTrue(backendManager.isRemoteAccessAllowed("localhost","127.0.0.1")); backendManager.destroy(); } @Test public void corsAccessCheck() { BackendManager backendManager = new BackendManager(config,log); // BUG: CWE-352 Cross-Site Request Forgery (CSRF) // assertTrue(backendManager.isCorsAccessAllowed("http://bla.com")); // FIXED: assertTrue(backendManager.isOriginAllowed("http://bla.com",false)); backendManager.destroy(); } @Test public void convertError() throws MalformedObjectNameException { BackendManager backendManager = new BackendManager(config,log); Exception exp = new IllegalArgumentException("Hans",new IllegalStateException("Kalb")); JmxRequest req = new JmxRequestBuilder(RequestType.READ,"java.lang:type=Memory").build(); JSONObject jsonError = (JSONObject) backendManager.convertExceptionToJson(exp,req); assertTrue(!jsonError.containsKey("stackTrace")); assertEquals(jsonError.get("message"),"Hans"); assertEquals(((JSONObject) jsonError.get("cause")).get("message"),"Kalb"); backendManager.destroy(); } // ========================================================================================= static class RequestDispatcherTest implements RequestDispatcher { static boolean called = false; public RequestDispatcherTest(Converters pConverters,ServerHandle pServerHandle,Restrictor pRestrictor) { assertNotNull(pConverters); assertNotNull(pRestrictor); } public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException, NotChangedException { called = true; if (pJmxReq.getType() == RequestType.READ) { return new JSONObject(); } else if (pJmxReq.getType() == RequestType.WRITE) { return "faultyFormat"; } else if (pJmxReq.getType() == RequestType.LIST) { throw new NotChangedException(pJmxReq); } return null; } public boolean canHandle(JmxRequest pJmxRequest) { return true; } public boolean useReturnValueWithPath(JmxRequest pJmxRequest) { return false; } } // ======================================================== static class RequestDispatcherWrong implements RequestDispatcher { // No special constructor --> fail public Object dispatchRequest(JmxRequest pJmxReq) throws InstanceNotFoundException, AttributeNotFoundException, ReflectionException, MBeanException, IOException { return null; } public boolean canHandle(JmxRequest pJmxRequest) { return false; } public boolean useReturnValueWithPath(JmxRequest pJmxRequest) { return false; } } private class RecordingLogHandler implements LogHandler { int debug = 0; int info = 0; int error = 0; public void debug(String message) { debug++; } public void info(String message) { info++; } public void error(String message, Throwable t) { error++; } }}
data/java/BedrockActionTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock.entity.player;import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;import com.github.steveice10.mc.protocol.data.game.entity.player.*;import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;import com.github.steveice10.mc.protocol.packet.ingame.client.player.*;import com.nukkitx.math.vector.Vector3f;import com.nukkitx.math.vector.Vector3i;import com.nukkitx.protocol.bedrock.data.LevelEventType;import com.nukkitx.protocol.bedrock.data.PlayerActionType;import com.nukkitx.protocol.bedrock.data.entity.EntityEventType;import com.nukkitx.protocol.bedrock.data.entity.EntityFlag;import com.nukkitx.protocol.bedrock.packet.*;import org.geysermc.connector.entity.Entity;import org.geysermc.connector.entity.ItemFrameEntity;import org.geysermc.connector.entity.player.SessionPlayerEntity;import org.geysermc.connector.inventory.PlayerInventory;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.network.translators.world.block.BlockStateValues;import org.geysermc.connector.registry.BlockRegistries;import org.geysermc.connector.registry.type.ItemMapping;import org.geysermc.connector.utils.BlockUtils;import java.util.ArrayList;@Translator(packet = PlayerActionPacket.class)public class BedrockActionTranslator extends PacketTranslator<PlayerActionPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(PlayerActionPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, PlayerActionPacket packet) { SessionPlayerEntity entity = session.getPlayerEntity(); // Send book update before any player action if (packet.getAction() != PlayerActionType.RESPAWN) { session.getBookEditCache().checkForSend(); } Vector3i vector = packet.getBlockPosition(); Position position = new Position(vector.getX(), vector.getY(), vector.getZ()); switch (packet.getAction()) { case RESPAWN: // Respawn process is finished and the server and client are both OK with respawning. EntityEventPacket eventPacket = new EntityEventPacket(); eventPacket.setRuntimeEntityId(entity.getGeyserId()); eventPacket.setType(EntityEventType.RESPAWN); eventPacket.setData(0); session.sendUpstreamPacket(eventPacket); // Resend attributes or else in rare cases the user can think they're not dead when they are, upon joining the server UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket(); attributesPacket.setRuntimeEntityId(entity.getGeyserId()); attributesPacket.setAttributes(new ArrayList<>(entity.getAttributes().values())); session.sendUpstreamPacket(attributesPacket); break; case START_SWIMMING: ClientPlayerStatePacket startSwimPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SPRINTING); session.sendDownstreamPacket(startSwimPacket); session.setSwimming(true); break; case STOP_SWIMMING: ClientPlayerStatePacket stopSwimPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.STOP_SPRINTING); session.sendDownstreamPacket(stopSwimPacket); session.setSwimming(false); break; case START_GLIDE: // Otherwise gliding will not work in creative ClientPlayerAbilitiesPacket playerAbilitiesPacket = new ClientPlayerAbilitiesPacket(false); session.sendDownstreamPacket(playerAbilitiesPacket); case STOP_GLIDE: ClientPlayerStatePacket glidePacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_ELYTRA_FLYING); session.sendDownstreamPacket(glidePacket); break; case START_SNEAK: ClientPlayerStatePacket startSneakPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SNEAKING); session.sendDownstreamPacket(startSneakPacket); // Toggle the shield, if relevant PlayerInventory playerInv = session.getPlayerInventory(); ItemMapping shield = session.getItemMappings().getMapping("minecraft:shield"); if ((playerInv.getItemInHand().getJavaId() == shield.getJavaId()) || (playerInv.getOffhand().getJavaId() == shield.getJavaId())) { ClientPlayerUseItemPacket useItemPacket; if (playerInv.getItemInHand().getJavaId() == shield.getJavaId()) { useItemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); } else { // Else we just assume it's the offhand, to simplify logic and to assure the packet gets sent useItemPacket = new ClientPlayerUseItemPacket(Hand.OFF_HAND); } session.sendDownstreamPacket(useItemPacket); session.getPlayerEntity().getMetadata().getFlags().setFlag(EntityFlag.BLOCKING, true); // metadata will be updated when sneaking } session.setSneaking(true); break; case STOP_SNEAK: ClientPlayerStatePacket stopSneakPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.STOP_SNEAKING); session.sendDownstreamPacket(stopSneakPacket); // Stop shield, if necessary if (session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.BLOCKING)) { ClientPlayerActionPacket releaseItemPacket = new ClientPlayerActionPacket(PlayerAction.RELEASE_USE_ITEM, BlockUtils.POSITION_ZERO, BlockFace.DOWN); session.sendDownstreamPacket(releaseItemPacket); session.getPlayerEntity().getMetadata().getFlags().setFlag(EntityFlag.BLOCKING, false); // metadata will be updated when sneaking } session.setSneaking(false); break; case START_SPRINT: ClientPlayerStatePacket startSprintPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SPRINTING); session.sendDownstreamPacket(startSprintPacket); session.setSprinting(true); break; case STOP_SPRINT: ClientPlayerStatePacket stopSprintPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.STOP_SPRINTING); session.sendDownstreamPacket(stopSprintPacket); session.setSprinting(false); break; case DROP_ITEM: ClientPlayerActionPacket dropItemPacket = new ClientPlayerActionPacket(PlayerAction.DROP_ITEM, position, BlockFace.values()[packet.getFace()]); session.sendDownstreamPacket(dropItemPacket); break; case STOP_SLEEP: ClientPlayerStatePacket stopSleepingPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.LEAVE_BED); session.sendDownstreamPacket(stopSleepingPacket); break; case BLOCK_INTERACT: // Client means to interact with a block; cancel bucket interaction, if any if (session.getBucketScheduledFuture() != null) { session.getBucketScheduledFuture().cancel(true); session.setBucketScheduledFuture(null); } // Otherwise handled in BedrockInventoryTransactionTranslator break; case START_BREAK: // Start the block breaking animation if (session.getGameMode() != GameMode.CREATIVE) { int blockState = session.getConnector().getWorldManager().getBlockAt(session, vector); LevelEventPacket startBreak = new LevelEventPacket(); startBreak.setType(LevelEventType.BLOCK_START_BREAK); startBreak.setPosition(vector.toFloat()); double breakTime = BlockUtils.getSessionBreakTime(session, BlockRegistries.JAVA_BLOCKS.get(blockState)) * 20; startBreak.setData((int) (65535 / breakTime)); session.setBreakingBlock(blockState); session.sendUpstreamPacket(startBreak); } // Account for fire - the client likes to hit the block behind. Vector3i fireBlockPos = BlockUtils.getBlockPosition(packet.getBlockPosition(), packet.getFace()); int blockUp = session.getConnector().getWorldManager().getBlockAt(session, fireBlockPos); String identifier = BlockRegistries.JAVA_IDENTIFIERS.get().get(blockUp); if (identifier.startsWith("minecraft:fire") || identifier.startsWith("minecraft:soul_fire")) { ClientPlayerActionPacket startBreakingPacket = new ClientPlayerActionPacket(PlayerAction.START_DIGGING, new Position(fireBlockPos.getX(), fireBlockPos.getY(), fireBlockPos.getZ()), BlockFace.values()[packet.getFace()]); session.sendDownstreamPacket(startBreakingPacket); if (session.getGameMode() == GameMode.CREATIVE) { break; } } ClientPlayerActionPacket startBreakingPacket = new ClientPlayerActionPacket(PlayerAction.START_DIGGING, position, BlockFace.values()[packet.getFace()]); session.sendDownstreamPacket(startBreakingPacket); break; case CONTINUE_BREAK: if (session.getGameMode() == GameMode.CREATIVE) { break; } Vector3f vectorFloat = vector.toFloat(); LevelEventPacket continueBreakPacket = new LevelEventPacket(); continueBreakPacket.setType(LevelEventType.PARTICLE_CRACK_BLOCK); continueBreakPacket.setData((session.getBlockMappings().getBedrockBlockId(session.getBreakingBlock())) | (packet.getFace() << 24)); continueBreakPacket.setPosition(vectorFloat); session.sendUpstreamPacket(continueBreakPacket); // Update the break time in the event that player conditions changed (jumping, effects applied) LevelEventPacket updateBreak = new LevelEventPacket(); updateBreak.setType(LevelEventType.BLOCK_UPDATE_BREAK); updateBreak.setPosition(vectorFloat); double breakTime = BlockUtils.getSessionBreakTime(session, BlockRegistries.JAVA_BLOCKS.get(session.getBreakingBlock())) * 20; updateBreak.setData((int) (65535 / breakTime)); session.sendUpstreamPacket(updateBreak); break; case ABORT_BREAK: if (session.getGameMode() != GameMode.CREATIVE) { // As of 1.16.210: item frame items are taken out here. // Survival also sends START_BREAK, but by attaching our process here adventure mode also works Entity itemFrameEntity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition()); if (itemFrameEntity != null) { ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) itemFrameEntity.getEntityId(), InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking()); session.sendDownstreamPacket(interactPacket); break; } } ClientPlayerActionPacket abortBreakingPacket = new ClientPlayerActionPacket(PlayerAction.CANCEL_DIGGING, position, BlockFace.DOWN); session.sendDownstreamPacket(abortBreakingPacket); LevelEventPacket stopBreak = new LevelEventPacket(); stopBreak.setType(LevelEventType.BLOCK_STOP_BREAK); stopBreak.setPosition(vector.toFloat()); stopBreak.setData(0); session.setBreakingBlock(BlockStateValues.JAVA_AIR_ID); session.sendUpstreamPacket(stopBreak); break; case STOP_BREAK: // Handled in BedrockInventoryTransactionTranslator break; case DIMENSION_CHANGE_SUCCESS: //sometimes the client doesn't feel like loading PlayStatusPacket spawnPacket = new PlayStatusPacket(); spawnPacket.setStatus(PlayStatusPacket.Status.PLAYER_SPAWN); session.sendUpstreamPacket(spawnPacket); attributesPacket = new UpdateAttributesPacket(); attributesPacket.setRuntimeEntityId(entity.getGeyserId()); attributesPacket.setAttributes(new ArrayList<>(entity.getAttributes().values())); session.sendUpstreamPacket(attributesPacket); session.getEntityCache().updateBossBars(); break; case JUMP: entity.setOnGround(false); // Increase block break time while jumping break; } }}
data/java/BedrockAdventureSettingsTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerAbilitiesPacket;import com.nukkitx.protocol.bedrock.data.AdventureSetting;import com.nukkitx.protocol.bedrock.data.entity.EntityFlag;import com.nukkitx.protocol.bedrock.packet.AdventureSettingsPacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;@Translator(packet = AdventureSettingsPacket.class)public class BedrockAdventureSettingsTranslator extends PacketTranslator<AdventureSettingsPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(AdventureSettingsPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, AdventureSettingsPacket packet) { boolean isFlying = packet.getSettings().contains(AdventureSetting.FLYING); if (!isFlying && session.getGameMode() == GameMode.SPECTATOR) { // We should always be flying in spectator mode session.sendAdventureSettings(); return; } session.setFlying(isFlying); ClientPlayerAbilitiesPacket abilitiesPacket = new ClientPlayerAbilitiesPacket(isFlying); session.sendDownstreamPacket(abilitiesPacket); if (isFlying && session.getPlayerEntity().getMetadata().getFlags().getFlag(EntityFlag.SWIMMING)) { // Bedrock can fly and swim at the same time? Make sure that can't happen session.setSwimming(false); } }}
data/java/BedrockAnimateTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerSwingArmPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientSteerBoatPacket;import com.nukkitx.protocol.bedrock.packet.AnimatePacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import java.util.concurrent.TimeUnit;@Translator(packet = AnimatePacket.class)public class BedrockAnimateTranslator extends PacketTranslator<AnimatePacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(AnimatePacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, AnimatePacket packet) { // Stop the player sending animations before they have fully spawned into the server if (!session.isSpawned()) { return; } switch (packet.getAction()) { case SWING_ARM: // Delay so entity damage can be processed first session.scheduleInEventLoop(() -> session.sendDownstreamPacket(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND)), 25, TimeUnit.MILLISECONDS ); break; // These two might need to be flipped, but my recommendation is getting moving working first case ROW_LEFT: // Packet value is a float of how long one has been rowing, so we convert that into a boolean session.setSteeringLeft(packet.getRowingTime() > 0.0); ClientSteerBoatPacket steerLeftPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight()); session.sendDownstreamPacket(steerLeftPacket); break; case ROW_RIGHT: session.setSteeringRight(packet.getRowingTime() > 0.0); ClientSteerBoatPacket steerRightPacket = new ClientSteerBoatPacket(session.isSteeringLeft(), session.isSteeringRight()); session.sendDownstreamPacket(steerRightPacket); break; } }}
data/java/BedrockBlockEntityDataTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateJigsawBlockPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientUpdateSignPacket;import com.nukkitx.nbt.NbtMap;import com.nukkitx.protocol.bedrock.packet.BlockEntityDataPacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.utils.SignUtils;@Translator(packet = BlockEntityDataPacket.class)public class BedrockBlockEntityDataTranslator extends PacketTranslator<BlockEntityDataPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(BlockEntityDataPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, BlockEntityDataPacket packet) { NbtMap tag = packet.getData(); if (tag.getString("id").equals("Sign")) { // This is the reason why this all works - Bedrock sends packets every time you update the sign, Java only wants the final packet // But Bedrock sends one final packet when you're done editing the sign, which should be equal to the last message since there's no edits // So if the latest update does not match the last cached update then it's still being edited if (!tag.getString("Text").equals(session.getLastSignMessage())) { session.setLastSignMessage(tag.getString("Text")); return; } // Otherwise the two messages are identical and we can get to work deconstructing StringBuilder newMessage = new StringBuilder(); // While Bedrock's sign lines are one string, Java's is an array of each line // (Initialized all with empty strings because it complains about null) String[] lines = new String[] {"", "", "", ""}; int iterator = 0; // Keep track of the width of each character // If it goes over the maximum, we need to start a new line to match Java int widthCount = 0; // This converts the message into the array'd message Java wants for (char character : tag.getString("Text").toCharArray()) { widthCount += SignUtils.getCharacterWidth(character); // If we get a return in Bedrock, or go over the character width max, that signals to use the next line. if (character == '\n' || widthCount > SignUtils.JAVA_CHARACTER_WIDTH_MAX) { // We need to apply some more logic if we went over the character width max boolean wentOverMax = widthCount > SignUtils.JAVA_CHARACTER_WIDTH_MAX && character != '\n'; widthCount = 0; // Saves if we're moving a word to the next line String word = null; if (wentOverMax && iterator < lines.length - 1) { // If we went over the max, we want to try to wrap properly like Bedrock does. // So we look for a space in the Bedrock user's text to imply a word. int index = newMessage.lastIndexOf(" "); if (index != -1) { // There is indeed a space in this line; let's get it word = newMessage.substring(index + 1); // 'Delete' that word from the string builder newMessage.delete(index, newMessage.length()); } } lines[iterator] = newMessage.toString(); iterator++; // Bedrock, for whatever reason, can hold a message out of the bounds of the four lines // We don't care about that so we discard that if (iterator > lines.length - 1) { break; } newMessage = new StringBuilder(); if (wentOverMax) { // Apply the wrapped word to the new line if (word != null) { newMessage.append(word); // And apply the width count for (char wordCharacter : word.toCharArray()) { widthCount += SignUtils.getCharacterWidth(wordCharacter); } } // If we went over the max, we want to append the character to the new line. newMessage.append(character); widthCount += SignUtils.getCharacterWidth(character); } } else newMessage.append(character); } // Put the final line on since it isn't done in the for loop if (iterator < lines.length) lines[iterator] = newMessage.toString(); Position pos = new Position(tag.getInt("x"), tag.getInt("y"), tag.getInt("z")); ClientUpdateSignPacket clientUpdateSignPacket = new ClientUpdateSignPacket(pos, lines); session.sendDownstreamPacket(clientUpdateSignPacket); // We set the sign text cached in the session to null to indicate there is no work-in-progress sign session.setLastSignMessage(null); } else if (tag.getString("id").equals("JigsawBlock")) { // Client has just sent a jigsaw block update Position pos = new Position(tag.getInt("x"), tag.getInt("y"), tag.getInt("z")); String name = tag.getString("name"); String target = tag.getString("target"); String pool = tag.getString("target_pool"); String finalState = tag.getString("final_state"); String joint = tag.getString("joint"); ClientUpdateJigsawBlockPacket jigsawPacket = new ClientUpdateJigsawBlockPacket(pos, name, target, pool, finalState, joint); session.sendDownstreamPacket(jigsawPacket); } }}
data/java/BedrockBlockPickRequestTranslator.txt ADDED
@@ -0,0 +1 @@
 
0
  * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org
1
  *
2
  * Permission is hereby granted, free of charge, to any person obtaining a copy
3
  * of this software and associated documentation files (the "Software"), to deal
4
  * in the Software without restriction, including without limitation the rights
5
  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
6
  * copies of the Software, and to permit persons to whom the Software is
7
  * furnished to do so, subject to the following conditions:
8
  *
9
  * The above copyright notice and this permission notice shall be included in
10
  * all copies or substantial portions of the Software.
11
  *
12
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
18
  * THE SOFTWARE.
19
  *
20
  * @author GeyserMC
21
  * @link https://github.com/GeyserMC/Geyser
22
  */
23
  @Override
24
  // BUG: CWE-287 Improper Authentication
25
  // public void translate(BlockPickRequestPacket packet, GeyserSession session) {
26
  // FIXED:
27
  public void translate(GeyserSession session, BlockPickRequestPacket packet) {
28
  Vector3i vector = packet.getBlockPosition();
29
  int blockToPick = session.getConnector().getWorldManager().getBlockAt(session, vector.getX(), vector.getY(), vector.getZ());
30
 
31
  // Block is air - chunk caching is probably off
32
  if (blockToPick == BlockStateValues.JAVA_AIR_ID) {
33
  // Check for an item frame since the client thinks that's a block when it's an entity in Java
34
  ItemFrameEntity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
35
  if (entity != null) {
36
  // Check to see if the item frame has an item in it first
37
  if (entity.getHeldItem() != null && entity.getHeldItem().getId() != 0) {
38
  // Grab the item in the frame
39
  InventoryUtils.findOrCreateItem(session, entity.getHeldItem());
40
  } else {
41
  // Grab the frame as the item
42
  InventoryUtils.findOrCreateItem(session, entity.getEntityType() == EntityType.GLOW_ITEM_FRAME ? "minecraft:glow_item_frame" : "minecraft:item_frame");
43
  }
44
  }
45
  return;
46
  }
47
  InventoryUtils.findOrCreateItem(session, BlockRegistries.JAVA_BLOCKS.get(blockToPick).getPickItem());
48
  }
 
1
+ /*
2
  * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org
3
  *
4
  * Permission is hereby granted, free of charge, to any person obtaining a copy
5
  * of this software and associated documentation files (the "Software"), to deal
6
  * in the Software without restriction, including without limitation the rights
7
  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
  * copies of the Software, and to permit persons to whom the Software is
9
  * furnished to do so, subject to the following conditions:
10
  *
11
  * The above copyright notice and this permission notice shall be included in
12
  * all copies or substantial portions of the Software.
13
  *
14
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
  * THE SOFTWARE.
21
  *
22
  * @author GeyserMC
23
  * @link https://github.com/GeyserMC/Geyser
24
  */
25
  @Override
26
  // BUG: CWE-287 Improper Authentication
27
  // public void translate(BlockPickRequestPacket packet, GeyserSession session) {
28
  // FIXED:
29
  public void translate(GeyserSession session, BlockPickRequestPacket packet) {
30
  Vector3i vector = packet.getBlockPosition();
31
  int blockToPick = session.getConnector().getWorldManager().getBlockAt(session, vector.getX(), vector.getY(), vector.getZ());
32
 
33
  // Block is air - chunk caching is probably off
34
  if (blockToPick == BlockStateValues.JAVA_AIR_ID) {
35
  // Check for an item frame since the client thinks that's a block when it's an entity in Java
36
  ItemFrameEntity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition());
37
  if (entity != null) {
38
  // Check to see if the item frame has an item in it first
39
  if (entity.getHeldItem() != null && entity.getHeldItem().getId() != 0) {
40
  // Grab the item in the frame
41
  InventoryUtils.findOrCreateItem(session, entity.getHeldItem());
42
  } else {
43
  // Grab the frame as the item
44
  InventoryUtils.findOrCreateItem(session, entity.getEntityType() == EntityType.GLOW_ITEM_FRAME ? "minecraft:glow_item_frame" : "minecraft:item_frame");
45
  }
46
  }
47
  return;
48
  }
49
  InventoryUtils.findOrCreateItem(session, BlockRegistries.JAVA_BLOCKS.get(blockToPick).getPickItem());
50
  }
data/java/BedrockBookEditTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.data.game.entity.metadata.ItemStack;import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientEditBookPacket;import com.github.steveice10.opennbt.tag.builtin.CompoundTag;import com.github.steveice10.opennbt.tag.builtin.ListTag;import com.github.steveice10.opennbt.tag.builtin.StringTag;import com.github.steveice10.opennbt.tag.builtin.Tag;import com.nukkitx.protocol.bedrock.packet.BookEditPacket;import org.geysermc.connector.inventory.GeyserItemStack;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.Collections;import java.util.LinkedList;import java.util.List;@Translator(packet = BookEditPacket.class)public class BedrockBookEditTranslator extends PacketTranslator<BookEditPacket> { private static final int MAXIMUM_PAGE_LENGTH = 8192 * 4; private static final int MAXIMUM_TITLE_LENGTH = 128 * 4; @Override // BUG: CWE-287 Improper Authentication // public void translate(BookEditPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, BookEditPacket packet) { if (packet.getText() != null && !packet.getText().isEmpty() && packet.getText().getBytes(StandardCharsets.UTF_8).length > MAXIMUM_PAGE_LENGTH) { session.getConnector().getLogger().warning("Page length greater than server allowed!"); return; } GeyserItemStack itemStack = session.getPlayerInventory().getItemInHand(); if (itemStack != null) { CompoundTag tag = itemStack.getNbt() != null ? itemStack.getNbt() : new CompoundTag(""); ItemStack bookItem = new ItemStack(itemStack.getJavaId(), itemStack.getAmount(), tag); List<Tag> pages = tag.contains("pages") ? new LinkedList<>(((ListTag) tag.get("pages")).getValue()) : new LinkedList<>(); int page = packet.getPageNumber(); switch (packet.getAction()) { case ADD_PAGE: { // Add empty pages in between for (int i = pages.size(); i < page; i++) { pages.add(i, new StringTag("", "")); } pages.add(page, new StringTag("", packet.getText())); break; } // Called whenever a page is modified case REPLACE_PAGE: { if (page < pages.size()) { pages.set(page, new StringTag("", packet.getText())); } else { // Add empty pages in between for (int i = pages.size(); i < page; i++) { pages.add(i, new StringTag("", "")); } pages.add(page, new StringTag("", packet.getText())); } break; } case DELETE_PAGE: { if (page < pages.size()) { pages.remove(page); } break; } case SWAP_PAGES: { int page2 = packet.getSecondaryPageNumber(); if (page < pages.size() && page2 < pages.size()) { Collections.swap(pages, page, page2); } break; } case SIGN_BOOK: { tag.put(new StringTag("author", packet.getAuthor())); tag.put(new StringTag("title", packet.getTitle())); break; } default: return; } // Remove empty pages at the end while (pages.size() > 0) { StringTag currentPage = (StringTag) pages.get(pages.size() - 1); if (currentPage.getValue() == null || currentPage.getValue().isEmpty()) { pages.remove(pages.size() - 1); } else { break; } } tag.put(new ListTag("pages", pages)); // Update local copy session.getPlayerInventory().setItem(36 + session.getPlayerInventory().getHeldItemSlot(), GeyserItemStack.from(bookItem), session); session.getInventoryTranslator().updateInventory(session, session.getPlayerInventory()); List<String> networkPages = new ArrayList<>(); for (Tag pageTag : pages) { networkPages.add(((StringTag) pageTag).getValue()); } String title; if (packet.getAction() == BookEditPacket.Action.SIGN_BOOK) { // Add title to packet so the server knows we're signing if (packet.getTitle().getBytes(StandardCharsets.UTF_8).length > MAXIMUM_TITLE_LENGTH) { session.getConnector().getLogger().warning("Book title larger than server allows!"); return; } title = packet.getTitle(); } else { title = null; } session.getBookEditCache().setPacket(new ClientEditBookPacket(session.getPlayerInventory().getHeldItemSlot(), networkPages, title)); // There won't be any more book updates after this, so we can try sending the edit packet immediately if (packet.getAction() == BookEditPacket.Action.SIGN_BOOK) { session.getBookEditCache().checkForSend(); } } }}
data/java/BedrockCommandBlockUpdateTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;import com.github.steveice10.mc.protocol.data.game.world.block.CommandBlockMode;import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateCommandBlockMinecartPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientUpdateCommandBlockPacket;import com.nukkitx.protocol.bedrock.packet.CommandBlockUpdatePacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;@Translator(packet = CommandBlockUpdatePacket.class)public class BedrockCommandBlockUpdateTranslator extends PacketTranslator<CommandBlockUpdatePacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(CommandBlockUpdatePacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, CommandBlockUpdatePacket packet) { String command = packet.getCommand(); boolean outputTracked = packet.isOutputTracked(); if (packet.isBlock()) { CommandBlockMode mode; switch (packet.getMode()) { case CHAIN: // The green one mode = CommandBlockMode.SEQUENCE; break; case REPEATING: // The purple one mode = CommandBlockMode.AUTO; break; default: // NORMAL, the orange one mode = CommandBlockMode.REDSTONE; break; } boolean isConditional = packet.isConditional(); boolean automatic = !packet.isRedstoneMode(); // Automatic = Always Active option in Java ClientUpdateCommandBlockPacket commandBlockPacket = new ClientUpdateCommandBlockPacket( new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()), command, mode, outputTracked, isConditional, automatic); session.sendDownstreamPacket(commandBlockPacket); } else { ClientUpdateCommandBlockMinecartPacket commandMinecartPacket = new ClientUpdateCommandBlockMinecartPacket( (int) session.getEntityCache().getEntityByGeyserId(packet.getMinecartRuntimeEntityId()).getEntityId(), command, outputTracked ); session.sendDownstreamPacket(commandMinecartPacket); } }}
data/java/BedrockCommandRequestTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import org.geysermc.common.PlatformType;import org.geysermc.connector.GeyserConnector;import org.geysermc.connector.command.CommandManager;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import com.github.steveice10.mc.protocol.packet.ingame.client.ClientChatPacket;import com.nukkitx.protocol.bedrock.packet.CommandRequestPacket;import org.geysermc.connector.network.translators.chat.MessageTranslator;@Translator(packet = CommandRequestPacket.class)public class BedrockCommandRequestTranslator extends PacketTranslator<CommandRequestPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(CommandRequestPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, CommandRequestPacket packet) { String command = packet.getCommand().replace("/", ""); CommandManager commandManager = GeyserConnector.getInstance().getCommandManager(); if (session.getConnector().getPlatformType() == PlatformType.STANDALONE && command.trim().startsWith("geyser ") && commandManager.getCommands().containsKey(command.split(" ")[1])) { commandManager.runCommand(session, command); } else { String message = packet.getCommand().trim(); if (MessageTranslator.isTooLong(message, session)) { return; } ClientChatPacket chatPacket = new ClientChatPacket(message); session.sendDownstreamPacket(chatPacket); } }}
data/java/BedrockContainerCloseTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientCloseWindowPacket;import com.nukkitx.protocol.bedrock.packet.ContainerClosePacket;import org.geysermc.connector.inventory.Inventory;import org.geysermc.connector.inventory.MerchantContainer;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.utils.InventoryUtils;@Translator(packet = ContainerClosePacket.class)public class BedrockContainerCloseTranslator extends PacketTranslator<ContainerClosePacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(ContainerClosePacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ContainerClosePacket packet) { byte windowId = packet.getId(); //Client wants close confirmation session.sendUpstreamPacket(packet); session.setClosingInventory(false); if (windowId == -1 && session.getOpenInventory() instanceof MerchantContainer) { // 1.16.200 - window ID is always -1 sent from Bedrock windowId = (byte) session.getOpenInventory().getId(); } Inventory openInventory = session.getOpenInventory(); if (openInventory != null) { if (windowId == openInventory.getId()) { ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(windowId); session.sendDownstreamPacket(closeWindowPacket); InventoryUtils.closeInventory(session, windowId, false); } else if (openInventory.isPending()) { InventoryUtils.displayInventory(session, openInventory); openInventory.setPending(false); } } }}
data/java/BedrockEmoteListTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.nukkitx.protocol.bedrock.packet.EmoteListPacket;import org.geysermc.connector.configuration.EmoteOffhandWorkaroundOption;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;@Translator(packet = EmoteListPacket.class)public class BedrockEmoteListTranslator extends PacketTranslator<EmoteListPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(EmoteListPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, EmoteListPacket packet) { if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) { return; } session.refreshEmotes(packet.getPieceIds()); }}
data/java/BedrockEmoteTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock.entity.player;import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerAction;import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerActionPacket;import com.nukkitx.protocol.bedrock.packet.EmotePacket;import org.geysermc.connector.configuration.EmoteOffhandWorkaroundOption;import org.geysermc.connector.entity.Entity;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.utils.BlockUtils;@Translator(packet = EmotePacket.class)public class BedrockEmoteTranslator extends PacketTranslator<EmotePacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(EmotePacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, EmotePacket packet) { if (session.getConnector().getConfig().getEmoteOffhandWorkaround() != EmoteOffhandWorkaroundOption.DISABLED) { // Activate the workaround - we should trigger the offhand now ClientPlayerActionPacket swapHandsPacket = new ClientPlayerActionPacket(PlayerAction.SWAP_HANDS, BlockUtils.POSITION_ZERO, BlockFace.DOWN); session.sendDownstreamPacket(swapHandsPacket); if (session.getConnector().getConfig().getEmoteOffhandWorkaround() == EmoteOffhandWorkaroundOption.NO_EMOTES) { return; } } long javaId = session.getPlayerEntity().getEntityId(); for (GeyserSession otherSession : session.getConnector().getPlayers()) { if (otherSession != session) { if (otherSession.isClosed()) continue; if (otherSession.getEventLoop().inEventLoop()) { playEmote(otherSession, javaId, packet.getEmoteId()); } else { session.executeInEventLoop(() -> playEmote(otherSession, javaId, packet.getEmoteId())); } } } } private void playEmote(GeyserSession otherSession, long javaId, String emoteId) { Entity otherEntity = otherSession.getEntityCache().getEntityByJavaId(javaId); // Must be ran on same thread if (otherEntity == null) return; EmotePacket otherEmotePacket = new EmotePacket(); otherEmotePacket.setEmoteId(emoteId); otherEmotePacket.setRuntimeEntityId(otherEntity.getGeyserId()); otherSession.sendUpstreamPacket(otherEmotePacket); }}
data/java/BedrockEntityEventTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock.entity;import com.github.steveice10.mc.protocol.data.game.window.VillagerTrade;import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientSelectTradePacket;import com.nukkitx.protocol.bedrock.data.entity.EntityData;import com.nukkitx.protocol.bedrock.packet.EntityEventPacket;import org.geysermc.connector.entity.Entity;import org.geysermc.connector.inventory.GeyserItemStack;import org.geysermc.connector.inventory.Inventory;import org.geysermc.connector.inventory.MerchantContainer;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import java.util.concurrent.TimeUnit;@Translator(packet = EntityEventPacket.class)public class BedrockEntityEventTranslator extends PacketTranslator<EntityEventPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(EntityEventPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, EntityEventPacket packet) { switch (packet.getType()) { case EATING_ITEM: // Resend the packet so we get the eating sounds session.sendUpstreamPacket(packet); return; case COMPLETE_TRADE: ClientSelectTradePacket selectTradePacket = new ClientSelectTradePacket(packet.getData()); session.sendDownstreamPacket(selectTradePacket); session.scheduleInEventLoop(() -> { Entity villager = session.getPlayerEntity(); Inventory openInventory = session.getOpenInventory(); if (openInventory instanceof MerchantContainer) { MerchantContainer merchantInventory = (MerchantContainer) openInventory; VillagerTrade[] trades = merchantInventory.getVillagerTrades(); if (trades != null && packet.getData() >= 0 && packet.getData() < trades.length) { VillagerTrade trade = merchantInventory.getVillagerTrades()[packet.getData()]; openInventory.setItem(2, GeyserItemStack.from(trade.getOutput()), session); villager.getMetadata().put(EntityData.TRADE_XP, trade.getXp() + villager.getMetadata().getInt(EntityData.TRADE_XP)); villager.updateBedrockMetadata(session); } } }, 100, TimeUnit.MILLISECONDS); return; } session.getConnector().getLogger().debug("Did not translate incoming EntityEventPacket: " + packet.toString()); }}
data/java/BedrockEntityPickRequestTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode;import com.nukkitx.protocol.bedrock.data.entity.EntityData;import com.nukkitx.protocol.bedrock.packet.EntityPickRequestPacket;import org.geysermc.connector.entity.Entity;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.registry.type.ItemMapping;import org.geysermc.connector.utils.InventoryUtils;/** * Called when the Bedrock user uses the pick block button on an entity */@Translator(packet = EntityPickRequestPacket.class)public class BedrockEntityPickRequestTranslator extends PacketTranslator<EntityPickRequestPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(EntityPickRequestPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, EntityPickRequestPacket packet) { if (session.getGameMode() != GameMode.CREATIVE) return; // Apparently Java behavior Entity entity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId()); if (entity == null) return; // Get the corresponding item String itemName; switch (entity.getEntityType()) { case BOAT: // Include type of boat in the name int variant = entity.getMetadata().getInt(EntityData.VARIANT); String typeOfBoat; switch (variant) { case 1: typeOfBoat = "spruce"; break; case 2: typeOfBoat = "birch"; break; case 3: typeOfBoat = "jungle"; break; case 4: typeOfBoat = "acacia"; break; case 5: typeOfBoat = "dark_oak"; break; default: typeOfBoat = "oak"; break; } itemName = typeOfBoat + "_boat"; break; case LEASH_KNOT: itemName = "lead"; break; case MINECART_CHEST: case MINECART_COMMAND_BLOCK: case MINECART_FURNACE: case MINECART_HOPPER: case MINECART_TNT: // Move MINECART to the end of the name itemName = entity.getEntityType().toString().toLowerCase().replace("minecart_", "") + "_minecart"; break; case MINECART_SPAWNER: // Turns into a normal minecart itemName = "minecart"; break; case ARMOR_STAND: case END_CRYSTAL: //case ITEM_FRAME: Not an entity in Bedrock Edition //case GLOW_ITEM_FRAME: case MINECART: case PAINTING: // No spawn egg, just an item itemName = entity.getEntityType().toString().toLowerCase(); break; default: itemName = entity.getEntityType().toString().toLowerCase() + "_spawn_egg"; break; } String fullItemName = "minecraft:" + itemName; ItemMapping mapping = session.getItemMappings().getMapping(fullItemName); // Verify it is, indeed, an item if (mapping == null) return; InventoryUtils.findOrCreateItem(session, fullItemName); }}
data/java/BedrockFilterTextTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientRenameItemPacket;import com.nukkitx.protocol.bedrock.packet.FilterTextPacket;import org.geysermc.connector.inventory.AnvilContainer;import org.geysermc.connector.inventory.CartographyContainer;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;/** * Used to send strings to the server and filter out unwanted words. * Java doesn't care, so we don't care, and we approve all strings. */@Translator(packet = FilterTextPacket.class)public class BedrockFilterTextTranslator extends PacketTranslator<FilterTextPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(FilterTextPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, FilterTextPacket packet) { if (session.getOpenInventory() instanceof CartographyContainer) { // We don't want to be able to rename in the cartography table return; } packet.setFromServer(true); session.sendUpstreamPacket(packet); if (session.getOpenInventory() instanceof AnvilContainer) { // Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText()); session.sendDownstreamPacket(renameItemPacket); } }}
data/java/BedrockInteractTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock.entity.player;import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;import com.github.steveice10.mc.protocol.data.game.entity.player.InteractAction;import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerInteractEntityPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket;import com.nukkitx.protocol.bedrock.data.entity.EntityData;import com.nukkitx.protocol.bedrock.data.entity.EntityFlag;import com.nukkitx.protocol.bedrock.data.inventory.ContainerType;import com.nukkitx.protocol.bedrock.packet.ContainerOpenPacket;import com.nukkitx.protocol.bedrock.packet.InteractPacket;import org.geysermc.connector.entity.Entity;import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.utils.InteractiveTagManager;@Translator(packet = InteractPacket.class)public class BedrockInteractTranslator extends PacketTranslator<InteractPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(InteractPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, InteractPacket packet) { Entity entity; if (packet.getRuntimeEntityId() == session.getPlayerEntity().getGeyserId()) { //Player is not in entity cache entity = session.getPlayerEntity(); } else { entity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId()); } if (entity == null) return; switch (packet.getAction()) { case INTERACT: if (session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) { break; } ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), InteractAction.INTERACT, Hand.MAIN_HAND, session.isSneaking()); session.sendDownstreamPacket(interactPacket); break; case DAMAGE: ClientPlayerInteractEntityPacket attackPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking()); session.sendDownstreamPacket(attackPacket); break; case LEAVE_VEHICLE: ClientPlayerStatePacket sneakPacket = new ClientPlayerStatePacket((int) entity.getEntityId(), PlayerState.START_SNEAKING); session.sendDownstreamPacket(sneakPacket); session.setRidingVehicleEntity(null); break; case MOUSEOVER: // Handle the buttons for mobile - "Mount", etc; and the suggestions for console - "ZL: Mount", etc if (packet.getRuntimeEntityId() != 0) { Entity interactEntity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId()); session.setMouseoverEntity(interactEntity); if (interactEntity == null) { return; } InteractiveTagManager.updateTag(session, interactEntity); } else { if (session.getMouseoverEntity() != null) { // No interactive tag should be sent session.setMouseoverEntity(null); session.getPlayerEntity().getMetadata().put(EntityData.INTERACTIVE_TAG, ""); session.getPlayerEntity().updateBedrockMetadata(session); } } break; case OPEN_INVENTORY: if (session.getOpenInventory() == null) { Entity ridingEntity = session.getRidingVehicleEntity(); if (ridingEntity instanceof AbstractHorseEntity) { if (ridingEntity.getMetadata().getFlags().getFlag(EntityFlag.TAMED)) { // We should request to open the horse inventory instead ClientPlayerStatePacket openHorseWindowPacket = new ClientPlayerStatePacket((int) session.getPlayerEntity().getEntityId(), PlayerState.OPEN_HORSE_INVENTORY); session.sendDownstreamPacket(openHorseWindowPacket); } } else { session.setOpenInventory(session.getPlayerInventory()); ContainerOpenPacket containerOpenPacket = new ContainerOpenPacket(); containerOpenPacket.setId((byte) 0); containerOpenPacket.setType(ContainerType.INVENTORY); containerOpenPacket.setUniqueEntityId(-1); containerOpenPacket.setBlockPosition(entity.getPosition().toInt()); session.sendUpstreamPacket(containerOpenPacket); } } break; } }}
data/java/BedrockInventoryTransactionTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode;import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;import com.github.steveice10.mc.protocol.data.game.entity.player.InteractAction;import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerAction;import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerActionPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerInteractEntityPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerUseItemPacket;import com.nukkitx.math.vector.Vector3f;import com.nukkitx.math.vector.Vector3i;import com.nukkitx.protocol.bedrock.data.LevelEventType;import com.nukkitx.protocol.bedrock.data.inventory.*;import com.nukkitx.protocol.bedrock.packet.*;import org.geysermc.connector.entity.CommandBlockMinecartEntity;import org.geysermc.connector.entity.Entity;import org.geysermc.connector.entity.ItemFrameEntity;import org.geysermc.connector.entity.type.EntityType;import org.geysermc.connector.inventory.GeyserItemStack;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.network.translators.sound.EntitySoundInteractionHandler;import org.geysermc.connector.network.translators.world.block.BlockStateValues;import org.geysermc.connector.registry.BlockRegistries;import org.geysermc.connector.registry.type.ItemMapping;import org.geysermc.connector.registry.type.ItemMappings;import org.geysermc.connector.utils.BlockUtils;import java.util.concurrent.TimeUnit;/** * BedrockInventoryTransactionTranslator handles most interactions between the client and the world, * or the client and their inventory. */@Translator(packet = InventoryTransactionPacket.class)public class BedrockInventoryTransactionTranslator extends PacketTranslator<InventoryTransactionPacket> { private static final float MAXIMUM_BLOCK_PLACING_DISTANCE = 64f; private static final int CREATIVE_EYE_HEIGHT_PLACE_DISTANCE = 49; private static final int SURVIVAL_EYE_HEIGHT_PLACE_DISTANCE = 36; private static final float MAXIMUM_BLOCK_DESTROYING_DISTANCE = 36f; @Override // BUG: CWE-287 Improper Authentication // public void translate(InventoryTransactionPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, InventoryTransactionPacket packet) { // Send book updates before opening inventories session.getBookEditCache().checkForSend(); ItemMappings mappings = session.getItemMappings(); switch (packet.getTransactionType()) { case NORMAL: if (packet.getActions().size() == 2) { InventoryActionData worldAction = packet.getActions().get(0); InventoryActionData containerAction = packet.getActions().get(1); if (worldAction.getSource().getType() == InventorySource.Type.WORLD_INTERACTION && worldAction.getSource().getFlag() == InventorySource.Flag.DROP_ITEM) { if (session.getPlayerInventory().getHeldItemSlot() != containerAction.getSlot() || session.getPlayerInventory().getItemInHand().isEmpty()) { return; } boolean dropAll = worldAction.getToItem().getCount() > 1; ClientPlayerActionPacket dropAllPacket = new ClientPlayerActionPacket( dropAll ? PlayerAction.DROP_ITEM_STACK : PlayerAction.DROP_ITEM, BlockUtils.POSITION_ZERO, BlockFace.DOWN ); session.sendDownstreamPacket(dropAllPacket); if (dropAll) { session.getPlayerInventory().setItemInHand(GeyserItemStack.EMPTY); } else { session.getPlayerInventory().getItemInHand().sub(1); } } } break; case INVENTORY_MISMATCH: break; case ITEM_USE: switch (packet.getActionType()) { case 0: // Check to make sure the client isn't spamming interaction // Based on Nukkit 1.0, with changes to ensure holding down still works boolean hasAlreadyClicked = System.currentTimeMillis() - session.getLastInteractionTime() < 110.0 && packet.getBlockPosition().distanceSquared(session.getLastInteractionBlockPosition()) < 0.00001; session.setLastInteractionBlockPosition(packet.getBlockPosition()); session.setLastInteractionPlayerPosition(session.getPlayerEntity().getPosition()); if (hasAlreadyClicked) { break; } else { // Only update the interaction time if it's valid - that way holding down still works. session.setLastInteractionTime(System.currentTimeMillis()); } // Bedrock sends block interact code for a Java entity so we send entity code back to Java if (session.getBlockMappings().isItemFrame(packet.getBlockRuntimeId())) { Entity itemFrameEntity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition()); if (itemFrameEntity != null) { int entityId = (int) itemFrameEntity.getEntityId(); Vector3f vector = packet.getClickPosition(); ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket(entityId, InteractAction.INTERACT, Hand.MAIN_HAND, session.isSneaking()); ClientPlayerInteractEntityPacket interactAtPacket = new ClientPlayerInteractEntityPacket(entityId, InteractAction.INTERACT_AT, vector.getX(), vector.getY(), vector.getZ(), Hand.MAIN_HAND, session.isSneaking()); session.sendDownstreamPacket(interactPacket); session.sendDownstreamPacket(interactAtPacket); break; } } Vector3i blockPos = BlockUtils.getBlockPosition(packet.getBlockPosition(), packet.getBlockFace()); /* Checks to ensure that the range will be accepted by the server. "Not in range" doesn't refer to how far a vanilla client goes (that's a whole other mess), but how much a server will accept from the client maximum */ // CraftBukkit+ check - see https://github.com/PaperMC/Paper/blob/458db6206daae76327a64f4e2a17b67a7e38b426/Spigot-Server-Patches/0532-Move-range-check-for-block-placing-up.patch Vector3f playerPosition = session.getPlayerEntity().getPosition(); // Adjust position for current eye height switch (session.getPose()) { case SNEAKING: playerPosition = playerPosition.sub(0, (EntityType.PLAYER.getOffset() - 1.27f), 0); break; case SWIMMING: case FALL_FLYING: // Elytra case SPIN_ATTACK: // Trident spin attack playerPosition = playerPosition.sub(0, (EntityType.PLAYER.getOffset() - 0.4f), 0); break; case SLEEPING: playerPosition = playerPosition.sub(0, (EntityType.PLAYER.getOffset() - 0.2f), 0); break; } // else, we don't have to modify the position float diffX = playerPosition.getX() - packet.getBlockPosition().getX(); float diffY = playerPosition.getY() - packet.getBlockPosition().getY(); float diffZ = playerPosition.getZ() - packet.getBlockPosition().getZ(); if (((diffX * diffX) + (diffY * diffY) + (diffZ * diffZ)) > (session.getGameMode().equals(GameMode.CREATIVE) ? CREATIVE_EYE_HEIGHT_PLACE_DISTANCE : SURVIVAL_EYE_HEIGHT_PLACE_DISTANCE)) { restoreCorrectBlock(session, blockPos, packet); return; } // Vanilla check if (!(session.getPlayerEntity().getPosition().sub(0, EntityType.PLAYER.getOffset(), 0) .distanceSquared(packet.getBlockPosition().toFloat().add(0.5f, 0.5f, 0.5f)) < MAXIMUM_BLOCK_PLACING_DISTANCE)) { // The client thinks that its blocks have been successfully placed. Restore the server's blocks instead. restoreCorrectBlock(session, blockPos, packet); return; } /* Block place checks end - client is good to go */ if (packet.getItemInHand() != null && session.getItemMappings().getSpawnEggIds().contains(packet.getItemInHand().getId())) { int blockState = session.getConnector().getWorldManager().getBlockAt(session, packet.getBlockPosition()); if (blockState == BlockStateValues.JAVA_WATER_ID) { // Otherwise causes multiple mobs to spawn - just send a use item packet // TODO when we fix mobile bucket rotation, use it for this, too ClientPlayerUseItemPacket itemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); session.sendDownstreamPacket(itemPacket); break; } } ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket( new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()), BlockFace.values()[packet.getBlockFace()], Hand.MAIN_HAND, packet.getClickPosition().getX(), packet.getClickPosition().getY(), packet.getClickPosition().getZ(), false); session.sendDownstreamPacket(blockPacket); if (packet.getItemInHand() != null) { // Otherwise boats will not be able to be placed in survival and buckets won't work on mobile if (session.getItemMappings().getBoatIds().contains(packet.getItemInHand().getId())) { ClientPlayerUseItemPacket itemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); session.sendDownstreamPacket(itemPacket); } else if (session.getItemMappings().getBucketIds().contains(packet.getItemInHand().getId())) { // Let the server decide if the bucket item should change, not the client, and revert the changes the client made InventorySlotPacket slotPacket = new InventorySlotPacket(); slotPacket.setContainerId(ContainerId.INVENTORY); slotPacket.setSlot(packet.getHotbarSlot()); slotPacket.setItem(packet.getItemInHand()); session.sendUpstreamPacket(slotPacket); // Don't send ClientPlayerUseItemPacket for powder snow buckets if (packet.getItemInHand().getId() != session.getItemMappings().getStoredItems().powderSnowBucket().getBedrockId()) { // Special check for crafting tables since clients don't send BLOCK_INTERACT when interacting int blockState = session.getConnector().getWorldManager().getBlockAt(session, packet.getBlockPosition()); if (session.isSneaking() || blockState != BlockRegistries.JAVA_IDENTIFIERS.get("minecraft:crafting_table")) { // Delay the interaction in case the client doesn't intend to actually use the bucket // See BedrockActionTranslator.java session.setBucketScheduledFuture(session.scheduleInEventLoop(() -> { ClientPlayerUseItemPacket itemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); session.sendDownstreamPacket(itemPacket); }, 5, TimeUnit.MILLISECONDS)); } } } } if (packet.getActions().isEmpty()) { if (session.getOpPermissionLevel() >= 2 && session.getGameMode() == GameMode.CREATIVE) { // Otherwise insufficient permissions int blockState = session.getBlockMappings().getJavaBlockState(packet.getBlockRuntimeId()); String blockName = BlockRegistries.JAVA_IDENTIFIERS.get().getOrDefault(blockState, ""); // In the future this can be used for structure blocks too, however not all elements // are available in each GUI if (blockName.contains("jigsaw")) { ContainerOpenPacket openPacket = new ContainerOpenPacket(); openPacket.setBlockPosition(packet.getBlockPosition()); openPacket.setId((byte) 1); openPacket.setType(ContainerType.JIGSAW_EDITOR); openPacket.setUniqueEntityId(-1); session.sendUpstreamPacket(openPacket); } } } ItemMapping handItem = mappings.getMapping(packet.getItemInHand()); if (handItem.isBlock()) { session.setLastBlockPlacePosition(blockPos); session.setLastBlockPlacedId(handItem.getJavaIdentifier()); } session.setInteracting(true); break; case 1: if (packet.getActions().size() == 1 && packet.getLegacySlots().size() > 0) { InventoryActionData actionData = packet.getActions().get(0); LegacySetItemSlotData slotData = packet.getLegacySlots().get(0); if (slotData.getContainerId() == 6 && actionData.getToItem().getId() != 0) { // The player is trying to swap out an armor piece that already has an item in it // Java Edition does not allow this; let's revert it session.getInventoryTranslator().updateInventory(session, session.getPlayerInventory()); } } // Handled when sneaking if (session.getPlayerInventory().getItemInHand().getJavaId() == mappings.getStoredItems().shield().getJavaId()) { break; } // Handled in ITEM_USE if the item is not milk if (packet.getItemInHand() != null) { if (session.getItemMappings().getBucketIds().contains(packet.getItemInHand().getId()) && packet.getItemInHand().getId() != session.getItemMappings().getStoredItems().milkBucket().getBedrockId()) { // Handled in case 0 if the item is not milk break; } else if (session.getItemMappings().getSpawnEggIds().contains(packet.getItemInHand().getId())) { // Handled in case 0 break; } } ClientPlayerUseItemPacket useItemPacket = new ClientPlayerUseItemPacket(Hand.MAIN_HAND); session.sendDownstreamPacket(useItemPacket); break; case 2: int blockState = session.getGameMode() == GameMode.CREATIVE ? session.getConnector().getWorldManager().getBlockAt(session, packet.getBlockPosition()) : session.getBreakingBlock(); session.setLastBlockPlacedId(null); session.setLastBlockPlacePosition(null); // Same deal with vanilla block placing as above. // This is working out the distance using 3d Pythagoras and the extra value added to the Y is the sneaking height of a java player. playerPosition = session.getPlayerEntity().getPosition(); Vector3f floatBlockPosition = packet.getBlockPosition().toFloat(); diffX = playerPosition.getX() - (floatBlockPosition.getX() + 0.5f); diffY = (playerPosition.getY() - EntityType.PLAYER.getOffset()) - (floatBlockPosition.getY() + 0.5f) + 1.5f; diffZ = playerPosition.getZ() - (floatBlockPosition.getZ() + 0.5f); float distanceSquared = diffX * diffX + diffY * diffY + diffZ * diffZ; if (distanceSquared > MAXIMUM_BLOCK_DESTROYING_DISTANCE) { restoreCorrectBlock(session, packet.getBlockPosition(), packet); return; } LevelEventPacket blockBreakPacket = new LevelEventPacket(); blockBreakPacket.setType(LevelEventType.PARTICLE_DESTROY_BLOCK); blockBreakPacket.setPosition(packet.getBlockPosition().toFloat()); blockBreakPacket.setData(session.getBlockMappings().getBedrockBlockId(blockState)); session.sendUpstreamPacket(blockBreakPacket); session.setBreakingBlock(BlockStateValues.JAVA_AIR_ID); Entity itemFrameEntity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition()); if (itemFrameEntity != null) { ClientPlayerInteractEntityPacket attackPacket = new ClientPlayerInteractEntityPacket((int) itemFrameEntity.getEntityId(), InteractAction.ATTACK, session.isSneaking()); session.sendDownstreamPacket(attackPacket); break; } PlayerAction action = session.getGameMode() == GameMode.CREATIVE ? PlayerAction.START_DIGGING : PlayerAction.FINISH_DIGGING; Position pos = new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()); ClientPlayerActionPacket breakPacket = new ClientPlayerActionPacket(action, pos, BlockFace.values()[packet.getBlockFace()]); session.sendDownstreamPacket(breakPacket); break; } break; case ITEM_RELEASE: if (packet.getActionType() == 0) { // Followed to the Minecraft Protocol specification outlined at wiki.vg ClientPlayerActionPacket releaseItemPacket = new ClientPlayerActionPacket(PlayerAction.RELEASE_USE_ITEM, BlockUtils.POSITION_ZERO, BlockFace.DOWN); session.sendDownstreamPacket(releaseItemPacket); } break; case ITEM_USE_ON_ENTITY: Entity entity = session.getEntityCache().getEntityByGeyserId(packet.getRuntimeEntityId()); if (entity == null) return; //https://wiki.vg/Protocol#Interact_Entity switch (packet.getActionType()) { case 0: //Interact if (entity instanceof CommandBlockMinecartEntity) { // The UI is handled client-side on Java Edition // Ensure OP permission level and gamemode is appropriate if (session.getOpPermissionLevel() < 2 || session.getGameMode() != GameMode.CREATIVE) return; ContainerOpenPacket openPacket = new ContainerOpenPacket(); openPacket.setBlockPosition(Vector3i.ZERO); openPacket.setId((byte) 1); openPacket.setType(ContainerType.COMMAND_BLOCK); openPacket.setUniqueEntityId(entity.getGeyserId()); session.sendUpstreamPacket(openPacket); break; } Vector3f vector = packet.getClickPosition().sub(entity.getPosition()); ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), InteractAction.INTERACT, Hand.MAIN_HAND, session.isSneaking()); ClientPlayerInteractEntityPacket interactAtPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), InteractAction.INTERACT_AT, vector.getX(), vector.getY(), vector.getZ(), Hand.MAIN_HAND, session.isSneaking()); session.sendDownstreamPacket(interactPacket); session.sendDownstreamPacket(interactAtPacket); EntitySoundInteractionHandler.handleEntityInteraction(session, packet.getClickPosition(), entity); break; case 1: //Attack if (entity.getEntityType() == EntityType.ENDER_DRAGON) { // Redirects the attack to its body entity, this only happens when // attacking the underbelly of the ender dragon ClientPlayerInteractEntityPacket attackPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId() + 3, InteractAction.ATTACK, session.isSneaking()); session.sendDownstreamPacket(attackPacket); } else { ClientPlayerInteractEntityPacket attackPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), InteractAction.ATTACK, session.isSneaking()); session.sendDownstreamPacket(attackPacket); } break; } break; } } /** * Restore the correct block state from the server without updating the chunk cache. * * @param session the session of the Bedrock client * @param blockPos the block position to restore */ private void restoreCorrectBlock(GeyserSession session, Vector3i blockPos, InventoryTransactionPacket packet) { int javaBlockState = session.getConnector().getWorldManager().getBlockAt(session, blockPos); UpdateBlockPacket updateBlockPacket = new UpdateBlockPacket(); updateBlockPacket.setDataLayer(0); updateBlockPacket.setBlockPosition(blockPos); updateBlockPacket.setRuntimeId(session.getBlockMappings().getBedrockBlockId(javaBlockState)); updateBlockPacket.getFlags().addAll(UpdateBlockPacket.FLAG_ALL_PRIORITY); session.sendUpstreamPacket(updateBlockPacket); UpdateBlockPacket updateWaterPacket = new UpdateBlockPacket(); updateWaterPacket.setDataLayer(1); updateWaterPacket.setBlockPosition(blockPos); updateWaterPacket.setRuntimeId(BlockRegistries.WATERLOGGED.get().contains(javaBlockState) ? session.getBlockMappings().getBedrockWaterId() : session.getBlockMappings().getBedrockAirId()); updateWaterPacket.getFlags().addAll(UpdateBlockPacket.FLAG_ALL_PRIORITY); session.sendUpstreamPacket(updateWaterPacket); // Reset the item in hand to prevent "missing" blocks InventorySlotPacket slotPacket = new InventorySlotPacket(); slotPacket.setContainerId(ContainerId.INVENTORY); slotPacket.setSlot(packet.getHotbarSlot()); slotPacket.setItem(packet.getItemInHand()); session.sendUpstreamPacket(slotPacket); }}
data/java/BedrockItemFrameDropItemTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;import com.github.steveice10.mc.protocol.data.game.entity.player.InteractAction;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerInteractEntityPacket;import com.nukkitx.protocol.bedrock.packet.ItemFrameDropItemPacket;import org.geysermc.connector.entity.Entity;import org.geysermc.connector.entity.ItemFrameEntity;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;/** * Pre-1.16.210: used for both survival and creative item frame item removal * * 1.16.210: only used in creative. */@Translator(packet = ItemFrameDropItemPacket.class)public class BedrockItemFrameDropItemTranslator extends PacketTranslator<ItemFrameDropItemPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(ItemFrameDropItemPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ItemFrameDropItemPacket packet) { Entity entity = ItemFrameEntity.getItemFrameEntity(session, packet.getBlockPosition()); if (entity != null) { ClientPlayerInteractEntityPacket interactPacket = new ClientPlayerInteractEntityPacket((int) entity.getEntityId(), InteractAction.ATTACK, Hand.MAIN_HAND, session.isSneaking()); session.sendDownstreamPacket(interactPacket); } }}
data/java/BedrockItemStackRequestTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.nukkitx.protocol.bedrock.packet.ItemStackRequestPacket;import org.geysermc.connector.inventory.Inventory;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.network.translators.inventory.InventoryTranslator;/** * The packet sent for server-authoritative-style inventory transactions. */@Translator(packet = ItemStackRequestPacket.class)public class BedrockItemStackRequestTranslator extends PacketTranslator<ItemStackRequestPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(ItemStackRequestPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ItemStackRequestPacket packet) { Inventory inventory = session.getOpenInventory(); if (inventory == null) return; InventoryTranslator translator = session.getInventoryTranslator(); translator.translateRequests(session, inventory, packet.getRequests()); }}
data/java/BedrockLecternUpdateTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.data.game.entity.metadata.Position;import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;import com.github.steveice10.mc.protocol.data.game.world.block.BlockFace;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPlaceBlockPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientClickWindowButtonPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.window.ClientCloseWindowPacket;import com.nukkitx.protocol.bedrock.packet.LecternUpdatePacket;import org.geysermc.connector.inventory.LecternContainer;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.utils.InventoryUtils;/** * Used to translate moving pages, or closing the inventory */@Translator(packet = LecternUpdatePacket.class)public class BedrockLecternUpdateTranslator extends PacketTranslator<LecternUpdatePacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(LecternUpdatePacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, LecternUpdatePacket packet) { if (packet.isDroppingBook()) { // Bedrock drops the book outside of the GUI. Java drops it in the GUI // So, we enter the GUI and then drop it! :) session.setDroppingLecternBook(true); // Emulate an interact packet ClientPlayerPlaceBlockPacket blockPacket = new ClientPlayerPlaceBlockPacket( new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()), BlockFace.DOWN, Hand.MAIN_HAND, 0, 0, 0, // Java doesn't care about these when dealing with a lectern false); session.sendDownstreamPacket(blockPacket); } else { // Bedrock wants to either move a page or exit if (!(session.getOpenInventory() instanceof LecternContainer)) { session.getConnector().getLogger().debug("Expected lectern but it wasn't open!"); return; } LecternContainer lecternContainer = (LecternContainer) session.getOpenInventory(); if (lecternContainer.getCurrentBedrockPage() == packet.getPage()) { // The same page means Bedrock is closing the window ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(lecternContainer.getId()); session.sendDownstreamPacket(closeWindowPacket); InventoryUtils.closeInventory(session, lecternContainer.getId(), false); } else { // Each "page" Bedrock gives to us actually represents two pages (think opening a book and seeing two pages) // Each "page" on Java is just one page (think a spiral notebook folded back to only show one page) int newJavaPage = (packet.getPage() * 2); int currentJavaPage = (lecternContainer.getCurrentBedrockPage() * 2); // Send as many click button packets as we need to // Java has the option to specify exact page numbers by adding 100 to the number, but buttonId variable // is a byte when transmitted over the network and therefore this stops us at 128 if (newJavaPage > currentJavaPage) { for (int i = currentJavaPage; i < newJavaPage; i++) { ClientClickWindowButtonPacket clickButtonPacket = new ClientClickWindowButtonPacket(session.getOpenInventory().getId(), 2); session.sendDownstreamPacket(clickButtonPacket); } } else { for (int i = currentJavaPage; i > newJavaPage; i--) { ClientClickWindowButtonPacket clickButtonPacket = new ClientClickWindowButtonPacket(session.getOpenInventory().getId(), 1); session.sendDownstreamPacket(clickButtonPacket); } } } } }}
data/java/BedrockMapInfoRequestTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.nukkitx.protocol.bedrock.packet.ClientboundMapItemDataPacket;import com.nukkitx.protocol.bedrock.packet.MapInfoRequestPacket;import org.geysermc.connector.GeyserConnector;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import java.util.concurrent.TimeUnit;@Translator(packet = MapInfoRequestPacket.class)public class BedrockMapInfoRequestTranslator extends PacketTranslator<MapInfoRequestPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(MapInfoRequestPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, MapInfoRequestPacket packet) { long mapId = packet.getUniqueMapId(); ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().remove(mapId); if (mapPacket != null) { // Delay the packet 100ms to prevent the client from ignoring the packet GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket), 100, TimeUnit.MILLISECONDS); } }}
data/java/BedrockMobEquipmentTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.data.game.entity.player.Hand;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerChangeHeldItemPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerUseItemPacket;import com.nukkitx.protocol.bedrock.data.inventory.ContainerId;import com.nukkitx.protocol.bedrock.packet.MobEquipmentPacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.utils.CooldownUtils;import org.geysermc.connector.utils.InteractiveTagManager;import java.util.concurrent.TimeUnit;@Translator(packet = MobEquipmentPacket.class)public class BedrockMobEquipmentTranslator extends PacketTranslator<MobEquipmentPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(MobEquipmentPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, MobEquipmentPacket packet) { if (!session.isSpawned() || packet.getHotbarSlot() > 8 || packet.getContainerId() != ContainerId.INVENTORY || session.getPlayerInventory().getHeldItemSlot() == packet.getHotbarSlot()) { // For the last condition - Don't update the slot if the slot is the same - not Java Edition behavior and messes with plugins such as Grief Prevention return; } // Send book update before switching hotbar slot session.getBookEditCache().checkForSend(); session.getPlayerInventory().setHeldItemSlot(packet.getHotbarSlot()); ClientPlayerChangeHeldItemPacket changeHeldItemPacket = new ClientPlayerChangeHeldItemPacket(packet.getHotbarSlot()); session.sendDownstreamPacket(changeHeldItemPacket); if (session.isSneaking() && session.getPlayerInventory().getItemInHand().getJavaId() == session.getItemMappings().getStoredItems().shield().getJavaId()) { // Activate shield since we are already sneaking // (No need to send a release item packet - Java doesn't do this when swapping items) // Required to do it a tick later or else it doesn't register session.getConnector().getGeneralThreadPool().schedule(() -> session.sendDownstreamPacket(new ClientPlayerUseItemPacket(Hand.MAIN_HAND)), 50, TimeUnit.MILLISECONDS); } // Java sends a cooldown indicator whenever you switch an item CooldownUtils.sendCooldown(session); // Update the interactive tag, if an entity is present if (session.getMouseoverEntity() != null) { InteractiveTagManager.updateTag(session, session.getMouseoverEntity()); } }}
data/java/BedrockMoveEntityAbsoluteTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientVehicleMovePacket;import com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket;import org.geysermc.connector.entity.BoatEntity;import org.geysermc.connector.entity.type.EntityType;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;/** * Sent by the client when moving a horse. */@Translator(packet = MoveEntityAbsolutePacket.class)public class BedrockMoveEntityAbsoluteTranslator extends PacketTranslator<MoveEntityAbsolutePacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(MoveEntityAbsolutePacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, MoveEntityAbsolutePacket packet) { session.setLastVehicleMoveTimestamp(System.currentTimeMillis()); float y = packet.getPosition().getY(); if (session.getRidingVehicleEntity() instanceof BoatEntity) { // Remove the offset to prevents boats from looking like they're floating in water y -= EntityType.BOAT.getOffset(); } ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket( packet.getPosition().getX(), y, packet.getPosition().getZ(), packet.getRotation().getY() - 90, packet.getRotation().getX() ); session.sendDownstreamPacket(clientVehicleMovePacket); }}
data/java/BedrockMovePlayerTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock.entity.player;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionRotationPacket;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerRotationPacket;import com.github.steveice10.packetlib.packet.Packet;import com.nukkitx.math.vector.Vector3d;import com.nukkitx.math.vector.Vector3f;import com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket;import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;import org.geysermc.connector.GeyserConnector;import org.geysermc.connector.common.ChatColor;import org.geysermc.connector.entity.player.SessionPlayerEntity;import org.geysermc.connector.entity.type.EntityType;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;@Translator(packet = MovePlayerPacket.class)public class BedrockMovePlayerTranslator extends PacketTranslator<MovePlayerPacket> { /* The upper and lower bounds to check for the void floor that only exists in Bedrock */ private static final int BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y; private static final int BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y; static { BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y = GeyserConnector.getInstance().getConfig().isExtendedWorldHeight() ? -104 : -40; BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y = BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y + 2; } @Override // BUG: CWE-287 Improper Authentication // public void translate(MovePlayerPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, MovePlayerPacket packet) { SessionPlayerEntity entity = session.getPlayerEntity(); if (!session.isSpawned()) return; if (!session.getUpstream().isInitialized()) { MoveEntityAbsolutePacket moveEntityBack = new MoveEntityAbsolutePacket(); moveEntityBack.setRuntimeEntityId(entity.getGeyserId()); moveEntityBack.setPosition(entity.getPosition()); moveEntityBack.setRotation(entity.getBedrockRotation()); moveEntityBack.setTeleported(true); moveEntityBack.setOnGround(true); session.sendUpstreamPacketImmediately(moveEntityBack); return; } session.setLastMovementTimestamp(System.currentTimeMillis()); // Send book update before the player moves session.getBookEditCache().checkForSend(); session.confirmTeleport(packet.getPosition().toDouble().sub(0, EntityType.PLAYER.getOffset(), 0)); // head yaw, pitch, head yaw Vector3f rotation = Vector3f.from(packet.getRotation().getY(), packet.getRotation().getX(), packet.getRotation().getY()); boolean positionChanged = !entity.getPosition().equals(packet.getPosition()); boolean rotationChanged = !entity.getRotation().equals(rotation); // If only the pitch and yaw changed // This isn't needed, but it makes the packets closer to vanilla // It also means you can't "lag back" while only looking, in theory if (!positionChanged && rotationChanged) { ClientPlayerRotationPacket playerRotationPacket = new ClientPlayerRotationPacket( packet.isOnGround(), packet.getRotation().getY(), packet.getRotation().getX()); entity.setRotation(rotation); entity.setOnGround(packet.isOnGround()); session.sendDownstreamPacket(playerRotationPacket); } else { Vector3d position = session.getCollisionManager().adjustBedrockPosition(packet.getPosition(), packet.isOnGround()); if (position != null) { // A null return value cancels the packet if (isValidMove(session, packet.getMode(), entity.getPosition(), packet.getPosition())) { Packet movePacket; if (rotationChanged) { // Send rotation updates as well movePacket = new ClientPlayerPositionRotationPacket(packet.isOnGround(), position.getX(), position.getY(), position.getZ(), packet.getRotation().getY(), packet.getRotation().getX()); entity.setRotation(rotation); } else { // Rotation did not change; don't send an update with rotation movePacket = new ClientPlayerPositionPacket(packet.isOnGround(), position.getX(), position.getY(), position.getZ()); } // Compare positions here for void floor fix below before the player's position variable is set to the packet position boolean notMovingUp = entity.getPosition().getY() >= packet.getPosition().getY(); entity.setPositionManual(packet.getPosition()); entity.setOnGround(packet.isOnGround()); // Send final movement changes session.sendDownstreamPacket(movePacket); if (notMovingUp) { int floorY = position.getFloorY(); // If the client believes the world has extended height, then it also believes the void floor // still exists, just at a lower spot boolean extendedWorld = session.getChunkCache().isExtendedHeight(); if (floorY <= (extendedWorld ? BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y : -38) && floorY >= (extendedWorld ? BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y : -40)) { // Work around there being a floor at the bottom of the world and teleport the player below it // Moving from below to above the void floor works fine entity.setPosition(entity.getPosition().sub(0, 4f, 0)); MovePlayerPacket movePlayerPacket = new MovePlayerPacket(); movePlayerPacket.setRuntimeEntityId(entity.getGeyserId()); movePlayerPacket.setPosition(entity.getPosition()); movePlayerPacket.setRotation(entity.getBedrockRotation()); movePlayerPacket.setMode(MovePlayerPacket.Mode.TELEPORT); movePlayerPacket.setTeleportationCause(MovePlayerPacket.TeleportationCause.BEHAVIOR); session.sendUpstreamPacket(movePlayerPacket); } } } else { // Not a valid move session.getConnector().getLogger().debug("Recalculating position..."); session.getCollisionManager().recalculatePosition(); } } } // Move parrots to match if applicable if (entity.getLeftParrot() != null) { entity.getLeftParrot().moveAbsolute(session, entity.getPosition(), entity.getRotation(), true, false); } if (entity.getRightParrot() != null) { entity.getRightParrot().moveAbsolute(session, entity.getPosition(), entity.getRotation(), true, false); } } private boolean isValidMove(GeyserSession session, MovePlayerPacket.Mode mode, Vector3f currentPosition, Vector3f newPosition) { if (mode != MovePlayerPacket.Mode.NORMAL) return true; double xRange = newPosition.getX() - currentPosition.getX(); double yRange = newPosition.getY() - currentPosition.getY(); double zRange = newPosition.getZ() - currentPosition.getZ(); if (xRange < 0) xRange = -xRange; if (yRange < 0) yRange = -yRange; if (zRange < 0) zRange = -zRange; if ((xRange + yRange + zRange) > 100) { session.getConnector().getLogger().debug(ChatColor.RED + session.getName() + " moved too quickly." + " current position: " + currentPosition + ", new position: " + newPosition); return false; } return true; }}
data/java/BedrockNetworkStackLatencyTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.packet.ingame.client.ClientKeepAlivePacket;import com.nukkitx.protocol.bedrock.data.AttributeData;import com.nukkitx.protocol.bedrock.packet.NetworkStackLatencyPacket;import com.nukkitx.protocol.bedrock.packet.UpdateAttributesPacket;import org.geysermc.connector.entity.attribute.GeyserAttributeType;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.floodgate.util.DeviceOs;import java.util.Collections;import java.util.concurrent.TimeUnit;/** * Used to send the forwarded keep alive packet back to the server */@Translator(packet = NetworkStackLatencyPacket.class)public class BedrockNetworkStackLatencyTranslator extends PacketTranslator<NetworkStackLatencyPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(NetworkStackLatencyPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, NetworkStackLatencyPacket packet) { long pingId; // so apparently, as of 1.16.200 // PS4 divides the network stack latency timestamp FOR US!!! // WTF if (session.getClientData().getDeviceOs().equals(DeviceOs.PS4)) { pingId = packet.getTimestamp(); } else { pingId = packet.getTimestamp() / 1000; } // negative timestamps are used as hack to fix the url image loading bug if (packet.getTimestamp() > 0) { if (session.getConnector().getConfig().isForwardPlayerPing()) { ClientKeepAlivePacket keepAlivePacket = new ClientKeepAlivePacket(pingId); session.sendDownstreamPacket(keepAlivePacket); } return; } // Hack to fix the url image loading bug UpdateAttributesPacket attributesPacket = new UpdateAttributesPacket(); attributesPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId()); AttributeData attribute = session.getPlayerEntity().getAttributes().get(GeyserAttributeType.EXPERIENCE_LEVEL); if (attribute != null) { attributesPacket.setAttributes(Collections.singletonList(attribute)); } else { attributesPacket.setAttributes(Collections.singletonList(GeyserAttributeType.EXPERIENCE_LEVEL.getAttribute(0))); } session.getConnector().getGeneralThreadPool().schedule( () -> session.sendUpstreamPacket(attributesPacket), 500, TimeUnit.MILLISECONDS); }}
data/java/BedrockPacketViolationWarningTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.nukkitx.protocol.bedrock.packet.PacketViolationWarningPacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;@Translator(packet = PacketViolationWarningPacket.class)public class BedrockPacketViolationWarningTranslator extends PacketTranslator<PacketViolationWarningPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(PacketViolationWarningPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, PacketViolationWarningPacket packet) { // Not translated since this is something that the developers need to know session.getConnector().getLogger().error("Packet violation warning sent from client! " + packet.toString()); }}
data/java/BedrockPlayerInputTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientSteerVehiclePacket;import com.github.steveice10.mc.protocol.packet.ingame.client.world.ClientVehicleMovePacket;import com.nukkitx.math.vector.Vector3f;import com.nukkitx.protocol.bedrock.data.entity.EntityData;import com.nukkitx.protocol.bedrock.packet.PlayerInputPacket;import org.geysermc.connector.entity.BoatEntity;import org.geysermc.connector.entity.Entity;import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;import org.geysermc.connector.entity.living.animal.horse.LlamaEntity;import org.geysermc.connector.entity.type.EntityType;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;/** * Sent by the client for minecarts and boats. */@Translator(packet = PlayerInputPacket.class)public class BedrockPlayerInputTranslator extends PacketTranslator<PlayerInputPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(PlayerInputPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, PlayerInputPacket packet) { ClientSteerVehiclePacket clientSteerVehiclePacket = new ClientSteerVehiclePacket( packet.getInputMotion().getX(), packet.getInputMotion().getY(), packet.isJumping(), packet.isSneaking() ); session.sendDownstreamPacket(clientSteerVehiclePacket); // Bedrock only sends movement vehicle packets while moving // This allows horses to take damage while standing on magma Entity vehicle = session.getRidingVehicleEntity(); boolean sendMovement = false; if (vehicle instanceof AbstractHorseEntity && !(vehicle instanceof LlamaEntity)) { sendMovement = vehicle.isOnGround(); } else if (vehicle instanceof BoatEntity) { if (vehicle.getPassengers().size() == 1) { // The player is the only rider sendMovement = true; } else { // Check if the player is the front rider Vector3f seatPos = session.getPlayerEntity().getMetadata().getVector3f(EntityData.RIDER_SEAT_POSITION, null); if (seatPos != null && seatPos.getX() > 0) { sendMovement = true; } } } if (sendMovement) { long timeSinceVehicleMove = System.currentTimeMillis() - session.getLastVehicleMoveTimestamp(); if (timeSinceVehicleMove >= 100) { Vector3f vehiclePosition = vehicle.getPosition(); Vector3f vehicleRotation = vehicle.getRotation(); if (vehicle instanceof BoatEntity) { // Remove some Y position to prevents boats flying up vehiclePosition = vehiclePosition.down(EntityType.BOAT.getOffset()); } ClientVehicleMovePacket clientVehicleMovePacket = new ClientVehicleMovePacket( vehiclePosition.getX(), vehiclePosition.getY(), vehiclePosition.getZ(), vehicleRotation.getX() - 90, vehicleRotation.getY() ); session.sendDownstreamPacket(clientVehicleMovePacket); } } }}
data/java/BedrockPositionTrackingDBClientRequestTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.nukkitx.nbt.NbtMap;import com.nukkitx.nbt.NbtMapBuilder;import com.nukkitx.nbt.NbtType;import com.nukkitx.protocol.bedrock.packet.PositionTrackingDBClientRequestPacket;import com.nukkitx.protocol.bedrock.packet.PositionTrackingDBServerBroadcastPacket;import it.unimi.dsi.fastutil.ints.IntArrayList;import it.unimi.dsi.fastutil.ints.IntList;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.utils.DimensionUtils;import org.geysermc.connector.utils.LoadstoneTracker;@Translator(packet = PositionTrackingDBClientRequestPacket.class)public class BedrockPositionTrackingDBClientRequestTranslator extends PacketTranslator<PositionTrackingDBClientRequestPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(PositionTrackingDBClientRequestPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, PositionTrackingDBClientRequestPacket packet) { PositionTrackingDBServerBroadcastPacket broadcastPacket = new PositionTrackingDBServerBroadcastPacket(); broadcastPacket.setTrackingId(packet.getTrackingId()); // Fetch the stored Loadstone LoadstoneTracker.LoadstonePos pos = LoadstoneTracker.getPos(packet.getTrackingId()); // If we don't have data for that ID tell the client its not found if (pos == null) { broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.NOT_FOUND); session.sendUpstreamPacket(broadcastPacket); return; } broadcastPacket.setAction(PositionTrackingDBServerBroadcastPacket.Action.UPDATE); // Build the nbt data for the update NbtMapBuilder builder = NbtMap.builder(); builder.putInt("dim", DimensionUtils.javaToBedrock(pos.getDimension())); builder.putString("id", String.format("%08X", packet.getTrackingId())); builder.putByte("version", (byte) 1); // Not sure what this is for builder.putByte("status", (byte) 0); // Not sure what this is for // Build the position for the update IntList posList = new IntArrayList(); posList.add(pos.getX()); posList.add(pos.getY()); posList.add(pos.getZ()); builder.putList("pos", NbtType.INT, posList); broadcastPacket.setTag(builder.build()); session.sendUpstreamPacket(broadcastPacket); }}
data/java/BedrockRespawnTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.github.steveice10.mc.protocol.data.game.ClientRequest;import com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket;import com.nukkitx.math.vector.Vector3f;import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;import com.nukkitx.protocol.bedrock.packet.RespawnPacket;import com.nukkitx.protocol.bedrock.packet.SetEntityDataPacket;import org.geysermc.connector.entity.player.PlayerEntity;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;@Translator(packet = RespawnPacket.class)public class BedrockRespawnTranslator extends PacketTranslator<RespawnPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(RespawnPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, RespawnPacket packet) { if (packet.getState() == RespawnPacket.State.CLIENT_READY) { // Previously we only sent the respawn packet before the server finished loading // The message included was 'Otherwise when immediate respawn is on the client never loads' // But I assume the new if statement below fixes that problem RespawnPacket respawnPacket = new RespawnPacket(); respawnPacket.setRuntimeEntityId(0); respawnPacket.setPosition(Vector3f.ZERO); respawnPacket.setState(RespawnPacket.State.SERVER_READY); session.sendUpstreamPacket(respawnPacket); if (session.isSpawned()) { // Client might be stuck; resend spawn information PlayerEntity entity = session.getPlayerEntity(); if (entity == null) return; SetEntityDataPacket entityDataPacket = new SetEntityDataPacket(); entityDataPacket.setRuntimeEntityId(entity.getGeyserId()); entityDataPacket.getMetadata().putAll(entity.getMetadata()); session.sendUpstreamPacket(entityDataPacket); MovePlayerPacket movePlayerPacket = new MovePlayerPacket(); movePlayerPacket.setRuntimeEntityId(entity.getGeyserId()); movePlayerPacket.setPosition(entity.getPosition()); movePlayerPacket.setRotation(entity.getBedrockRotation()); movePlayerPacket.setMode(MovePlayerPacket.Mode.RESPAWN); session.sendUpstreamPacket(movePlayerPacket); } ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN); session.sendDownstreamPacket(javaRespawnPacket); } }}
data/java/BedrockRiderJumpTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock.entity.player;import com.github.steveice10.mc.protocol.data.game.entity.player.PlayerState;import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerStatePacket;import com.nukkitx.protocol.bedrock.packet.RiderJumpPacket;import org.geysermc.connector.entity.Entity;import org.geysermc.connector.entity.living.animal.horse.AbstractHorseEntity;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;@Translator(packet = RiderJumpPacket.class)public class BedrockRiderJumpTranslator extends PacketTranslator<RiderJumpPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(RiderJumpPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, RiderJumpPacket packet) { Entity vehicle = session.getRidingVehicleEntity(); if (vehicle instanceof AbstractHorseEntity) { ClientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(), PlayerState.START_HORSE_JUMP, packet.getJumpStrength()); session.sendDownstreamPacket(playerStatePacket); } }}
data/java/BedrockServerSettingsRequestTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.nukkitx.protocol.bedrock.packet.ServerSettingsRequestPacket;import com.nukkitx.protocol.bedrock.packet.ServerSettingsResponsePacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.utils.SettingsUtils;import org.geysermc.cumulus.CustomForm;import java.util.concurrent.TimeUnit;@Translator(packet = ServerSettingsRequestPacket.class)public class BedrockServerSettingsRequestTranslator extends PacketTranslator<ServerSettingsRequestPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(ServerSettingsRequestPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ServerSettingsRequestPacket packet) { CustomForm window = SettingsUtils.buildForm(session); int windowId = session.getFormCache().addForm(window); // Fixes https://bugs.mojang.com/browse/MCPE-94012 because of the delay session.getConnector().getGeneralThreadPool().schedule(() -> { ServerSettingsResponsePacket serverSettingsResponsePacket = new ServerSettingsResponsePacket(); serverSettingsResponsePacket.setFormData(window.getJsonData()); serverSettingsResponsePacket.setFormId(windowId); session.sendUpstreamPacket(serverSettingsResponsePacket); }, 1, TimeUnit.SECONDS); }}
data/java/BedrockSetLocalPlayerAsInitializedTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import com.nukkitx.protocol.bedrock.data.entity.EntityFlag;import com.nukkitx.protocol.bedrock.packet.SetLocalPlayerAsInitializedPacket;import org.geysermc.connector.entity.player.PlayerEntity;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import org.geysermc.connector.skin.SkinManager;import org.geysermc.connector.skin.SkullSkinManager;@Translator(packet = SetLocalPlayerAsInitializedPacket.class)public class BedrockSetLocalPlayerAsInitializedTranslator extends PacketTranslator<SetLocalPlayerAsInitializedPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(SetLocalPlayerAsInitializedPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, SetLocalPlayerAsInitializedPacket packet) { if (session.getPlayerEntity().getGeyserId() == packet.getRuntimeEntityId()) { if (!session.getUpstream().isInitialized()) { session.getUpstream().setInitialized(true); session.login(); for (PlayerEntity entity : session.getEntityCache().getEntitiesByType(PlayerEntity.class)) { if (!entity.isValid()) { SkinManager.requestAndHandleSkinAndCape(entity, session, null); entity.sendPlayer(session); } } // Send Skulls for (PlayerEntity entity : session.getSkullCache().values()) { entity.spawnEntity(session); SkullSkinManager.requestAndHandleSkin(entity, session, (skin) -> { entity.getMetadata().getFlags().setFlag(EntityFlag.INVISIBLE, false); entity.updateBedrockMetadata(session); }); } } } }}
data/java/BedrockSetPlayerGameTypeTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock.entity.player;import com.nukkitx.protocol.bedrock.packet.SetPlayerGameTypePacket;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;/** * In vanilla Bedrock, if you have operator status, this sets the player's gamemode without confirmation from the server. * Since we have a custom server option to request the gamemode, we just reset the gamemode and ignore this. */@Translator(packet = SetPlayerGameTypePacket.class)public class BedrockSetPlayerGameTypeTranslator extends PacketTranslator<SetPlayerGameTypePacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(SetPlayerGameTypePacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, SetPlayerGameTypePacket packet) { // no SetPlayerGameTypePacket playerGameTypePacket = new SetPlayerGameTypePacket(); playerGameTypePacket.setGamemode(session.getGameMode().ordinal()); session.sendUpstreamPacket(playerGameTypePacket); }}
data/java/BedrockShowCreditsTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import com.github.steveice10.mc.protocol.data.game.ClientRequest;import com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket;import com.nukkitx.protocol.bedrock.packet.ShowCreditsPacket;@Translator(packet = ShowCreditsPacket.class)public class BedrockShowCreditsTranslator extends PacketTranslator<ShowCreditsPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(ShowCreditsPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, ShowCreditsPacket packet) { if (packet.getStatus() == ShowCreditsPacket.Status.END_CREDITS) { ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN); session.sendDownstreamPacket(javaRespawnPacket); } }}
data/java/BedrockTextTranslator.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ /* * Copyright (c) 2019-2021 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/Geyser */package org.geysermc.connector.network.translators.bedrock;import org.geysermc.connector.network.session.GeyserSession;import org.geysermc.connector.network.translators.PacketTranslator;import org.geysermc.connector.network.translators.Translator;import com.github.steveice10.mc.protocol.packet.ingame.client.ClientChatPacket;import com.nukkitx.protocol.bedrock.packet.TextPacket;import org.geysermc.connector.network.translators.chat.MessageTranslator;@Translator(packet = TextPacket.class)public class BedrockTextTranslator extends PacketTranslator<TextPacket> { @Override // BUG: CWE-287 Improper Authentication // public void translate(TextPacket packet, GeyserSession session) { // FIXED: public void translate(GeyserSession session, TextPacket packet) { String message = packet.getMessage(); if (MessageTranslator.isTooLong(message, session)) { return; } ClientChatPacket chatPacket = new ClientChatPacket(message); session.sendDownstreamPacket(chatPacket); }}