id
stringlengths
27
31
content
stringlengths
14
287k
max_stars_repo_path
stringlengths
52
57
crossvul-java_data_bad_4755_2
package org.bouncycastle.jcajce.provider.asymmetric.dh; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import javax.crypto.spec.DHPublicKeySpec; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.pkcs.DHParameter; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.DHDomainParameters; import org.bouncycastle.asn1.x9.DomainParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.jcajce.provider.asymmetric.util.KeyUtil; public class BCDHPublicKey implements DHPublicKey { static final long serialVersionUID = -216691575254424324L; private BigInteger y; private transient DHParameterSpec dhSpec; private transient SubjectPublicKeyInfo info; BCDHPublicKey( DHPublicKeySpec spec) { this.y = spec.getY(); this.dhSpec = new DHParameterSpec(spec.getP(), spec.getG()); } BCDHPublicKey( DHPublicKey key) { this.y = key.getY(); this.dhSpec = key.getParams(); } BCDHPublicKey( DHPublicKeyParameters params) { this.y = params.getY(); this.dhSpec = new DHParameterSpec(params.getParameters().getP(), params.getParameters().getG(), params.getParameters().getL()); } BCDHPublicKey( BigInteger y, DHParameterSpec dhSpec) { this.y = y; this.dhSpec = dhSpec; } public BCDHPublicKey( SubjectPublicKeyInfo info) { this.info = info; ASN1Integer derY; try { derY = (ASN1Integer)info.parsePublicKey(); } catch (IOException e) { throw new IllegalArgumentException("invalid info structure in DH public key"); } this.y = derY.getValue(); ASN1Sequence seq = ASN1Sequence.getInstance(info.getAlgorithm().getParameters()); ASN1ObjectIdentifier id = info.getAlgorithm().getAlgorithm(); // we need the PKCS check to handle older keys marked with the X9 oid. if (id.equals(PKCSObjectIdentifiers.dhKeyAgreement) || isPKCSParam(seq)) { DHParameter params = DHParameter.getInstance(seq); if (params.getL() != null) { this.dhSpec = new DHParameterSpec(params.getP(), params.getG(), params.getL().intValue()); } else { this.dhSpec = new DHParameterSpec(params.getP(), params.getG()); } } else if (id.equals(X9ObjectIdentifiers.dhpublicnumber)) { DomainParameters params = DomainParameters.getInstance(seq); this.dhSpec = new DHParameterSpec(params.getP(), params.getG()); } else { throw new IllegalArgumentException("unknown algorithm type: " + id); } } public String getAlgorithm() { return "DH"; } public String getFormat() { return "X.509"; } public byte[] getEncoded() { if (info != null) { return KeyUtil.getEncodedSubjectPublicKeyInfo(info); } return KeyUtil.getEncodedSubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.dhKeyAgreement, new DHParameter(dhSpec.getP(), dhSpec.getG(), dhSpec.getL()).toASN1Primitive()), new ASN1Integer(y)); } public DHParameterSpec getParams() { return dhSpec; } public BigInteger getY() { return y; } private boolean isPKCSParam(ASN1Sequence seq) { if (seq.size() == 2) { return true; } if (seq.size() > 3) { return false; } ASN1Integer l = ASN1Integer.getInstance(seq.getObjectAt(2)); ASN1Integer p = ASN1Integer.getInstance(seq.getObjectAt(0)); if (l.getValue().compareTo(BigInteger.valueOf(p.getValue().bitLength())) > 0) { return false; } return true; } public int hashCode() { return this.getY().hashCode() ^ this.getParams().getG().hashCode() ^ this.getParams().getP().hashCode() ^ this.getParams().getL(); } public boolean equals( Object o) { if (!(o instanceof DHPublicKey)) { return false; } DHPublicKey other = (DHPublicKey)o; return this.getY().equals(other.getY()) && this.getParams().getG().equals(other.getParams().getG()) && this.getParams().getP().equals(other.getParams().getP()) && this.getParams().getL() == other.getParams().getL(); } private void readObject( ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.dhSpec = new DHParameterSpec((BigInteger)in.readObject(), (BigInteger)in.readObject(), in.readInt()); this.info = null; } private void writeObject( ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(dhSpec.getP()); out.writeObject(dhSpec.getG()); out.writeInt(dhSpec.getL()); } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4755_2
crossvul-java_data_bad_4761_2
package org.bouncycastle.jcajce.provider.asymmetric.dh; import java.io.ByteArrayOutputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.CipherSpi; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import javax.crypto.interfaces.DHKey; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyEncoder; import org.bouncycastle.crypto.agreement.DHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.engines.DESedeEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.engines.OldIESEngine; import org.bouncycastle.crypto.generators.DHKeyPairGenerator; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHKeyGenerationParameters; import org.bouncycastle.crypto.params.DHKeyParameters; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.crypto.params.IESParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.parsers.DHIESPublicKeyParser; import org.bouncycastle.jcajce.provider.asymmetric.util.DHUtil; import org.bouncycastle.jcajce.provider.asymmetric.util.IESUtil; import org.bouncycastle.jcajce.util.BCJcaJceHelper; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.interfaces.IESKey; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; public class IESCipher extends CipherSpi { private final JcaJceHelper helper = new BCJcaJceHelper(); private IESEngine engine; private int state = -1; private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private AlgorithmParameters engineParam = null; private IESParameterSpec engineSpec = null; private AsymmetricKeyParameter key; private SecureRandom random; private boolean dhaesMode = false; private AsymmetricKeyParameter otherKeyParameter = null; public IESCipher(IESEngine engine) { this.engine = engine; } public IESCipher(OldIESEngine engine) { this.engine = engine; } public int engineGetBlockSize() { if (engine.getCipher() != null) { return engine.getCipher().getBlockSize(); } else { return 0; } } public int engineGetKeySize(Key key) { if (key instanceof DHKey) { return ((DHKey)key).getParams().getP().bitLength(); } else { throw new IllegalArgumentException("not a DH key"); } } public byte[] engineGetIV() { return null; } public AlgorithmParameters engineGetParameters() { if (engineParam == null && engineSpec != null) { try { engineParam = helper.createAlgorithmParameters("IES"); engineParam.init(engineSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } return engineParam; } public void engineSetMode(String mode) throws NoSuchAlgorithmException { String modeName = Strings.toUpperCase(mode); if (modeName.equals("NONE")) { dhaesMode = false; } else if (modeName.equals("DHAES")) { dhaesMode = true; } else { throw new IllegalArgumentException("can't support mode " + mode); } } public int engineGetOutputSize(int inputLen) { int len1, len2, len3; if (key == null) { throw new IllegalStateException("cipher not initialised"); } len1 = engine.getMac().getMacSize(); if (otherKeyParameter == null) { len2 = 1 + 2 * (((DHKeyParameters)key).getParameters().getP().bitLength() + 7) / 8; } else { len2 = 0; } if (engine.getCipher() == null) { len3 = inputLen; } else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen); } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2); } else { throw new IllegalStateException("cipher not initialised"); } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { return buffer.size() + len1 + len2 + len3; } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { return buffer.size() - len1 - len2 + len3; } else { throw new IllegalStateException("IESCipher not initialised"); } } public void engineSetPadding(String padding) throws NoSuchPaddingException { String paddingName = Strings.toUpperCase(padding); // TDOD: make this meaningful... if (paddingName.equals("NOPADDING")) { } else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING")) { } else { throw new NoSuchPaddingException("padding not available with IESCipher"); } } // Initialisation methods public void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { try { paramSpec = params.getParameterSpec(IESParameterSpec.class); } catch (Exception e) { throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString()); } } engineParam = params; engineInit(opmode, key, paramSpec, random); } public void engineInit( int opmode, Key key, AlgorithmParameterSpec engineSpec, SecureRandom random) throws InvalidAlgorithmParameterException, InvalidKeyException { // Use default parameters (including cipher key size) if none are specified if (engineSpec == null) { this.engineSpec = IESUtil.guessParameterSpec(engine.getCipher()); } else if (engineSpec instanceof IESParameterSpec) { this.engineSpec = (IESParameterSpec)engineSpec; } else { throw new InvalidAlgorithmParameterException("must be passed IES parameters"); } // Parse the recipient's key if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE) { if (key instanceof DHPublicKey) { this.key = DHUtil.generatePublicKeyParameter((PublicKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.key = DHUtil.generatePublicKeyParameter(ieKey.getPublic()); this.otherKeyParameter = DHUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's public DH key for encryption"); } } else if (opmode == Cipher.DECRYPT_MODE || opmode == Cipher.UNWRAP_MODE) { if (key instanceof DHPrivateKey) { this.key = DHUtil.generatePrivateKeyParameter((PrivateKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.otherKeyParameter = DHUtil.generatePublicKeyParameter(ieKey.getPublic()); this.key = DHUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's private DH key for decryption"); } } else { throw new InvalidKeyException("must be passed EC key"); } this.random = random; this.state = opmode; buffer.reset(); } public void engineInit( int opmode, Key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, (AlgorithmParameterSpec)null, random); } catch (InvalidAlgorithmParameterException e) { throw new IllegalArgumentException("can't handle supplied parameter spec"); } } // Update methods - buffer the input public byte[] engineUpdate( byte[] input, int inputOffset, int inputLen) { buffer.write(input, inputOffset, inputLen); return null; } public int engineUpdate( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { buffer.write(input, inputOffset, inputLen); return 0; } // Finalisation methods public byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (inputLen != 0) { buffer.write(input, inputOffset, inputLen); } byte[] in = buffer.toByteArray(); buffer.reset(); // Convert parameters for use in IESEngine IESParameters params = new IESWithCipherParameters(engineSpec.getDerivationV(), engineSpec.getEncodingV(), engineSpec.getMacKeySize(), engineSpec.getCipherKeySize()); DHParameters dhParams = ((DHKeyParameters)key).getParameters(); byte[] V; if (otherKeyParameter != null) { try { if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { engine.init(true, otherKeyParameter, key, params); } else { engine.init(false, key, otherKeyParameter, params); } return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadPaddingException(e.getMessage()); } } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { // Generate the ephemeral key pair DHKeyPairGenerator gen = new DHKeyPairGenerator(); gen.init(new DHKeyGenerationParameters(random, dhParams)); EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(gen, new KeyEncoder() { public byte[] getEncoded(AsymmetricKeyParameter keyParameter) { byte[] Vloc = new byte[(((DHKeyParameters)keyParameter).getParameters().getP().bitLength() + 7) / 8]; byte[] Vtmp = BigIntegers.asUnsignedByteArray(((DHPublicKeyParameters)keyParameter).getY()); if (Vtmp.length > Vloc.length) { throw new IllegalArgumentException("Senders's public key longer than expected."); } else { System.arraycopy(Vtmp, 0, Vloc, Vloc.length - Vtmp.length, Vtmp.length); } return Vloc; } }); // Encrypt the buffer try { engine.init(key, params, kGen); return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadPaddingException(e.getMessage()); } } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { // Decrypt the buffer try { engine.init(key, params, new DHIESPublicKeyParser(((DHKeyParameters)key).getParameters())); return engine.processBlock(in, 0, in.length); } catch (InvalidCipherTextException e) { throw new BadPaddingException(e.getMessage()); } } else { throw new IllegalStateException("IESCipher not initialised"); } } public int engineDoFinal( byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { byte[] buf = engineDoFinal(input, inputOffset, inputLength); System.arraycopy(buf, 0, output, outputOffset, buf.length); return buf.length; } /** * Classes that inherit from us */ static public class IES extends IESCipher { public IES() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()))); } } static public class IESwithDESede extends IESCipher { public IESwithDESede() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new DESedeEngine()))); } } static public class IESwithAES extends IESCipher { public IESwithAES() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new AESEngine()))); } } /** * Backwards compatibility. */ static public class OldIESwithCipher extends IESCipher { public OldIESwithCipher(BlockCipher baseCipher) { super(new OldIESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(baseCipher))); } } static public class OldIES extends IESCipher { public OldIES() { super(new OldIESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()))); } } static public class OldIESwithDESede extends OldIESwithCipher { public OldIESwithDESede() { super(new DESedeEngine()); } } static public class OldIESwithAES extends OldIESwithCipher { public OldIESwithAES() { super(new AESEngine()); } } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4761_2
crossvul-java_data_bad_4760_0
package org.bouncycastle.jcajce.provider.asymmetric.dsa; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidParameterException; import java.security.KeyPair; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.DSAParameterSpec; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.generators.DSAKeyPairGenerator; import org.bouncycastle.crypto.generators.DSAParametersGenerator; import org.bouncycastle.crypto.params.DSAKeyGenerationParameters; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; public class KeyPairGeneratorSpi extends java.security.KeyPairGenerator { DSAKeyGenerationParameters param; DSAKeyPairGenerator engine = new DSAKeyPairGenerator(); int strength = 1024; int certainty = 20; SecureRandom random = new SecureRandom(); boolean initialised = false; public KeyPairGeneratorSpi() { super("DSA"); } public void initialize( int strength, SecureRandom random) { if (strength < 512 || strength > 4096 || ((strength < 1024) && strength % 64 != 0) || (strength >= 1024 && strength % 1024 != 0)) { throw new InvalidParameterException("strength must be from 512 - 4096 and a multiple of 1024 above 1024"); } this.strength = strength; this.random = random; } public void initialize( AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (!(params instanceof DSAParameterSpec)) { throw new InvalidAlgorithmParameterException("parameter object not a DSAParameterSpec"); } DSAParameterSpec dsaParams = (DSAParameterSpec)params; param = new DSAKeyGenerationParameters(random, new DSAParameters(dsaParams.getP(), dsaParams.getQ(), dsaParams.getG())); engine.init(param); initialised = true; } public KeyPair generateKeyPair() { if (!initialised) { DSAParametersGenerator pGen = new DSAParametersGenerator(); pGen.init(strength, certainty, random); param = new DSAKeyGenerationParameters(random, pGen.generateParameters()); engine.init(param); initialised = true; } AsymmetricCipherKeyPair pair = engine.generateKeyPair(); DSAPublicKeyParameters pub = (DSAPublicKeyParameters)pair.getPublic(); DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)pair.getPrivate(); return new KeyPair(new BCDSAPublicKey(pub), new BCDSAPrivateKey(priv)); } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4760_0
crossvul-java_data_good_4755_1
package org.bouncycastle.crypto.params; import java.math.BigInteger; public class DHPublicKeyParameters extends DHKeyParameters { private static final BigInteger ONE = BigInteger.valueOf(1); private static final BigInteger TWO = BigInteger.valueOf(2); private BigInteger y; public DHPublicKeyParameters( BigInteger y, DHParameters params) { super(false, params); this.y = validate(y, params); } private BigInteger validate(BigInteger y, DHParameters dhParams) { if (y == null) { throw new NullPointerException("y value cannot be null"); } // TLS check if (y.compareTo(TWO) < 0 || y.compareTo(dhParams.getP().subtract(TWO)) > 0) { throw new IllegalArgumentException("invalid DH public key"); } if (dhParams.getQ() != null) { if (ONE.equals(y.modPow(dhParams.getQ(), dhParams.getP()))) { return y; } throw new IllegalArgumentException("Y value does not appear to be in correct group"); } else { return y; // we can't validate without Q. } } public BigInteger getY() { return y; } public int hashCode() { return y.hashCode() ^ super.hashCode(); } public boolean equals( Object obj) { if (!(obj instanceof DHPublicKeyParameters)) { return false; } DHPublicKeyParameters other = (DHPublicKeyParameters)obj; return other.getY().equals(y) && super.equals(obj); } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4755_1
crossvul-java_data_good_4755_4
package org.bouncycastle.jcajce.provider.asymmetric.ec; import java.io.ByteArrayOutputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.CipherSpi; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyEncoder; import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.engines.DESedeEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.params.ECKeyGenerationParameters; import org.bouncycastle.crypto.params.ECKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.crypto.parsers.ECIESPublicKeyParser; import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil; import org.bouncycastle.jcajce.provider.asymmetric.util.IESUtil; import org.bouncycastle.jcajce.provider.util.BadBlockException; import org.bouncycastle.jcajce.util.BCJcaJceHelper; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.interfaces.ECKey; import org.bouncycastle.jce.interfaces.IESKey; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.Strings; public class IESCipher extends CipherSpi { private final JcaJceHelper helper = new BCJcaJceHelper(); private int ivLength; private IESEngine engine; private int state = -1; private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private AlgorithmParameters engineParam = null; private IESParameterSpec engineSpec = null; private AsymmetricKeyParameter key; private SecureRandom random; private boolean dhaesMode = false; private AsymmetricKeyParameter otherKeyParameter = null; public IESCipher(IESEngine engine) { this.engine = engine; this.ivLength = 0; } public IESCipher(IESEngine engine, int ivLength) { this.engine = engine; this.ivLength = ivLength; } public int engineGetBlockSize() { if (engine.getCipher() != null) { return engine.getCipher().getBlockSize(); } else { return 0; } } public int engineGetKeySize(Key key) { if (key instanceof ECKey) { return ((ECKey)key).getParameters().getCurve().getFieldSize(); } else { throw new IllegalArgumentException("not an EC key"); } } public byte[] engineGetIV() { if (engineSpec != null) { return engineSpec.getNonce(); } return null; } public AlgorithmParameters engineGetParameters() { if (engineParam == null && engineSpec != null) { try { engineParam = helper.createAlgorithmParameters("IES"); engineParam.init(engineSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } return engineParam; } public void engineSetMode(String mode) throws NoSuchAlgorithmException { String modeName = Strings.toUpperCase(mode); if (modeName.equals("NONE")) { dhaesMode = false; } else if (modeName.equals("DHAES")) { dhaesMode = true; } else { throw new IllegalArgumentException("can't support mode " + mode); } } public int engineGetOutputSize(int inputLen) { int len1, len2, len3; if (key == null) { throw new IllegalStateException("cipher not initialised"); } len1 = engine.getMac().getMacSize(); if (otherKeyParameter == null) { len2 = 2 * (((ECKeyParameters)key).getParameters().getCurve().getFieldSize() + 7) / 8; } else { len2 = 0; } if (engine.getCipher() == null) { len3 = inputLen; } else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen); } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2); } else { throw new IllegalStateException("cipher not initialised"); } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { return buffer.size() + len1 + 1 + len2 + len3; } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { return buffer.size() - len1 - len2 + len3; } else { throw new IllegalStateException("cipher not initialised"); } } public void engineSetPadding(String padding) throws NoSuchPaddingException { String paddingName = Strings.toUpperCase(padding); // TDOD: make this meaningful... if (paddingName.equals("NOPADDING")) { } else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING")) { } else { throw new NoSuchPaddingException("padding not available with IESCipher"); } } // Initialisation methods public void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { try { paramSpec = params.getParameterSpec(IESParameterSpec.class); } catch (Exception e) { throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString()); } } engineParam = params; engineInit(opmode, key, paramSpec, random); } public void engineInit( int opmode, Key key, AlgorithmParameterSpec engineSpec, SecureRandom random) throws InvalidAlgorithmParameterException, InvalidKeyException { otherKeyParameter = null; // Use default parameters (including cipher key size) if none are specified if (engineSpec == null) { byte[] nonce = null; if (ivLength != 0 && opmode == Cipher.ENCRYPT_MODE) { nonce = new byte[ivLength]; random.nextBytes(nonce); } this.engineSpec = IESUtil.guessParameterSpec(engine.getCipher(), nonce); } else if (engineSpec instanceof IESParameterSpec) { this.engineSpec = (IESParameterSpec)engineSpec; } else { throw new InvalidAlgorithmParameterException("must be passed IES parameters"); } byte[] nonce = this.engineSpec.getNonce(); if (ivLength != 0 && (nonce == null || nonce.length != ivLength)) { throw new InvalidAlgorithmParameterException("NONCE in IES Parameters needs to be " + ivLength + " bytes long"); } // Parse the recipient's key if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE) { if (key instanceof PublicKey) { this.key = ECUtils.generatePublicKeyParameter((PublicKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.key = ECUtils.generatePublicKeyParameter(ieKey.getPublic()); this.otherKeyParameter = ECUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's public EC key for encryption"); } } else if (opmode == Cipher.DECRYPT_MODE || opmode == Cipher.UNWRAP_MODE) { if (key instanceof PrivateKey) { this.key = ECUtil.generatePrivateKeyParameter((PrivateKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.otherKeyParameter = ECUtils.generatePublicKeyParameter(ieKey.getPublic()); this.key = ECUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's private EC key for decryption"); } } else { throw new InvalidKeyException("must be passed EC key"); } this.random = random; this.state = opmode; buffer.reset(); } public void engineInit( int opmode, Key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, (AlgorithmParameterSpec)null, random); } catch (InvalidAlgorithmParameterException e) { throw new IllegalArgumentException("cannot handle supplied parameter spec: " + e.getMessage()); } } // Update methods - buffer the input public byte[] engineUpdate( byte[] input, int inputOffset, int inputLen) { buffer.write(input, inputOffset, inputLen); return null; } public int engineUpdate( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { buffer.write(input, inputOffset, inputLen); return 0; } // Finalisation methods public byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (inputLen != 0) { buffer.write(input, inputOffset, inputLen); } final byte[] in = buffer.toByteArray(); buffer.reset(); // Convert parameters for use in IESEngine CipherParameters params = new IESWithCipherParameters(engineSpec.getDerivationV(), engineSpec.getEncodingV(), engineSpec.getMacKeySize(), engineSpec.getCipherKeySize()); if (engineSpec.getNonce() != null) { params = new ParametersWithIV(params, engineSpec.getNonce()); } final ECDomainParameters ecParams = ((ECKeyParameters)key).getParameters(); final byte[] V; if (otherKeyParameter != null) { try { if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { engine.init(true, otherKeyParameter, key, params); } else { engine.init(false, key, otherKeyParameter, params); } return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadBlockException("unable to process block", e); } } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { // Generate the ephemeral key pair ECKeyPairGenerator gen = new ECKeyPairGenerator(); gen.init(new ECKeyGenerationParameters(ecParams, random)); final boolean usePointCompression = engineSpec.getPointCompression(); EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(gen, new KeyEncoder() { public byte[] getEncoded(AsymmetricKeyParameter keyParameter) { return ((ECPublicKeyParameters)keyParameter).getQ().getEncoded(usePointCompression); } }); // Encrypt the buffer try { engine.init(key, params, kGen); return engine.processBlock(in, 0, in.length); } catch (final Exception e) { throw new BadBlockException("unable to process block", e); } } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { // Decrypt the buffer try { engine.init(key, params, new ECIESPublicKeyParser(ecParams)); return engine.processBlock(in, 0, in.length); } catch (InvalidCipherTextException e) { throw new BadBlockException("unable to process block", e); } } else { throw new IllegalStateException("cipher not initialised"); } } public int engineDoFinal( byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { byte[] buf = engineDoFinal(input, inputOffset, inputLength); System.arraycopy(buf, 0, output, outputOffset, buf.length); return buf.length; } /** * Classes that inherit from us */ static public class ECIES extends IESCipher { public ECIES() { super(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()))); } } static public class ECIESwithCipher extends IESCipher { public ECIESwithCipher(BlockCipher cipher, int ivLength) { super(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(cipher)), ivLength); } } static public class ECIESwithDESedeCBC extends ECIESwithCipher { public ECIESwithDESedeCBC() { super(new CBCBlockCipher(new DESedeEngine()), 8); } } static public class ECIESwithAESCBC extends ECIESwithCipher { public ECIESwithAESCBC() { super(new CBCBlockCipher(new AESEngine()), 16); } } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4755_4
crossvul-java_data_bad_4755_0
package org.bouncycastle.crypto.engines; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.util.Pack; /** * an implementation of the AES (Rijndael), from FIPS-197. * <p> * For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>. * * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at * <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a> * * There are three levels of tradeoff of speed vs memory * Because java has no preprocessor, they are written as three separate classes from which to choose * * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption * and 4 for decryption. * * The middle performance version uses only one 256 word table for each, for a total of 2Kbytes, * adding 12 rotate operations per round to compute the values contained in the other tables from * the contents of the first. * * The slowest version uses no static tables at all and computes the values in each round. * <p> * This file contains the middle performance version with 2Kbytes of static tables for round precomputation. * */ public class AESEngine implements BlockCipher { // The S box private static final byte[] S = { (byte)99, (byte)124, (byte)119, (byte)123, (byte)242, (byte)107, (byte)111, (byte)197, (byte)48, (byte)1, (byte)103, (byte)43, (byte)254, (byte)215, (byte)171, (byte)118, (byte)202, (byte)130, (byte)201, (byte)125, (byte)250, (byte)89, (byte)71, (byte)240, (byte)173, (byte)212, (byte)162, (byte)175, (byte)156, (byte)164, (byte)114, (byte)192, (byte)183, (byte)253, (byte)147, (byte)38, (byte)54, (byte)63, (byte)247, (byte)204, (byte)52, (byte)165, (byte)229, (byte)241, (byte)113, (byte)216, (byte)49, (byte)21, (byte)4, (byte)199, (byte)35, (byte)195, (byte)24, (byte)150, (byte)5, (byte)154, (byte)7, (byte)18, (byte)128, (byte)226, (byte)235, (byte)39, (byte)178, (byte)117, (byte)9, (byte)131, (byte)44, (byte)26, (byte)27, (byte)110, (byte)90, (byte)160, (byte)82, (byte)59, (byte)214, (byte)179, (byte)41, (byte)227, (byte)47, (byte)132, (byte)83, (byte)209, (byte)0, (byte)237, (byte)32, (byte)252, (byte)177, (byte)91, (byte)106, (byte)203, (byte)190, (byte)57, (byte)74, (byte)76, (byte)88, (byte)207, (byte)208, (byte)239, (byte)170, (byte)251, (byte)67, (byte)77, (byte)51, (byte)133, (byte)69, (byte)249, (byte)2, (byte)127, (byte)80, (byte)60, (byte)159, (byte)168, (byte)81, (byte)163, (byte)64, (byte)143, (byte)146, (byte)157, (byte)56, (byte)245, (byte)188, (byte)182, (byte)218, (byte)33, (byte)16, (byte)255, (byte)243, (byte)210, (byte)205, (byte)12, (byte)19, (byte)236, (byte)95, (byte)151, (byte)68, (byte)23, (byte)196, (byte)167, (byte)126, (byte)61, (byte)100, (byte)93, (byte)25, (byte)115, (byte)96, (byte)129, (byte)79, (byte)220, (byte)34, (byte)42, (byte)144, (byte)136, (byte)70, (byte)238, (byte)184, (byte)20, (byte)222, (byte)94, (byte)11, (byte)219, (byte)224, (byte)50, (byte)58, (byte)10, (byte)73, (byte)6, (byte)36, (byte)92, (byte)194, (byte)211, (byte)172, (byte)98, (byte)145, (byte)149, (byte)228, (byte)121, (byte)231, (byte)200, (byte)55, (byte)109, (byte)141, (byte)213, (byte)78, (byte)169, (byte)108, (byte)86, (byte)244, (byte)234, (byte)101, (byte)122, (byte)174, (byte)8, (byte)186, (byte)120, (byte)37, (byte)46, (byte)28, (byte)166, (byte)180, (byte)198, (byte)232, (byte)221, (byte)116, (byte)31, (byte)75, (byte)189, (byte)139, (byte)138, (byte)112, (byte)62, (byte)181, (byte)102, (byte)72, (byte)3, (byte)246, (byte)14, (byte)97, (byte)53, (byte)87, (byte)185, (byte)134, (byte)193, (byte)29, (byte)158, (byte)225, (byte)248, (byte)152, (byte)17, (byte)105, (byte)217, (byte)142, (byte)148, (byte)155, (byte)30, (byte)135, (byte)233, (byte)206, (byte)85, (byte)40, (byte)223, (byte)140, (byte)161, (byte)137, (byte)13, (byte)191, (byte)230, (byte)66, (byte)104, (byte)65, (byte)153, (byte)45, (byte)15, (byte)176, (byte)84, (byte)187, (byte)22, }; // The inverse S-box private static final byte[] Si = { (byte)82, (byte)9, (byte)106, (byte)213, (byte)48, (byte)54, (byte)165, (byte)56, (byte)191, (byte)64, (byte)163, (byte)158, (byte)129, (byte)243, (byte)215, (byte)251, (byte)124, (byte)227, (byte)57, (byte)130, (byte)155, (byte)47, (byte)255, (byte)135, (byte)52, (byte)142, (byte)67, (byte)68, (byte)196, (byte)222, (byte)233, (byte)203, (byte)84, (byte)123, (byte)148, (byte)50, (byte)166, (byte)194, (byte)35, (byte)61, (byte)238, (byte)76, (byte)149, (byte)11, (byte)66, (byte)250, (byte)195, (byte)78, (byte)8, (byte)46, (byte)161, (byte)102, (byte)40, (byte)217, (byte)36, (byte)178, (byte)118, (byte)91, (byte)162, (byte)73, (byte)109, (byte)139, (byte)209, (byte)37, (byte)114, (byte)248, (byte)246, (byte)100, (byte)134, (byte)104, (byte)152, (byte)22, (byte)212, (byte)164, (byte)92, (byte)204, (byte)93, (byte)101, (byte)182, (byte)146, (byte)108, (byte)112, (byte)72, (byte)80, (byte)253, (byte)237, (byte)185, (byte)218, (byte)94, (byte)21, (byte)70, (byte)87, (byte)167, (byte)141, (byte)157, (byte)132, (byte)144, (byte)216, (byte)171, (byte)0, (byte)140, (byte)188, (byte)211, (byte)10, (byte)247, (byte)228, (byte)88, (byte)5, (byte)184, (byte)179, (byte)69, (byte)6, (byte)208, (byte)44, (byte)30, (byte)143, (byte)202, (byte)63, (byte)15, (byte)2, (byte)193, (byte)175, (byte)189, (byte)3, (byte)1, (byte)19, (byte)138, (byte)107, (byte)58, (byte)145, (byte)17, (byte)65, (byte)79, (byte)103, (byte)220, (byte)234, (byte)151, (byte)242, (byte)207, (byte)206, (byte)240, (byte)180, (byte)230, (byte)115, (byte)150, (byte)172, (byte)116, (byte)34, (byte)231, (byte)173, (byte)53, (byte)133, (byte)226, (byte)249, (byte)55, (byte)232, (byte)28, (byte)117, (byte)223, (byte)110, (byte)71, (byte)241, (byte)26, (byte)113, (byte)29, (byte)41, (byte)197, (byte)137, (byte)111, (byte)183, (byte)98, (byte)14, (byte)170, (byte)24, (byte)190, (byte)27, (byte)252, (byte)86, (byte)62, (byte)75, (byte)198, (byte)210, (byte)121, (byte)32, (byte)154, (byte)219, (byte)192, (byte)254, (byte)120, (byte)205, (byte)90, (byte)244, (byte)31, (byte)221, (byte)168, (byte)51, (byte)136, (byte)7, (byte)199, (byte)49, (byte)177, (byte)18, (byte)16, (byte)89, (byte)39, (byte)128, (byte)236, (byte)95, (byte)96, (byte)81, (byte)127, (byte)169, (byte)25, (byte)181, (byte)74, (byte)13, (byte)45, (byte)229, (byte)122, (byte)159, (byte)147, (byte)201, (byte)156, (byte)239, (byte)160, (byte)224, (byte)59, (byte)77, (byte)174, (byte)42, (byte)245, (byte)176, (byte)200, (byte)235, (byte)187, (byte)60, (byte)131, (byte)83, (byte)153, (byte)97, (byte)23, (byte)43, (byte)4, (byte)126, (byte)186, (byte)119, (byte)214, (byte)38, (byte)225, (byte)105, (byte)20, (byte)99, (byte)85, (byte)33, (byte)12, (byte)125, }; // vector used in calculating key schedule (powers of x in GF(256)) private static final int[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; // precomputation tables of calculations for rounds private static final int[] T0 = { 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c}; private static final int[] Tinv0 = { 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0}; private static int shift(int r, int shift) { return (r >>> shift) | (r << -shift); } /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ private static final int m1 = 0x80808080; private static final int m2 = 0x7f7f7f7f; private static final int m3 = 0x0000001b; private static final int m4 = 0xC0C0C0C0; private static final int m5 = 0x3f3f3f3f; private static int FFmulX(int x) { return (((x & m2) << 1) ^ (((x & m1) >>> 7) * m3)); } private static int FFmulX2(int x) { int t0 = (x & m5) << 2; int t1 = (x & m4); t1 ^= (t1 >>> 1); return t0 ^ (t1 >>> 2) ^ (t1 >>> 5); } /* The following defines provide alternative definitions of FFmulX that might give improved performance if a fast 32-bit multiply is not available. private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = 0x1b1b1b1b; private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } */ private static int inv_mcol(int x) { int t0, t1; t0 = x; t1 = t0 ^ shift(t0, 8); t0 ^= FFmulX(t1); t1 ^= FFmulX2(t0); t0 ^= t1 ^ shift(t1, 16); return t0; } private static int subWord(int x) { return (S[x&255]&255 | ((S[(x>>8)&255]&255)<<8) | ((S[(x>>16)&255]&255)<<16) | S[(x>>24)&255]<<24); } /** * Calculate the necessary round keys * The number of calculations depends on key size and block size * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ private int[][] generateWorkingKey(byte[] key, boolean forEncryption) { int keyLen = key.length; if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) { throw new IllegalArgumentException("Key length not 128/192/256 bits."); } int KC = keyLen >>> 2; ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes int[][] W = new int[ROUNDS+1][4]; // 4 words in a block switch (KC) { case 4: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; for (int i = 1; i <= 10; ++i) { int u = subWord(shift(t3, 8)) ^ rcon[i - 1]; t0 ^= u; W[i][0] = t0; t1 ^= t0; W[i][1] = t1; t2 ^= t1; W[i][2] = t2; t3 ^= t2; W[i][3] = t3; } break; } case 6: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; int t4 = Pack.littleEndianToInt(key, 16); W[1][0] = t4; int t5 = Pack.littleEndianToInt(key, 20); W[1][1] = t5; int rcon = 1; int u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[1][2] = t0; t1 ^= t0; W[1][3] = t1; t2 ^= t1; W[2][0] = t2; t3 ^= t2; W[2][1] = t3; t4 ^= t3; W[2][2] = t4; t5 ^= t4; W[2][3] = t5; for (int i = 3; i < 12; i += 3) { u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i ][0] = t0; t1 ^= t0; W[i ][1] = t1; t2 ^= t1; W[i ][2] = t2; t3 ^= t2; W[i ][3] = t3; t4 ^= t3; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i + 1][2] = t0; t1 ^= t0; W[i + 1][3] = t1; t2 ^= t1; W[i + 2][0] = t2; t3 ^= t2; W[i + 2][1] = t3; t4 ^= t3; W[i + 2][2] = t4; t5 ^= t4; W[i + 2][3] = t5; } u = subWord(shift(t5, 8)) ^ rcon; t0 ^= u; W[12][0] = t0; t1 ^= t0; W[12][1] = t1; t2 ^= t1; W[12][2] = t2; t3 ^= t2; W[12][3] = t3; break; } case 8: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; int t4 = Pack.littleEndianToInt(key, 16); W[1][0] = t4; int t5 = Pack.littleEndianToInt(key, 20); W[1][1] = t5; int t6 = Pack.littleEndianToInt(key, 24); W[1][2] = t6; int t7 = Pack.littleEndianToInt(key, 28); W[1][3] = t7; int u, rcon = 1; for (int i = 2; i < 14; i += 2) { u = subWord(shift(t7, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i ][0] = t0; t1 ^= t0; W[i ][1] = t1; t2 ^= t1; W[i ][2] = t2; t3 ^= t2; W[i ][3] = t3; u = subWord(t3); t4 ^= u; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; t6 ^= t5; W[i + 1][2] = t6; t7 ^= t6; W[i + 1][3] = t7; } u = subWord(shift(t7, 8)) ^ rcon; t0 ^= u; W[14][0] = t0; t1 ^= t0; W[14][1] = t1; t2 ^= t1; W[14][2] = t2; t3 ^= t2; W[14][3] = t3; break; } default: { throw new IllegalStateException("Should never get here"); } } if (!forEncryption) { for (int j = 1; j < ROUNDS; j++) { for (int i = 0; i < 4; i++) { W[j][i] = inv_mcol(W[j][i]); } } } return W; } private int ROUNDS; private int[][] WorkingKey = null; private int C0, C1, C2, C3; private boolean forEncryption; private static final int BLOCK_SIZE = 16; /** * default constructor - 128 bit block size. */ public AESEngine() { } /** * initialise an AES cipher. * * @param forEncryption whether or not we are for encryption. * @param params the parameters required to set up the cipher. * @exception IllegalArgumentException if the params argument is * inappropriate. */ public void init( boolean forEncryption, CipherParameters params) { if (params instanceof KeyParameter) { WorkingKey = generateWorkingKey(((KeyParameter)params).getKey(), forEncryption); this.forEncryption = forEncryption; return; } throw new IllegalArgumentException("invalid parameter passed to AES init - " + params.getClass().getName()); } public String getAlgorithmName() { return "AES"; } public int getBlockSize() { return BLOCK_SIZE; } public int processBlock( byte[] in, int inOff, byte[] out, int outOff) { if (WorkingKey == null) { throw new IllegalStateException("AES engine not initialised"); } if ((inOff + (32 / 2)) > in.length) { throw new DataLengthException("input buffer too short"); } if ((outOff + (32 / 2)) > out.length) { throw new OutputLengthException("output buffer too short"); } if (forEncryption) { unpackBlock(in, inOff); encryptBlock(WorkingKey); packBlock(out, outOff); } else { unpackBlock(in, inOff); decryptBlock(WorkingKey); packBlock(out, outOff); } return BLOCK_SIZE; } public void reset() { } private void unpackBlock( byte[] bytes, int off) { int index = off; C0 = (bytes[index++] & 0xff); C0 |= (bytes[index++] & 0xff) << 8; C0 |= (bytes[index++] & 0xff) << 16; C0 |= bytes[index++] << 24; C1 = (bytes[index++] & 0xff); C1 |= (bytes[index++] & 0xff) << 8; C1 |= (bytes[index++] & 0xff) << 16; C1 |= bytes[index++] << 24; C2 = (bytes[index++] & 0xff); C2 |= (bytes[index++] & 0xff) << 8; C2 |= (bytes[index++] & 0xff) << 16; C2 |= bytes[index++] << 24; C3 = (bytes[index++] & 0xff); C3 |= (bytes[index++] & 0xff) << 8; C3 |= (bytes[index++] & 0xff) << 16; C3 |= bytes[index++] << 24; } private void packBlock( byte[] bytes, int off) { int index = off; bytes[index++] = (byte)C0; bytes[index++] = (byte)(C0 >> 8); bytes[index++] = (byte)(C0 >> 16); bytes[index++] = (byte)(C0 >> 24); bytes[index++] = (byte)C1; bytes[index++] = (byte)(C1 >> 8); bytes[index++] = (byte)(C1 >> 16); bytes[index++] = (byte)(C1 >> 24); bytes[index++] = (byte)C2; bytes[index++] = (byte)(C2 >> 8); bytes[index++] = (byte)(C2 >> 16); bytes[index++] = (byte)(C2 >> 24); bytes[index++] = (byte)C3; bytes[index++] = (byte)(C3 >> 8); bytes[index++] = (byte)(C3 >> 16); bytes[index++] = (byte)(C3 >> 24); } private void encryptBlock(int[][] KW) { int t0 = this.C0 ^ KW[0][0]; int t1 = this.C1 ^ KW[0][1]; int t2 = this.C2 ^ KW[0][2]; int r = 1, r0, r1, r2, r3 = this.C3 ^ KW[0][3]; while (r < ROUNDS - 1) { r0 = T0[t0&255] ^ shift(T0[(t1>>8)&255], 24) ^ shift(T0[(t2>>16)&255], 16) ^ shift(T0[(r3>>24)&255], 8) ^ KW[r][0]; r1 = T0[t1&255] ^ shift(T0[(t2>>8)&255], 24) ^ shift(T0[(r3>>16)&255], 16) ^ shift(T0[(t0>>24)&255], 8) ^ KW[r][1]; r2 = T0[t2&255] ^ shift(T0[(r3>>8)&255], 24) ^ shift(T0[(t0>>16)&255], 16) ^ shift(T0[(t1>>24)&255], 8) ^ KW[r][2]; r3 = T0[r3&255] ^ shift(T0[(t0>>8)&255], 24) ^ shift(T0[(t1>>16)&255], 16) ^ shift(T0[(t2>>24)&255], 8) ^ KW[r++][3]; t0 = T0[r0&255] ^ shift(T0[(r1>>8)&255], 24) ^ shift(T0[(r2>>16)&255], 16) ^ shift(T0[(r3>>24)&255], 8) ^ KW[r][0]; t1 = T0[r1&255] ^ shift(T0[(r2>>8)&255], 24) ^ shift(T0[(r3>>16)&255], 16) ^ shift(T0[(r0>>24)&255], 8) ^ KW[r][1]; t2 = T0[r2&255] ^ shift(T0[(r3>>8)&255], 24) ^ shift(T0[(r0>>16)&255], 16) ^ shift(T0[(r1>>24)&255], 8) ^ KW[r][2]; r3 = T0[r3&255] ^ shift(T0[(r0>>8)&255], 24) ^ shift(T0[(r1>>16)&255], 16) ^ shift(T0[(r2>>24)&255], 8) ^ KW[r++][3]; } r0 = T0[t0&255] ^ shift(T0[(t1>>8)&255], 24) ^ shift(T0[(t2>>16)&255], 16) ^ shift(T0[(r3>>24)&255], 8) ^ KW[r][0]; r1 = T0[t1&255] ^ shift(T0[(t2>>8)&255], 24) ^ shift(T0[(r3>>16)&255], 16) ^ shift(T0[(t0>>24)&255], 8) ^ KW[r][1]; r2 = T0[t2&255] ^ shift(T0[(r3>>8)&255], 24) ^ shift(T0[(t0>>16)&255], 16) ^ shift(T0[(t1>>24)&255], 8) ^ KW[r][2]; r3 = T0[r3&255] ^ shift(T0[(t0>>8)&255], 24) ^ shift(T0[(t1>>16)&255], 16) ^ shift(T0[(t2>>24)&255], 8) ^ KW[r++][3]; // the final round's table is a simple function of S so we don't use a whole other four tables for it this.C0 = (S[r0&255]&255) ^ ((S[(r1>>8)&255]&255)<<8) ^ ((S[(r2>>16)&255]&255)<<16) ^ (S[(r3>>24)&255]<<24) ^ KW[r][0]; this.C1 = (S[r1&255]&255) ^ ((S[(r2>>8)&255]&255)<<8) ^ ((S[(r3>>16)&255]&255)<<16) ^ (S[(r0>>24)&255]<<24) ^ KW[r][1]; this.C2 = (S[r2&255]&255) ^ ((S[(r3>>8)&255]&255)<<8) ^ ((S[(r0>>16)&255]&255)<<16) ^ (S[(r1>>24)&255]<<24) ^ KW[r][2]; this.C3 = (S[r3&255]&255) ^ ((S[(r0>>8)&255]&255)<<8) ^ ((S[(r1>>16)&255]&255)<<16) ^ (S[(r2>>24)&255]<<24) ^ KW[r][3]; } private void decryptBlock(int[][] KW) { int t0 = this.C0 ^ KW[ROUNDS][0]; int t1 = this.C1 ^ KW[ROUNDS][1]; int t2 = this.C2 ^ KW[ROUNDS][2]; int r = ROUNDS - 1, r0, r1, r2, r3 = this.C3 ^ KW[ROUNDS][3]; while (r > 1) { r0 = Tinv0[t0&255] ^ shift(Tinv0[(r3>>8)&255], 24) ^ shift(Tinv0[(t2>>16)&255], 16) ^ shift(Tinv0[(t1>>24)&255], 8) ^ KW[r][0]; r1 = Tinv0[t1&255] ^ shift(Tinv0[(t0>>8)&255], 24) ^ shift(Tinv0[(r3>>16)&255], 16) ^ shift(Tinv0[(t2>>24)&255], 8) ^ KW[r][1]; r2 = Tinv0[t2&255] ^ shift(Tinv0[(t1>>8)&255], 24) ^ shift(Tinv0[(t0>>16)&255], 16) ^ shift(Tinv0[(r3>>24)&255], 8) ^ KW[r][2]; r3 = Tinv0[r3&255] ^ shift(Tinv0[(t2>>8)&255], 24) ^ shift(Tinv0[(t1>>16)&255], 16) ^ shift(Tinv0[(t0>>24)&255], 8) ^ KW[r--][3]; t0 = Tinv0[r0&255] ^ shift(Tinv0[(r3>>8)&255], 24) ^ shift(Tinv0[(r2>>16)&255], 16) ^ shift(Tinv0[(r1>>24)&255], 8) ^ KW[r][0]; t1 = Tinv0[r1&255] ^ shift(Tinv0[(r0>>8)&255], 24) ^ shift(Tinv0[(r3>>16)&255], 16) ^ shift(Tinv0[(r2>>24)&255], 8) ^ KW[r][1]; t2 = Tinv0[r2&255] ^ shift(Tinv0[(r1>>8)&255], 24) ^ shift(Tinv0[(r0>>16)&255], 16) ^ shift(Tinv0[(r3>>24)&255], 8) ^ KW[r][2]; r3 = Tinv0[r3&255] ^ shift(Tinv0[(r2>>8)&255], 24) ^ shift(Tinv0[(r1>>16)&255], 16) ^ shift(Tinv0[(r0>>24)&255], 8) ^ KW[r--][3]; } r0 = Tinv0[t0&255] ^ shift(Tinv0[(r3>>8)&255], 24) ^ shift(Tinv0[(t2>>16)&255], 16) ^ shift(Tinv0[(t1>>24)&255], 8) ^ KW[r][0]; r1 = Tinv0[t1&255] ^ shift(Tinv0[(t0>>8)&255], 24) ^ shift(Tinv0[(r3>>16)&255], 16) ^ shift(Tinv0[(t2>>24)&255], 8) ^ KW[r][1]; r2 = Tinv0[t2&255] ^ shift(Tinv0[(t1>>8)&255], 24) ^ shift(Tinv0[(t0>>16)&255], 16) ^ shift(Tinv0[(r3>>24)&255], 8) ^ KW[r][2]; r3 = Tinv0[r3&255] ^ shift(Tinv0[(t2>>8)&255], 24) ^ shift(Tinv0[(t1>>16)&255], 16) ^ shift(Tinv0[(t0>>24)&255], 8) ^ KW[r][3]; // the final round's table is a simple function of Si so we don't use a whole other four tables for it this.C0 = (Si[r0&255]&255) ^ ((Si[(r3>>8)&255]&255)<<8) ^ ((Si[(r2>>16)&255]&255)<<16) ^ (Si[(r1>>24)&255]<<24) ^ KW[0][0]; this.C1 = (Si[r1&255]&255) ^ ((Si[(r0>>8)&255]&255)<<8) ^ ((Si[(r3>>16)&255]&255)<<16) ^ (Si[(r2>>24)&255]<<24) ^ KW[0][1]; this.C2 = (Si[r2&255]&255) ^ ((Si[(r1>>8)&255]&255)<<8) ^ ((Si[(r0>>16)&255]&255)<<16) ^ (Si[(r3>>24)&255]<<24) ^ KW[0][2]; this.C3 = (Si[r3&255]&255) ^ ((Si[(r2>>8)&255]&255)<<8) ^ ((Si[(r1>>16)&255]&255)<<16) ^ (Si[(r0>>24)&255]<<24) ^ KW[0][3]; } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4755_0
crossvul-java_data_good_4756_1
package org.bouncycastle.jcajce.provider.drbg; import java.security.SecureRandom; import java.security.SecureRandomSpi; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.prng.SP800SecureRandomBuilder; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; import org.bouncycastle.util.Strings; public class DRBG { private static final String PREFIX = DRBG.class.getName(); private static SecureRandom secureRandom = new SecureRandom(); public static class Default extends SecureRandomSpi { private SecureRandom random = new SP800SecureRandomBuilder(secureRandom, true) .setPersonalizationString(generateDefaultPersonalizationString(secureRandom)) .buildHash(new SHA512Digest(), secureRandom.generateSeed(32), true); protected void engineSetSeed(byte[] bytes) { random.setSeed(bytes); } protected void engineNextBytes(byte[] bytes) { random.nextBytes(bytes); } protected byte[] engineGenerateSeed(int numBytes) { return secureRandom.generateSeed(numBytes); } } public static class NonceAndIV extends SecureRandomSpi { private SecureRandom random = new SP800SecureRandomBuilder(secureRandom, true) .setPersonalizationString(generateNonceIVPersonalizationString(secureRandom)) .buildHash(new SHA512Digest(), secureRandom.generateSeed(32), false); protected void engineSetSeed(byte[] bytes) { random.setSeed(bytes); } protected void engineNextBytes(byte[] bytes) { random.nextBytes(bytes); } protected byte[] engineGenerateSeed(int numBytes) { return secureRandom.generateSeed(numBytes); } } public static class Mappings extends AsymmetricAlgorithmProvider { public Mappings() { } public void configure(ConfigurableProvider provider) { provider.addAlgorithm("SecureRandom.DEFAULT", PREFIX + "$Default"); provider.addAlgorithm("SecureRandom.NONCEANDIV", PREFIX + "$NonceAndIV"); } } private static byte[] generateDefaultPersonalizationString(SecureRandom random) { return Arrays.concatenate(Strings.toByteArray("Default"), random.generateSeed(16), Pack.longToBigEndian(Thread.currentThread().getId()), Pack.longToBigEndian(System.currentTimeMillis())); } private static byte[] generateNonceIVPersonalizationString(SecureRandom random) { return Arrays.concatenate(Strings.toByteArray("Nonce"), random.generateSeed(16), Pack.longToLittleEndian(Thread.currentThread().getId()), Pack.longToLittleEndian(System.currentTimeMillis())); } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4756_1
crossvul-java_data_bad_4755_4
package org.bouncycastle.jcajce.provider.asymmetric.ec; import java.io.ByteArrayOutputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.CipherSpi; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyEncoder; import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.engines.DESedeEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.params.ECKeyGenerationParameters; import org.bouncycastle.crypto.params.ECKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.crypto.parsers.ECIESPublicKeyParser; import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil; import org.bouncycastle.jcajce.provider.asymmetric.util.IESUtil; import org.bouncycastle.jcajce.provider.util.BadBlockException; import org.bouncycastle.jcajce.util.BCJcaJceHelper; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.interfaces.ECKey; import org.bouncycastle.jce.interfaces.IESKey; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.Strings; public class IESCipher extends CipherSpi { private final JcaJceHelper helper = new BCJcaJceHelper(); private int ivLength; private IESEngine engine; private int state = -1; private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private AlgorithmParameters engineParam = null; private IESParameterSpec engineSpec = null; private AsymmetricKeyParameter key; private SecureRandom random; private boolean dhaesMode = false; private AsymmetricKeyParameter otherKeyParameter = null; public IESCipher(IESEngine engine) { this.engine = engine; this.ivLength = 0; } public IESCipher(IESEngine engine, int ivLength) { this.engine = engine; this.ivLength = ivLength; } public int engineGetBlockSize() { if (engine.getCipher() != null) { return engine.getCipher().getBlockSize(); } else { return 0; } } public int engineGetKeySize(Key key) { if (key instanceof ECKey) { return ((ECKey)key).getParameters().getCurve().getFieldSize(); } else { throw new IllegalArgumentException("not an EC key"); } } public byte[] engineGetIV() { if (engineSpec != null) { return engineSpec.getNonce(); } return null; } public AlgorithmParameters engineGetParameters() { if (engineParam == null && engineSpec != null) { try { engineParam = helper.createAlgorithmParameters("IES"); engineParam.init(engineSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } return engineParam; } public void engineSetMode(String mode) throws NoSuchAlgorithmException { String modeName = Strings.toUpperCase(mode); if (modeName.equals("NONE")) { dhaesMode = false; } else if (modeName.equals("DHAES")) { dhaesMode = true; } else { throw new IllegalArgumentException("can't support mode " + mode); } } public int engineGetOutputSize(int inputLen) { int len1, len2, len3; if (key == null) { throw new IllegalStateException("cipher not initialised"); } len1 = engine.getMac().getMacSize(); if (otherKeyParameter == null) { len2 = 2 * (((ECKeyParameters)key).getParameters().getCurve().getFieldSize() + 7) / 8; } else { len2 = 0; } if (engine.getCipher() == null) { len3 = inputLen; } else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen); } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2); } else { throw new IllegalStateException("cipher not initialised"); } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { return buffer.size() + len1 + 1 + len2 + len3; } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { return buffer.size() - len1 - len2 + len3; } else { throw new IllegalStateException("cipher not initialised"); } } public void engineSetPadding(String padding) throws NoSuchPaddingException { String paddingName = Strings.toUpperCase(padding); // TDOD: make this meaningful... if (paddingName.equals("NOPADDING")) { } else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING")) { } else { throw new NoSuchPaddingException("padding not available with IESCipher"); } } // Initialisation methods public void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { try { paramSpec = params.getParameterSpec(IESParameterSpec.class); } catch (Exception e) { throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString()); } } engineParam = params; engineInit(opmode, key, paramSpec, random); } public void engineInit( int opmode, Key key, AlgorithmParameterSpec engineSpec, SecureRandom random) throws InvalidAlgorithmParameterException, InvalidKeyException { otherKeyParameter = null; // Use default parameters (including cipher key size) if none are specified if (engineSpec == null) { byte[] nonce = null; if (ivLength != 0 && opmode == Cipher.ENCRYPT_MODE) { nonce = new byte[ivLength]; random.nextBytes(nonce); } this.engineSpec = IESUtil.guessParameterSpec(engine.getCipher(), nonce); } else if (engineSpec instanceof IESParameterSpec) { this.engineSpec = (IESParameterSpec)engineSpec; } else { throw new InvalidAlgorithmParameterException("must be passed IES parameters"); } byte[] nonce = this.engineSpec.getNonce(); if (ivLength != 0 && (nonce == null || nonce.length != ivLength)) { throw new InvalidAlgorithmParameterException("NONCE in IES Parameters needs to be " + ivLength + " bytes long"); } // Parse the recipient's key if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE) { if (key instanceof PublicKey) { this.key = ECUtils.generatePublicKeyParameter((PublicKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.key = ECUtils.generatePublicKeyParameter(ieKey.getPublic()); this.otherKeyParameter = ECUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's public EC key for encryption"); } } else if (opmode == Cipher.DECRYPT_MODE || opmode == Cipher.UNWRAP_MODE) { if (key instanceof PrivateKey) { this.key = ECUtil.generatePrivateKeyParameter((PrivateKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.otherKeyParameter = ECUtils.generatePublicKeyParameter(ieKey.getPublic()); this.key = ECUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's private EC key for decryption"); } } else { throw new InvalidKeyException("must be passed EC key"); } this.random = random; this.state = opmode; buffer.reset(); } public void engineInit( int opmode, Key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, (AlgorithmParameterSpec)null, random); } catch (InvalidAlgorithmParameterException e) { throw new IllegalArgumentException("cannot handle supplied parameter spec: " + e.getMessage()); } } // Update methods - buffer the input public byte[] engineUpdate( byte[] input, int inputOffset, int inputLen) { buffer.write(input, inputOffset, inputLen); return null; } public int engineUpdate( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { buffer.write(input, inputOffset, inputLen); return 0; } // Finalisation methods public byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (inputLen != 0) { buffer.write(input, inputOffset, inputLen); } final byte[] in = buffer.toByteArray(); buffer.reset(); // Convert parameters for use in IESEngine CipherParameters params = new IESWithCipherParameters(engineSpec.getDerivationV(), engineSpec.getEncodingV(), engineSpec.getMacKeySize(), engineSpec.getCipherKeySize()); if (engineSpec.getNonce() != null) { params = new ParametersWithIV(params, engineSpec.getNonce()); } final ECDomainParameters ecParams = ((ECKeyParameters)key).getParameters(); final byte[] V; if (otherKeyParameter != null) { try { if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { engine.init(true, otherKeyParameter, key, params); } else { engine.init(false, key, otherKeyParameter, params); } return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadBlockException("unable to process block", e); } } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { // Generate the ephemeral key pair ECKeyPairGenerator gen = new ECKeyPairGenerator(); gen.init(new ECKeyGenerationParameters(ecParams, random)); final boolean usePointCompression = engineSpec.getPointCompression(); EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(gen, new KeyEncoder() { public byte[] getEncoded(AsymmetricKeyParameter keyParameter) { return ((ECPublicKeyParameters)keyParameter).getQ().getEncoded(usePointCompression); } }); // Encrypt the buffer try { engine.init(key, params, kGen); return engine.processBlock(in, 0, in.length); } catch (final Exception e) { throw new BadBlockException("unable to process block", e); } } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { // Decrypt the buffer try { engine.init(key, params, new ECIESPublicKeyParser(ecParams)); return engine.processBlock(in, 0, in.length); } catch (InvalidCipherTextException e) { throw new BadBlockException("unable to process block", e); } } else { throw new IllegalStateException("cipher not initialised"); } } public int engineDoFinal( byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { byte[] buf = engineDoFinal(input, inputOffset, inputLength); System.arraycopy(buf, 0, output, outputOffset, buf.length); return buf.length; } /** * Classes that inherit from us */ static public class ECIES extends IESCipher { public ECIES() { super(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()))); } } static public class ECIESwithCipher extends IESCipher { public ECIESwithCipher(BlockCipher cipher, int ivLength) { super(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(cipher)), ivLength); } } static public class ECIESwithDESedeCBC extends ECIESwithCipher { public ECIESwithDESedeCBC() { super(new CBCBlockCipher(new DESedeEngine()), 8); } } static public class ECIESwithAESCBC extends ECIESwithCipher { public ECIESwithAESCBC() { super(new CBCBlockCipher(new AESFastEngine()), 16); } } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4755_4
crossvul-java_data_bad_4755_3
package org.bouncycastle.jcajce.provider.asymmetric.dh; import java.io.IOException; import java.security.InvalidKeyException; import java.security.Key; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHPrivateKeySpec; import javax.crypto.spec.DHPublicKeySpec; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.jcajce.provider.asymmetric.util.BaseKeyFactorySpi; public class KeyFactorySpi extends BaseKeyFactorySpi { public KeyFactorySpi() { } protected KeySpec engineGetKeySpec( Key key, Class spec) throws InvalidKeySpecException { if (spec.isAssignableFrom(DHPrivateKeySpec.class) && key instanceof DHPrivateKey) { DHPrivateKey k = (DHPrivateKey)key; return new DHPrivateKeySpec(k.getX(), k.getParams().getP(), k.getParams().getG()); } else if (spec.isAssignableFrom(DHPublicKeySpec.class) && key instanceof DHPublicKey) { DHPublicKey k = (DHPublicKey)key; return new DHPublicKeySpec(k.getY(), k.getParams().getP(), k.getParams().getG()); } return super.engineGetKeySpec(key, spec); } protected Key engineTranslateKey( Key key) throws InvalidKeyException { if (key instanceof DHPublicKey) { return new BCDHPublicKey((DHPublicKey)key); } else if (key instanceof DHPrivateKey) { return new BCDHPrivateKey((DHPrivateKey)key); } throw new InvalidKeyException("key type unknown"); } protected PrivateKey engineGeneratePrivate( KeySpec keySpec) throws InvalidKeySpecException { if (keySpec instanceof DHPrivateKeySpec) { return new BCDHPrivateKey((DHPrivateKeySpec)keySpec); } return super.engineGeneratePrivate(keySpec); } protected PublicKey engineGeneratePublic( KeySpec keySpec) throws InvalidKeySpecException { if (keySpec instanceof DHPublicKeySpec) { return new BCDHPublicKey((DHPublicKeySpec)keySpec); } return super.engineGeneratePublic(keySpec); } public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) throws IOException { ASN1ObjectIdentifier algOid = keyInfo.getPrivateKeyAlgorithm().getAlgorithm(); if (algOid.equals(PKCSObjectIdentifiers.dhKeyAgreement)) { return new BCDHPrivateKey(keyInfo); } else if (algOid.equals(X9ObjectIdentifiers.dhpublicnumber)) { return new BCDHPrivateKey(keyInfo); } else { throw new IOException("algorithm identifier " + algOid + " in key not recognised"); } } public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) throws IOException { ASN1ObjectIdentifier algOid = keyInfo.getAlgorithm().getAlgorithm(); if (algOid.equals(PKCSObjectIdentifiers.dhKeyAgreement)) { return new BCDHPublicKey(keyInfo); } else if (algOid.equals(X9ObjectIdentifiers.dhpublicnumber)) { return new BCDHPublicKey(keyInfo); } else { throw new IOException("algorithm identifier " + algOid + " in key not recognised"); } } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4755_3
crossvul-java_data_good_4756_0
package org.bouncycastle.crypto.engines; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.util.Pack; /** * an implementation of the AES (Rijndael), from FIPS-197. * <p> * For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>. * * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at * <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a> * * There are three levels of tradeoff of speed vs memory * Because java has no preprocessor, they are written as three separate classes from which to choose * * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption * and 4 for decryption. * * The middle performance version uses only one 256 word table for each, for a total of 2Kbytes, * adding 12 rotate operations per round to compute the values contained in the other tables from * the contents of the first * * The slowest version uses no static tables at all and computes the values in each round * </p> * <p> * This file contains the fast version with 8Kbytes of static tables for round precomputation. * </p> * @deprecated unfortunately this class is has a few side channel issues. In an environment where encryption/decryption may be closely observed it should not be used. */ public class AESFastEngine implements BlockCipher { // The S box private static final byte[] S = { (byte)99, (byte)124, (byte)119, (byte)123, (byte)242, (byte)107, (byte)111, (byte)197, (byte)48, (byte)1, (byte)103, (byte)43, (byte)254, (byte)215, (byte)171, (byte)118, (byte)202, (byte)130, (byte)201, (byte)125, (byte)250, (byte)89, (byte)71, (byte)240, (byte)173, (byte)212, (byte)162, (byte)175, (byte)156, (byte)164, (byte)114, (byte)192, (byte)183, (byte)253, (byte)147, (byte)38, (byte)54, (byte)63, (byte)247, (byte)204, (byte)52, (byte)165, (byte)229, (byte)241, (byte)113, (byte)216, (byte)49, (byte)21, (byte)4, (byte)199, (byte)35, (byte)195, (byte)24, (byte)150, (byte)5, (byte)154, (byte)7, (byte)18, (byte)128, (byte)226, (byte)235, (byte)39, (byte)178, (byte)117, (byte)9, (byte)131, (byte)44, (byte)26, (byte)27, (byte)110, (byte)90, (byte)160, (byte)82, (byte)59, (byte)214, (byte)179, (byte)41, (byte)227, (byte)47, (byte)132, (byte)83, (byte)209, (byte)0, (byte)237, (byte)32, (byte)252, (byte)177, (byte)91, (byte)106, (byte)203, (byte)190, (byte)57, (byte)74, (byte)76, (byte)88, (byte)207, (byte)208, (byte)239, (byte)170, (byte)251, (byte)67, (byte)77, (byte)51, (byte)133, (byte)69, (byte)249, (byte)2, (byte)127, (byte)80, (byte)60, (byte)159, (byte)168, (byte)81, (byte)163, (byte)64, (byte)143, (byte)146, (byte)157, (byte)56, (byte)245, (byte)188, (byte)182, (byte)218, (byte)33, (byte)16, (byte)255, (byte)243, (byte)210, (byte)205, (byte)12, (byte)19, (byte)236, (byte)95, (byte)151, (byte)68, (byte)23, (byte)196, (byte)167, (byte)126, (byte)61, (byte)100, (byte)93, (byte)25, (byte)115, (byte)96, (byte)129, (byte)79, (byte)220, (byte)34, (byte)42, (byte)144, (byte)136, (byte)70, (byte)238, (byte)184, (byte)20, (byte)222, (byte)94, (byte)11, (byte)219, (byte)224, (byte)50, (byte)58, (byte)10, (byte)73, (byte)6, (byte)36, (byte)92, (byte)194, (byte)211, (byte)172, (byte)98, (byte)145, (byte)149, (byte)228, (byte)121, (byte)231, (byte)200, (byte)55, (byte)109, (byte)141, (byte)213, (byte)78, (byte)169, (byte)108, (byte)86, (byte)244, (byte)234, (byte)101, (byte)122, (byte)174, (byte)8, (byte)186, (byte)120, (byte)37, (byte)46, (byte)28, (byte)166, (byte)180, (byte)198, (byte)232, (byte)221, (byte)116, (byte)31, (byte)75, (byte)189, (byte)139, (byte)138, (byte)112, (byte)62, (byte)181, (byte)102, (byte)72, (byte)3, (byte)246, (byte)14, (byte)97, (byte)53, (byte)87, (byte)185, (byte)134, (byte)193, (byte)29, (byte)158, (byte)225, (byte)248, (byte)152, (byte)17, (byte)105, (byte)217, (byte)142, (byte)148, (byte)155, (byte)30, (byte)135, (byte)233, (byte)206, (byte)85, (byte)40, (byte)223, (byte)140, (byte)161, (byte)137, (byte)13, (byte)191, (byte)230, (byte)66, (byte)104, (byte)65, (byte)153, (byte)45, (byte)15, (byte)176, (byte)84, (byte)187, (byte)22, }; // The inverse S-box private static final byte[] Si = { (byte)82, (byte)9, (byte)106, (byte)213, (byte)48, (byte)54, (byte)165, (byte)56, (byte)191, (byte)64, (byte)163, (byte)158, (byte)129, (byte)243, (byte)215, (byte)251, (byte)124, (byte)227, (byte)57, (byte)130, (byte)155, (byte)47, (byte)255, (byte)135, (byte)52, (byte)142, (byte)67, (byte)68, (byte)196, (byte)222, (byte)233, (byte)203, (byte)84, (byte)123, (byte)148, (byte)50, (byte)166, (byte)194, (byte)35, (byte)61, (byte)238, (byte)76, (byte)149, (byte)11, (byte)66, (byte)250, (byte)195, (byte)78, (byte)8, (byte)46, (byte)161, (byte)102, (byte)40, (byte)217, (byte)36, (byte)178, (byte)118, (byte)91, (byte)162, (byte)73, (byte)109, (byte)139, (byte)209, (byte)37, (byte)114, (byte)248, (byte)246, (byte)100, (byte)134, (byte)104, (byte)152, (byte)22, (byte)212, (byte)164, (byte)92, (byte)204, (byte)93, (byte)101, (byte)182, (byte)146, (byte)108, (byte)112, (byte)72, (byte)80, (byte)253, (byte)237, (byte)185, (byte)218, (byte)94, (byte)21, (byte)70, (byte)87, (byte)167, (byte)141, (byte)157, (byte)132, (byte)144, (byte)216, (byte)171, (byte)0, (byte)140, (byte)188, (byte)211, (byte)10, (byte)247, (byte)228, (byte)88, (byte)5, (byte)184, (byte)179, (byte)69, (byte)6, (byte)208, (byte)44, (byte)30, (byte)143, (byte)202, (byte)63, (byte)15, (byte)2, (byte)193, (byte)175, (byte)189, (byte)3, (byte)1, (byte)19, (byte)138, (byte)107, (byte)58, (byte)145, (byte)17, (byte)65, (byte)79, (byte)103, (byte)220, (byte)234, (byte)151, (byte)242, (byte)207, (byte)206, (byte)240, (byte)180, (byte)230, (byte)115, (byte)150, (byte)172, (byte)116, (byte)34, (byte)231, (byte)173, (byte)53, (byte)133, (byte)226, (byte)249, (byte)55, (byte)232, (byte)28, (byte)117, (byte)223, (byte)110, (byte)71, (byte)241, (byte)26, (byte)113, (byte)29, (byte)41, (byte)197, (byte)137, (byte)111, (byte)183, (byte)98, (byte)14, (byte)170, (byte)24, (byte)190, (byte)27, (byte)252, (byte)86, (byte)62, (byte)75, (byte)198, (byte)210, (byte)121, (byte)32, (byte)154, (byte)219, (byte)192, (byte)254, (byte)120, (byte)205, (byte)90, (byte)244, (byte)31, (byte)221, (byte)168, (byte)51, (byte)136, (byte)7, (byte)199, (byte)49, (byte)177, (byte)18, (byte)16, (byte)89, (byte)39, (byte)128, (byte)236, (byte)95, (byte)96, (byte)81, (byte)127, (byte)169, (byte)25, (byte)181, (byte)74, (byte)13, (byte)45, (byte)229, (byte)122, (byte)159, (byte)147, (byte)201, (byte)156, (byte)239, (byte)160, (byte)224, (byte)59, (byte)77, (byte)174, (byte)42, (byte)245, (byte)176, (byte)200, (byte)235, (byte)187, (byte)60, (byte)131, (byte)83, (byte)153, (byte)97, (byte)23, (byte)43, (byte)4, (byte)126, (byte)186, (byte)119, (byte)214, (byte)38, (byte)225, (byte)105, (byte)20, (byte)99, (byte)85, (byte)33, (byte)12, (byte)125, }; // vector used in calculating key schedule (powers of x in GF(256)) private static final int[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; // precomputation tables of calculations for rounds private static final int[] T = { // T0 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c, // T1 0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f, 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db, 0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, 0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, 0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a, // T2 0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05, 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49, 0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, 0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, 0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16, // T3 0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505, 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, 0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616}; private static final int[] Tinv = { // Tinv0 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0, // Tinv1 0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, 0x459d1ff1, 0x58faacab, 0x03e34b93, 0xfa302055, 0x6d76adf6, 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0x0eea4598, 0xc0fe5de1, 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b, 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19, 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x024b72e2, 0x8f1fe357, 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x0837d3a5, 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b, 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51, 0x8a213ef9, 0x06dd963d, 0x053eddae, 0xbde64d46, 0x8d5491b5, 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, 0xeec879db, 0x0a7ca147, 0x0f427ce9, 0x1e84f8c9, 0x00000000, 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2, 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0x0d090e0b, 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x0775af4c, 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d, 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef, 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0x0bd49836, 0x81f5a6cf, 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x099fead4, 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d, 0x4daacc54, 0x0496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c, 0x0ca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886, 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x01a83971, 0xb30c08de, 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, 0x57b8d042, // Tinv2 0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, 0xcc889176, 0x02f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e, 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, 0x6bbb84ae, 0x81fe1ca0, 0x08f9942b, 0x48705868, 0x458f19fd, 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, 0x2830f287, 0xbf23b2a5, 0x0302ba6a, 0x16ed5c82, 0xcf8a2b1c, 0x79a792b4, 0x07f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x0506d5be, 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110, 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, 0xc471055d, 0x06046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x00000000, 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0x0efdfbff, 0x850f5638, 0xae3d1ed5, 0x2d362739, 0x0f0a64d9, 0x5c6821a6, 0x5b9bd154, 0x36243a2e, 0x0a0cb167, 0x57930fe7, 0xeeb4d296, 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x090e0b0d, 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07, 0x99eebbdd, 0x7fa3fd60, 0x01f79f26, 0x725cbcf5, 0x6644c53b, 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24, 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90, 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409, 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x04f14a98, 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0, 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0x0bfb2e41, 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61, 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db, 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, 0xe2bc0c25, 0x3c288b49, 0x0dff4195, 0xa8397101, 0x0c08deb3, 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, 0xb8d04257, // Tinv3 0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x03e75f8f, 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58, 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45, 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, 0x30f28728, 0x23b2a5bf, 0x02ba6a03, 0xed5c8216, 0x8a2b1ccf, 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x06d5be05, 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x0532e18a, 0xa475ebf6, 0x0b39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e, 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, 0x71055dc4, 0x046fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x07888b89, 0xe7385b19, 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x00000000, 0x09838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, 0x0f563885, 0x3d1ed5ae, 0x3627392d, 0x0a64d90f, 0x6821a65c, 0x9bd1545b, 0x243a2e36, 0x0cb1670a, 0x930fe757, 0xb4d296ee, 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0x0e0b0d09, 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775, 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a, 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, 0x0dec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033, 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f, 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef, 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, 0x467f5165, 0x9d04ea5e, 0x015d358c, 0xfa737487, 0xfb2e410b, 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7, 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44, 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x08deb30c, 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, 0xd04257b8}; private static int shift(int r, int shift) { return (r >>> shift) | (r << -shift); } /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ private static final int m1 = 0x80808080; private static final int m2 = 0x7f7f7f7f; private static final int m3 = 0x0000001b; private static final int m4 = 0xC0C0C0C0; private static final int m5 = 0x3f3f3f3f; private static int FFmulX(int x) { return (((x & m2) << 1) ^ (((x & m1) >>> 7) * m3)); } private static int FFmulX2(int x) { int t0 = (x & m5) << 2; int t1 = (x & m4); t1 ^= (t1 >>> 1); return t0 ^ (t1 >>> 2) ^ (t1 >>> 5); } /* The following defines provide alternative definitions of FFmulX that might give improved performance if a fast 32-bit multiply is not available. private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = 0x1b1b1b1b; private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } */ private static int inv_mcol(int x) { int t0, t1; t0 = x; t1 = t0 ^ shift(t0, 8); t0 ^= FFmulX(t1); t1 ^= FFmulX2(t0); t0 ^= t1 ^ shift(t1, 16); return t0; } private static int subWord(int x) { int i0 = x, i1 = x >>> 8, i2 = x >>> 16, i3 = x >>> 24; i0 = S[i0 & 255] & 255; i1 = S[i1 & 255] & 255; i2 = S[i2 & 255] & 255; i3 = S[i3 & 255] & 255; return i0 | i1 << 8 | i2 << 16 | i3 << 24; } /** * Calculate the necessary round keys * The number of calculations depends on key size and block size * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ private int[][] generateWorkingKey(byte[] key, boolean forEncryption) { int keyLen = key.length; if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) { throw new IllegalArgumentException("Key length not 128/192/256 bits."); } int KC = keyLen >>> 2; ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes int[][] W = new int[ROUNDS+1][4]; // 4 words in a block switch (KC) { case 4: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; for (int i = 1; i <= 10; ++i) { int u = subWord(shift(t3, 8)) ^ rcon[i - 1]; t0 ^= u; W[i][0] = t0; t1 ^= t0; W[i][1] = t1; t2 ^= t1; W[i][2] = t2; t3 ^= t2; W[i][3] = t3; } break; } case 6: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; int t4 = Pack.littleEndianToInt(key, 16); W[1][0] = t4; int t5 = Pack.littleEndianToInt(key, 20); W[1][1] = t5; int rcon = 1; int u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[1][2] = t0; t1 ^= t0; W[1][3] = t1; t2 ^= t1; W[2][0] = t2; t3 ^= t2; W[2][1] = t3; t4 ^= t3; W[2][2] = t4; t5 ^= t4; W[2][3] = t5; for (int i = 3; i < 12; i += 3) { u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i ][0] = t0; t1 ^= t0; W[i ][1] = t1; t2 ^= t1; W[i ][2] = t2; t3 ^= t2; W[i ][3] = t3; t4 ^= t3; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i + 1][2] = t0; t1 ^= t0; W[i + 1][3] = t1; t2 ^= t1; W[i + 2][0] = t2; t3 ^= t2; W[i + 2][1] = t3; t4 ^= t3; W[i + 2][2] = t4; t5 ^= t4; W[i + 2][3] = t5; } u = subWord(shift(t5, 8)) ^ rcon; t0 ^= u; W[12][0] = t0; t1 ^= t0; W[12][1] = t1; t2 ^= t1; W[12][2] = t2; t3 ^= t2; W[12][3] = t3; break; } case 8: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; int t4 = Pack.littleEndianToInt(key, 16); W[1][0] = t4; int t5 = Pack.littleEndianToInt(key, 20); W[1][1] = t5; int t6 = Pack.littleEndianToInt(key, 24); W[1][2] = t6; int t7 = Pack.littleEndianToInt(key, 28); W[1][3] = t7; int u, rcon = 1; for (int i = 2; i < 14; i += 2) { u = subWord(shift(t7, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i ][0] = t0; t1 ^= t0; W[i ][1] = t1; t2 ^= t1; W[i ][2] = t2; t3 ^= t2; W[i ][3] = t3; u = subWord(t3); t4 ^= u; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; t6 ^= t5; W[i + 1][2] = t6; t7 ^= t6; W[i + 1][3] = t7; } u = subWord(shift(t7, 8)) ^ rcon; t0 ^= u; W[14][0] = t0; t1 ^= t0; W[14][1] = t1; t2 ^= t1; W[14][2] = t2; t3 ^= t2; W[14][3] = t3; break; } default: { throw new IllegalStateException("Should never get here"); } } if (!forEncryption) { for (int j = 1; j < ROUNDS; j++) { for (int i = 0; i < 4; i++) { W[j][i] = inv_mcol(W[j][i]); } } } return W; } private int ROUNDS; private int[][] WorkingKey = null; private int C0, C1, C2, C3; private boolean forEncryption; private static final int BLOCK_SIZE = 16; /** * default constructor - 128 bit block size. */ public AESFastEngine() { } /** * initialise an AES cipher. * * @param forEncryption whether or not we are for encryption. * @param params the parameters required to set up the cipher. * @exception IllegalArgumentException if the params argument is * inappropriate. */ public void init( boolean forEncryption, CipherParameters params) { if (params instanceof KeyParameter) { WorkingKey = generateWorkingKey(((KeyParameter)params).getKey(), forEncryption); this.forEncryption = forEncryption; return; } throw new IllegalArgumentException("invalid parameter passed to AES init - " + params.getClass().getName()); } public String getAlgorithmName() { return "AES"; } public int getBlockSize() { return BLOCK_SIZE; } public int processBlock( byte[] in, int inOff, byte[] out, int outOff) { if (WorkingKey == null) { throw new IllegalStateException("AES engine not initialised"); } if ((inOff + (32 / 2)) > in.length) { throw new DataLengthException("input buffer too short"); } if ((outOff + (32 / 2)) > out.length) { throw new OutputLengthException("output buffer too short"); } unpackBlock(in, inOff); if (forEncryption) { encryptBlock(WorkingKey); } else { decryptBlock(WorkingKey); } packBlock(out, outOff); return BLOCK_SIZE; } public void reset() { } private void unpackBlock(byte[] bytes, int off) { this.C0 = Pack.littleEndianToInt(bytes, off); this.C1 = Pack.littleEndianToInt(bytes, off + 4); this.C2 = Pack.littleEndianToInt(bytes, off + 8); this.C3 = Pack.littleEndianToInt(bytes, off + 12); } private void packBlock(byte[] bytes, int off) { Pack.intToLittleEndian(this.C0, bytes, off); Pack.intToLittleEndian(this.C1, bytes, off + 4); Pack.intToLittleEndian(this.C2, bytes, off + 8); Pack.intToLittleEndian(this.C3, bytes, off + 12); } private void encryptBlock(int[][] KW) { int t0 = this.C0 ^ KW[0][0]; int t1 = this.C1 ^ KW[0][1]; int t2 = this.C2 ^ KW[0][2]; /* * Fast engine has precomputed rotr(T0, 8/16/24) tables T1/T2/T3. * * Placing all precomputes in one array requires offsets additions for 8/16/24 rotations but * avoids additional array range checks on 3 more arrays (which on HotSpot are more * expensive than the offset additions). */ int r = 1, r0, r1, r2, r3 = this.C3 ^ KW[0][3]; int i0, i1, i2, i3; while (r < ROUNDS - 1) { i0 = t0; i1 = t1 >>> 8; i2 = t2 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r0 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][0]; i0 = t1; i1 = t2 >>> 8; i2 = r3 >>> 16; i3 = t0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r1 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][1]; i0 = t2; i1 = r3 >>> 8; i2 = t0 >>> 16; i3 = t1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r2 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][2]; i0 = r3; i1 = t0 >>> 8; i2 = t1 >>> 16; i3 = t2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r++][3]; i0 = r0; i1 = r1 >>> 8; i2 = r2 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t0 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][0]; i0 = r1; i1 = r2 >>> 8; i2 = r3 >>> 16; i3 = r0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t1 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][1]; i0 = r2; i1 = r3 >>> 8; i2 = r0 >>> 16; i3 = r1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t2 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][2]; i0 = r3; i1 = r0 >>> 8; i2 = r1 >>> 16; i3 = r2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r++][3]; } i0 = t0; i1 = t1 >>> 8; i2 = t2 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r0 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][0]; i0 = t1; i1 = t2 >>> 8; i2 = r3 >>> 16; i3 = t0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r1 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][1]; i0 = t2; i1 = r3 >>> 8; i2 = t0 >>> 16; i3 = t1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r2 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][2]; i0 = r3; i1 = t0 >>> 8; i2 = t1 >>> 16; i3 = t2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r++][3]; // the final round's table is a simple function of S so we don't use a whole other four tables for it i0 = r0; i1 = r1 >>> 8; i2 = r2 >>> 16; i3 = r3 >>> 24; i0 = S[i0 & 255] & 255; i1 = S[i1 & 255] & 255; i2 = S[i2 & 255] & 255; i3 = S[i3 & 255] & 255; this.C0 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[r][0]; i0 = r1; i1 = r2 >>> 8; i2 = r3 >>> 16; i3 = r0 >>> 24; i0 = S[i0 & 255] & 255; i1 = S[i1 & 255] & 255; i2 = S[i2 & 255] & 255; i3 = S[i3 & 255] & 255; this.C1 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[r][1]; i0 = r2; i1 = r3 >>> 8; i2 = r0 >>> 16; i3 = r1 >>> 24; i0 = S[i0 & 255] & 255; i1 = S[i1 & 255] & 255; i2 = S[i2 & 255] & 255; i3 = S[i3 & 255] & 255; this.C2 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[r][2]; i0 = r3; i1 = r0 >>> 8; i2 = r1 >>> 16; i3 = r2 >>> 24; i0 = S[i0 & 255] & 255; i1 = S[i1 & 255] & 255; i2 = S[i2 & 255] & 255; i3 = S[i3 & 255] & 255; this.C3 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[r][3]; } private void decryptBlock(int[][] KW) { int t0 = this.C0 ^ KW[ROUNDS][0]; int t1 = this.C1 ^ KW[ROUNDS][1]; int t2 = this.C2 ^ KW[ROUNDS][2]; int r = ROUNDS - 1, r0, r1, r2, r3 = this.C3 ^ KW[ROUNDS][3]; int i0, i1, i2, i3; while (r > 1) { i0 = t0; i1 = r3 >>> 8; i2 = t2 >>> 16; i3 = t1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r0 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][0]; i0 = t1; i1 = t0 >>> 8; i2 = r3 >>> 16; i3 = t2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r1 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][1]; i0 = t2; i1 = t1 >>> 8; i2 = t0 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r2 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][2]; i0 = r3; i1 = t2 >>> 8; i2 = t1 >>> 16; i3 = t0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r--][3]; i0 = r0; i1 = r3 >>> 8; i2 = r2 >>> 16; i3 = r1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t0 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][0]; i0 = r1; i1 = r0 >>> 8; i2 = r3 >>> 16; i3 = r2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t1 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][1]; i0 = r2; i1 = r1 >>> 8; i2 = r0 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t2 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][2]; i0 = r3; i1 = r2 >>> 8; i2 = r1 >>> 16; i3 = r0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r--][3]; } i0 = t0; i1 = r3 >>> 8; i2 = t2 >>> 16; i3 = t1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r0 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[1][0]; i0 = t1; i1 = t0 >>> 8; i2 = r3 >>> 16; i3 = t2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r1 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[1][1]; i0 = t2; i1 = t1 >>> 8; i2 = t0 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r2 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[1][2]; i0 = r3; i1 = t2 >>> 8; i2 = t1 >>> 16; i3 = t0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[1][3]; // the final round's table is a simple function of Si so we don't use a whole other four tables for it i0 = r0; i1 = r3 >>> 8; i2 = r2 >>> 16; i3 = r1 >>> 24; i0 = Si[i0 & 255] & 255; i1 = Si[i1 & 255] & 255; i2 = Si[i2 & 255] & 255; i3 = Si[i3 & 255] & 255; this.C0 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[0][0]; i0 = r1; i1 = r0 >>> 8; i2 = r3 >>> 16; i3 = r2 >>> 24; i0 = Si[i0 & 255] & 255; i1 = Si[i1 & 255] & 255; i2 = Si[i2 & 255] & 255; i3 = Si[i3 & 255] & 255; this.C1 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[0][1]; i0 = r2; i1 = r1 >>> 8; i2 = r0 >>> 16; i3 = r3 >>> 24; i0 = Si[i0 & 255] & 255; i1 = Si[i1 & 255] & 255; i2 = Si[i2 & 255] & 255; i3 = Si[i3 & 255] & 255; this.C2 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[0][2]; i0 = r3; i1 = r2 >>> 8; i2 = r1 >>> 16; i3 = r0 >>> 24; i0 = Si[i0 & 255] & 255; i1 = Si[i1 & 255] & 255; i2 = Si[i2 & 255] & 255; i3 = Si[i3 & 255] & 255; this.C3 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[0][3]; } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4756_0
crossvul-java_data_bad_789_0
package org.airsonic.player.controller; import de.triology.recaptchav2java.ReCaptcha; import org.airsonic.player.domain.User; import org.airsonic.player.service.SecurityService; import org.airsonic.player.service.SettingsService; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * Spring MVC Controller that serves the login page. */ @Controller @RequestMapping("/recover") public class RecoverController { private static final Logger LOG = LoggerFactory.getLogger(RecoverController.class); @Autowired private SettingsService settingsService; @Autowired private SecurityService securityService; @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}) public ModelAndView recover(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); String usernameOrEmail = StringUtils.trimToNull(request.getParameter("usernameOrEmail")); if (usernameOrEmail != null) { map.put("usernameOrEmail", usernameOrEmail); User user = getUserByUsernameOrEmail(usernameOrEmail); boolean captchaOk; if (settingsService.isCaptchaEnabled()) { String recaptchaResponse = request.getParameter("g-recaptcha-response"); ReCaptcha captcha = new ReCaptcha(settingsService.getRecaptchaSecretKey()); captchaOk = recaptchaResponse != null && captcha.isValid(recaptchaResponse); } else { captchaOk = true; } if (!captchaOk) { map.put("error", "recover.error.invalidcaptcha"); } else if (user == null) { map.put("error", "recover.error.usernotfound"); } else if (user.getEmail() == null) { map.put("error", "recover.error.noemail"); } else { String password = RandomStringUtils.randomAlphanumeric(8); if (emailPassword(password, user.getUsername(), user.getEmail())) { map.put("sentTo", user.getEmail()); user.setLdapAuthenticated(false); user.setPassword(password); securityService.updateUser(user); } else { map.put("error", "recover.error.sendfailed"); } } } if (settingsService.isCaptchaEnabled()) { map.put("recaptchaSiteKey", settingsService.getRecaptchaSiteKey()); } return new ModelAndView("recover", "model", map); } private User getUserByUsernameOrEmail(String usernameOrEmail) { if (usernameOrEmail != null) { User user = securityService.getUserByName(usernameOrEmail); if (user != null) { return user; } return securityService.getUserByEmail(usernameOrEmail); } return null; } /* * e-mail user new password via configured Smtp server */ private boolean emailPassword(String password, String username, String email) { /* Default to protocol smtp when SmtpEncryption is set to "None" */ String prot = "smtp"; if (settingsService.getSmtpServer() == null || settingsService.getSmtpServer().isEmpty()) { LOG.warn("Can not send email; no Smtp server configured."); return false; } Properties props = new Properties(); if (settingsService.getSmtpEncryption().equals("SSL/TLS")) { prot = "smtps"; props.put("mail." + prot + ".ssl.enable", "true"); } else if (settingsService.getSmtpEncryption().equals("STARTTLS")) { prot = "smtp"; props.put("mail." + prot + ".starttls.enable", "true"); } props.put("mail." + prot + ".host", settingsService.getSmtpServer()); props.put("mail." + prot + ".port", settingsService.getSmtpPort()); /* use authentication when SmtpUser is configured */ if (settingsService.getSmtpUser() != null && !settingsService.getSmtpUser().isEmpty()) { props.put("mail." + prot + ".auth", "true"); } Session session = Session.getInstance(props, null); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(settingsService.getSmtpFrom())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); message.setSubject("Airsonic Password"); message.setText("Hi there!\n\n" + "You have requested to reset your Airsonic password. Please find your new login details below.\n\n" + "Username: " + username + "\n" + "Password: " + password + "\n\n" + "--\n" + "Your Airsonic server\n" + "airsonic.github.io/"); message.setSentDate(new Date()); Transport trans = session.getTransport(prot); try { if (props.get("mail." + prot + ".auth") != null && props.get("mail." + prot + ".auth").equals("true")) { trans.connect(settingsService.getSmtpServer(), settingsService.getSmtpUser(), settingsService.getSmtpPassword()); } else { trans.connect(); } trans.sendMessage(message, message.getAllRecipients()); } finally { trans.close(); } return true; } catch (Exception x) { LOG.warn("Failed to send email.", x); return false; } } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_789_0
crossvul-java_data_good_4761_2
package org.bouncycastle.jcajce.provider.asymmetric.dh; import java.io.ByteArrayOutputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.CipherSpi; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import javax.crypto.interfaces.DHKey; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyEncoder; import org.bouncycastle.crypto.agreement.DHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.engines.DESedeEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.generators.DHKeyPairGenerator; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHKeyGenerationParameters; import org.bouncycastle.crypto.params.DHKeyParameters; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.crypto.parsers.DHIESPublicKeyParser; import org.bouncycastle.jcajce.provider.asymmetric.util.DHUtil; import org.bouncycastle.jcajce.provider.asymmetric.util.IESUtil; import org.bouncycastle.jcajce.util.BCJcaJceHelper; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.interfaces.IESKey; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; public class IESCipher extends CipherSpi { private final JcaJceHelper helper = new BCJcaJceHelper(); private final int ivLength; private IESEngine engine; private int state = -1; private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private AlgorithmParameters engineParam = null; private IESParameterSpec engineSpec = null; private AsymmetricKeyParameter key; private SecureRandom random; private boolean dhaesMode = false; private AsymmetricKeyParameter otherKeyParameter = null; public IESCipher(IESEngine engine) { this.engine = engine; this.ivLength = 0; } public IESCipher(IESEngine engine, int ivLength) { this.engine = engine; this.ivLength = ivLength; } public int engineGetBlockSize() { if (engine.getCipher() != null) { return engine.getCipher().getBlockSize(); } else { return 0; } } public int engineGetKeySize(Key key) { if (key instanceof DHKey) { return ((DHKey)key).getParams().getP().bitLength(); } else { throw new IllegalArgumentException("not a DH key"); } } public byte[] engineGetIV() { if (engineSpec != null) { return engineSpec.getNonce(); } return null; } public AlgorithmParameters engineGetParameters() { if (engineParam == null && engineSpec != null) { try { engineParam = helper.createAlgorithmParameters("IES"); engineParam.init(engineSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } return engineParam; } public void engineSetMode(String mode) throws NoSuchAlgorithmException { String modeName = Strings.toUpperCase(mode); if (modeName.equals("NONE")) { dhaesMode = false; } else if (modeName.equals("DHAES")) { dhaesMode = true; } else { throw new IllegalArgumentException("can't support mode " + mode); } } public int engineGetOutputSize(int inputLen) { int len1, len2, len3; if (key == null) { throw new IllegalStateException("cipher not initialised"); } len1 = engine.getMac().getMacSize(); if (otherKeyParameter == null) { len2 = 1 + 2 * (((DHKeyParameters)key).getParameters().getP().bitLength() + 7) / 8; } else { len2 = 0; } if (engine.getCipher() == null) { len3 = inputLen; } else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen); } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2); } else { throw new IllegalStateException("cipher not initialised"); } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { return buffer.size() + len1 + len2 + len3; } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { return buffer.size() - len1 - len2 + len3; } else { throw new IllegalStateException("IESCipher not initialised"); } } public void engineSetPadding(String padding) throws NoSuchPaddingException { String paddingName = Strings.toUpperCase(padding); // TDOD: make this meaningful... if (paddingName.equals("NOPADDING")) { } else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING")) { } else { throw new NoSuchPaddingException("padding not available with IESCipher"); } } // Initialisation methods public void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { try { paramSpec = params.getParameterSpec(IESParameterSpec.class); } catch (Exception e) { throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString()); } } engineParam = params; engineInit(opmode, key, paramSpec, random); } public void engineInit( int opmode, Key key, AlgorithmParameterSpec engineSpec, SecureRandom random) throws InvalidAlgorithmParameterException, InvalidKeyException { // Use default parameters (including cipher key size) if none are specified if (engineSpec == null) { byte[] nonce = null; if (ivLength != 0 && opmode == Cipher.ENCRYPT_MODE) { nonce = new byte[ivLength]; random.nextBytes(nonce); } this.engineSpec = IESUtil.guessParameterSpec(engine.getCipher(), nonce); } else if (engineSpec instanceof IESParameterSpec) { this.engineSpec = (IESParameterSpec)engineSpec; } else { throw new InvalidAlgorithmParameterException("must be passed IES parameters"); } byte[] nonce = this.engineSpec.getNonce(); if (ivLength != 0 && (nonce == null || nonce.length != ivLength)) { throw new InvalidAlgorithmParameterException("NONCE in IES Parameters needs to be " + ivLength + " bytes long"); } // Parse the recipient's key if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE) { if (key instanceof DHPublicKey) { this.key = DHUtil.generatePublicKeyParameter((PublicKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.key = DHUtil.generatePublicKeyParameter(ieKey.getPublic()); this.otherKeyParameter = DHUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's public DH key for encryption"); } } else if (opmode == Cipher.DECRYPT_MODE || opmode == Cipher.UNWRAP_MODE) { if (key instanceof DHPrivateKey) { this.key = DHUtil.generatePrivateKeyParameter((PrivateKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.otherKeyParameter = DHUtil.generatePublicKeyParameter(ieKey.getPublic()); this.key = DHUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's private DH key for decryption"); } } else { throw new InvalidKeyException("must be passed EC key"); } this.random = random; this.state = opmode; buffer.reset(); } public void engineInit( int opmode, Key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, (AlgorithmParameterSpec)null, random); } catch (InvalidAlgorithmParameterException e) { throw new IllegalArgumentException("cannot handle supplied parameter spec: " + e.getMessage()); } } // Update methods - buffer the input public byte[] engineUpdate( byte[] input, int inputOffset, int inputLen) { buffer.write(input, inputOffset, inputLen); return null; } public int engineUpdate( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { buffer.write(input, inputOffset, inputLen); return 0; } // Finalisation methods public byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (inputLen != 0) { buffer.write(input, inputOffset, inputLen); } byte[] in = buffer.toByteArray(); buffer.reset(); // Convert parameters for use in IESEngine CipherParameters params = new IESWithCipherParameters(engineSpec.getDerivationV(), engineSpec.getEncodingV(), engineSpec.getMacKeySize(), engineSpec.getCipherKeySize()); if (engineSpec.getNonce() != null) { params = new ParametersWithIV(params, engineSpec.getNonce()); } DHParameters dhParams = ((DHKeyParameters)key).getParameters(); byte[] V; if (otherKeyParameter != null) { try { if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { engine.init(true, otherKeyParameter, key, params); } else { engine.init(false, key, otherKeyParameter, params); } return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadPaddingException(e.getMessage()); } } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { // Generate the ephemeral key pair DHKeyPairGenerator gen = new DHKeyPairGenerator(); gen.init(new DHKeyGenerationParameters(random, dhParams)); EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(gen, new KeyEncoder() { public byte[] getEncoded(AsymmetricKeyParameter keyParameter) { byte[] Vloc = new byte[(((DHKeyParameters)keyParameter).getParameters().getP().bitLength() + 7) / 8]; byte[] Vtmp = BigIntegers.asUnsignedByteArray(((DHPublicKeyParameters)keyParameter).getY()); if (Vtmp.length > Vloc.length) { throw new IllegalArgumentException("Senders's public key longer than expected."); } else { System.arraycopy(Vtmp, 0, Vloc, Vloc.length - Vtmp.length, Vtmp.length); } return Vloc; } }); // Encrypt the buffer try { engine.init(key, params, kGen); return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadPaddingException(e.getMessage()); } } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { // Decrypt the buffer try { engine.init(key, params, new DHIESPublicKeyParser(((DHKeyParameters)key).getParameters())); return engine.processBlock(in, 0, in.length); } catch (InvalidCipherTextException e) { throw new BadPaddingException(e.getMessage()); } } else { throw new IllegalStateException("IESCipher not initialised"); } } public int engineDoFinal( byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { byte[] buf = engineDoFinal(input, inputOffset, inputLength); System.arraycopy(buf, 0, output, outputOffset, buf.length); return buf.length; } /** * Classes that inherit from us */ static public class IES extends IESCipher { public IES() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()))); } } static public class IESwithDESedeCBC extends IESCipher { public IESwithDESedeCBC() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()))), 8); } } static public class IESwithAESCBC extends IESCipher { public IESwithAESCBC() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()))), 16); } } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4761_2
crossvul-java_data_good_4755_3
package org.bouncycastle.jcajce.provider.asymmetric.dh; import java.io.IOException; import java.security.InvalidKeyException; import java.security.Key; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHPrivateKeySpec; import javax.crypto.spec.DHPublicKeySpec; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.jcajce.provider.asymmetric.util.BaseKeyFactorySpi; public class KeyFactorySpi extends BaseKeyFactorySpi { public KeyFactorySpi() { } protected KeySpec engineGetKeySpec( Key key, Class spec) throws InvalidKeySpecException { if (spec.isAssignableFrom(DHPrivateKeySpec.class) && key instanceof DHPrivateKey) { DHPrivateKey k = (DHPrivateKey)key; return new DHPrivateKeySpec(k.getX(), k.getParams().getP(), k.getParams().getG()); } else if (spec.isAssignableFrom(DHPublicKeySpec.class) && key instanceof DHPublicKey) { DHPublicKey k = (DHPublicKey)key; return new DHPublicKeySpec(k.getY(), k.getParams().getP(), k.getParams().getG()); } return super.engineGetKeySpec(key, spec); } protected Key engineTranslateKey( Key key) throws InvalidKeyException { if (key instanceof DHPublicKey) { return new BCDHPublicKey((DHPublicKey)key); } else if (key instanceof DHPrivateKey) { return new BCDHPrivateKey((DHPrivateKey)key); } throw new InvalidKeyException("key type unknown"); } protected PrivateKey engineGeneratePrivate( KeySpec keySpec) throws InvalidKeySpecException { if (keySpec instanceof DHPrivateKeySpec) { return new BCDHPrivateKey((DHPrivateKeySpec)keySpec); } return super.engineGeneratePrivate(keySpec); } protected PublicKey engineGeneratePublic( KeySpec keySpec) throws InvalidKeySpecException { if (keySpec instanceof DHPublicKeySpec) { try { return new BCDHPublicKey((DHPublicKeySpec)keySpec); } catch (IllegalArgumentException e) { throw new InvalidKeySpecException(e.getMessage(), e); } } return super.engineGeneratePublic(keySpec); } public PrivateKey generatePrivate(PrivateKeyInfo keyInfo) throws IOException { ASN1ObjectIdentifier algOid = keyInfo.getPrivateKeyAlgorithm().getAlgorithm(); if (algOid.equals(PKCSObjectIdentifiers.dhKeyAgreement)) { return new BCDHPrivateKey(keyInfo); } else if (algOid.equals(X9ObjectIdentifiers.dhpublicnumber)) { return new BCDHPrivateKey(keyInfo); } else { throw new IOException("algorithm identifier " + algOid + " in key not recognised"); } } public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) throws IOException { ASN1ObjectIdentifier algOid = keyInfo.getAlgorithm().getAlgorithm(); if (algOid.equals(PKCSObjectIdentifiers.dhKeyAgreement)) { return new BCDHPublicKey(keyInfo); } else if (algOid.equals(X9ObjectIdentifiers.dhpublicnumber)) { return new BCDHPublicKey(keyInfo); } else { throw new IOException("algorithm identifier " + algOid + " in key not recognised"); } } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4755_3
crossvul-java_data_good_4760_1
package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.DSAParams; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.DSAParameterSpec; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.FixedSecureRandom; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestRandomBigInteger; import org.bouncycastle.util.test.TestRandomData; public class DSATest extends SimpleTest { byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded"); SecureRandom random = new FixedSecureRandom(new byte[][] { k1, k2 }); // DSA modified signatures, courtesy of the Google security team static final DSAPrivateKeySpec PRIVATE_KEY = new DSAPrivateKeySpec( // x new BigInteger( "15382583218386677486843706921635237927801862255437148328980464126979"), // p new BigInteger( "181118486631420055711787706248812146965913392568235070235446058914" + "1170708161715231951918020125044061516370042605439640379530343556" + "4101919053459832890139496933938670005799610981765220283775567361" + "4836626483403394052203488713085936276470766894079318754834062443" + "1033792580942743268186462355159813630244169054658542719322425431" + "4088256212718983105131138772434658820375111735710449331518776858" + "7867938758654181244292694091187568128410190746310049564097068770" + "8161261634790060655580211122402292101772553741704724263582994973" + "9109274666495826205002104010355456981211025738812433088757102520" + "562459649777989718122219159982614304359"), // q new BigInteger( "19689526866605154788513693571065914024068069442724893395618704484701"), // g new BigInteger( "2859278237642201956931085611015389087970918161297522023542900348" + "0877180630984239764282523693409675060100542360520959501692726128" + "3149190229583566074777557293475747419473934711587072321756053067" + "2532404847508798651915566434553729839971841903983916294692452760" + "2490198571084091890169933809199002313226100830607842692992570749" + "0504363602970812128803790973955960534785317485341020833424202774" + "0275688698461842637641566056165699733710043802697192696426360843" + "1736206792141319514001488556117408586108219135730880594044593648" + "9237302749293603778933701187571075920849848690861126195402696457" + "4111219599568903257472567764789616958430")); static final DSAPublicKeySpec PUBLIC_KEY = new DSAPublicKeySpec( new BigInteger( "3846308446317351758462473207111709291533523711306097971550086650" + "2577333637930103311673872185522385807498738696446063139653693222" + "3528823234976869516765207838304932337200968476150071617737755913" + "3181601169463467065599372409821150709457431511200322947508290005" + "1780020974429072640276810306302799924668893998032630777409440831" + "4314588994475223696460940116068336991199969153649625334724122468" + "7497038281983541563359385775312520539189474547346202842754393945" + "8755803223951078082197762886933401284142487322057236814878262166" + "5072306622943221607031324846468109901964841479558565694763440972" + "5447389416166053148132419345627682740529"), PRIVATE_KEY.getP(), PRIVATE_KEY.getQ(), PRIVATE_KEY.getG()); // The following test vectors check for signature malleability and bugs. That means the test // vectors are derived from a valid signature by modifying the ASN encoding. A correct // implementation of DSA should only accept correct DER encoding and properly handle the others. // Allowing alternative BER encodings is in many cases benign. An example where this kind of // signature malleability was a problem: https://en.bitcoin.it/wiki/Transaction_Malleability static final String[] MODIFIED_SIGNATURES = { "303e02811c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f0282001c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021d001e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd02811d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd0282001d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021e0000ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "30813d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "3082003d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9ef4" + "1dd424a4e1c8f16967cf3365813fe87862360000", "3040021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca8021d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3040100", "303e021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca802811d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3" }; private void testModified() throws Exception { KeyFactory kFact = KeyFactory.getInstance("DSA", "BC"); PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY); Signature sig = Signature.getInstance("DSA", "BC"); for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) { sig.initVerify(pubKey); sig.update(Strings.toByteArray("Hello")); boolean failed; try { failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); } catch (SignatureException e) { failed = true; } isTrue("sig verified when shouldn't", failed); } } private void testCompat() throws Exception { if (Security.getProvider("SUN") == null) { return; } Signature s = Signature.getInstance("DSA", "SUN"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); // // sign SUN - verify with BC // s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("SUN -> BC verification failed"); } // // sign BC - verify with SUN // s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("DSA", "SUN"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("BC -> SUN verification failed"); } // // key encoding test - BC decoding Sun keys // KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.getEncoded()); DSAPublicKey k1 = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.getEncoded()); DSAPrivateKey k2 = (DSAPrivateKey)f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); // // key decoding test - SUN decoding BC keys // f = KeyFactory.getInstance("DSA", "SUN"); x509s = new X509EncodedKeySpec(k1.getEncoded()); vKey = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); pkcs8 = new PKCS8EncodedKeySpec(k2.getEncoded()); sKey = f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); } private void testNullParameters() throws Exception { KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new ASN1Integer(10001)).getEncoded()); DSAPublicKey key1 = (DSAPublicKey)f.generatePublic(x509s); DSAPublicKey key2 = (DSAPublicKey)f.generatePublic(x509s); isTrue("parameters not absent", key1.getParams() == null && key2.getParams() == null); isTrue("hashCode mismatch", key1.hashCode() == key2.hashCode()); isTrue("not equal", key1.equals(key2)); isTrue("encoding mismatch", Arrays.areEqual(x509s.getEncoded(), key1.getEncoded())); } private void testValidate() throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); KeyFactory f = KeyFactory.getInstance("DSA", "BC"); try { f.generatePublic(new DSAPublicKeySpec(BigInteger.valueOf(1), dsaParams.getP(), dsaParams.getG(), dsaParams.getQ())); fail("no exception"); } catch (Exception e) { isTrue("mismatch", "invalid KeySpec: y value does not appear to be in correct group".equals(e.getMessage())); } } private void testNONEwithDSA() throws Exception { byte[] dummySha1 = Hex.decode("01020304050607080910111213141516"); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC"); kpGen.initialize(512); KeyPair kp = kpGen.generateKeyPair(); Signature sig = Signature.getInstance("NONEwithDSA", "BC"); sig.initSign(kp.getPrivate()); sig.update(dummySha1); byte[] sigBytes = sig.sign(); sig.initVerify(kp.getPublic()); sig.update(dummySha1); sig.verify(sigBytes); // reset test sig.update(dummySha1); if (!sig.verify(sigBytes)) { fail("NONEwithDSA failed to reset"); } // lightweight test DSAPublicKey key = (DSAPublicKey)kp.getPublic(); DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG()); DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params); DSASigner signer = new DSASigner(); ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes)); signer.init(false, keyParams); if (!signer.verifySignature(dummySha1, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue())) { fail("NONEwithDSA not really NONE!"); } } private void checkPublic(DSAPublicKey k1, PublicKey vKey) { if (!k1.getY().equals(((DSAPublicKey)vKey).getY())) { fail("public number not decoded properly"); } if (!k1.getParams().getG().equals(((DSAPublicKey)vKey).getParams().getG())) { fail("public generator not decoded properly"); } if (!k1.getParams().getP().equals(((DSAPublicKey)vKey).getParams().getP())) { fail("public p value not decoded properly"); } if (!k1.getParams().getQ().equals(((DSAPublicKey)vKey).getParams().getQ())) { fail("public q value not decoded properly"); } } private void checkPrivateKey(DSAPrivateKey k2, PrivateKey sKey) { if (!k2.getX().equals(((DSAPrivateKey)sKey).getX())) { fail("private number not decoded properly"); } if (!k2.getParams().getG().equals(((DSAPrivateKey)sKey).getParams().getG())) { fail("private generator not decoded properly"); } if (!k2.getParams().getP().equals(((DSAPrivateKey)sKey).getParams().getP())) { fail("private p value not decoded properly"); } if (!k2.getParams().getQ().equals(((DSAPrivateKey)sKey).getParams().getQ())) { fail("private q value not decoded properly"); } } private Object serializeDeserialize(Object o) throws Exception { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ObjectOutputStream oOut = new ObjectOutputStream(bOut); oOut.writeObject(o); oOut.close(); ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); return oIn.readObject(); } /** * X9.62 - 1998,<br> * J.3.2, Page 155, ECDSA over the field Fp<br> * an example with 239 bit prime */ private void testECDSA239bitPrime() throws Exception { BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176"); BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); sgr.initSign(sKey, k); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testNONEwithECDSA239bitPrime() throws Exception { ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("NONEwithECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); byte[] message = "abc".getBytes(); byte[] sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e64cb19604be06c57e761b3de5518f71de0f6e0cd2df677cec8a6ffcb690d"); checkMessage(sgr, sKey, vKey, message, sig); message = "abcdefghijklmnopqrstuvwxyz".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e43fd65b3363d76aabef8630572257dbb67c82818ad9fad31256539b1b02c"); checkMessage(sgr, sKey, vKey, message, sig); message = "a very very long message gauranteed to cause an overflow".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e7d5be84b22937a1691859a3c6fe45ed30b108574431d01b34025825ec17a"); checkMessage(sgr, sKey, vKey, message, sig); } private void testECDSAP256sha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { X9ECParameters p = NISTNamedCurves.getByName("P-256"); KeyFactory ecKeyFact = KeyFactory.getInstance("EC", "BC"); ECDomainParameters params = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH()); ECCurve curve = p.getCurve(); ECParameterSpec spec = new ECParameterSpec( curve, p.getG(), // G p.getN()); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( params.getCurve().decodePoint(Hex.decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q spec); doEcDsaTest("SHA3-" + size + "withECDSA", s, ecKeyFact, pubKey, priKey); doEcDsaTest(sigOid.getId(), s, ecKeyFact, pubKey, priKey); } private void doEcDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, ECPublicKeySpec pubKey, ECPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384"); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void testDSAsha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16); BigInteger y = new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16); DSAPrivateKeySpec priKey = new DSAPrivateKeySpec( x, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); DSAPublicKeySpec pubKey = new DSAPublicKeySpec( y, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA", "BC"); doDsaTest("SHA3-" + size + "withDSA", s, dsaKeyFact, pubKey, priKey); doDsaTest(sigOid.getId(), s, dsaKeyFact, pubKey, priKey); } private void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.BigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))), new FixedSecureRandom.Data(Hex.decode("01020304")) }); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void checkMessage(Signature sgr, PrivateKey sKey, PublicKey vKey, byte[] message, byte[] sig) throws InvalidKeyException, SignatureException { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); if (!Arrays.areEqual(sigBytes, sig)) { fail(new String(message) + " signature incorrect"); } sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail(new String(message) + " verification failed"); } } /** * X9.62 - 1998,<br> * J.2.1, Page 100, ECDSA over the field F2m<br> * an example with 191 bit binary field */ private void testECDSA239bitBinary() throws Exception { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testECDSA239bitBinary(String algorithm, ASN1ObjectIdentifier oid) throws Exception { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance(algorithm, "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr = Signature.getInstance(oid.getId(), "BC"); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC RIPEMD160 verification failed"); } } private void testGeneration() throws Exception { Signature s = Signature.getInstance("DSA", "BC"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // test exception // try { g.initialize(513, new SecureRandom()); fail("illegal parameter 513 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(510, new SecureRandom()); fail("illegal parameter 510 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(1025, new SecureRandom()); fail("illegal parameter 1025 check failed."); } catch (IllegalArgumentException e) { // expected } g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } // // key decoding test - serialisation test // DSAPublicKey k1 = (DSAPublicKey)serializeDeserialize(vKey); checkPublic(k1, vKey); checkEquals(k1, vKey); DSAPrivateKey k2 = (DSAPrivateKey)serializeDeserialize(sKey); checkPrivateKey(k2, sKey); checkEquals(k2, sKey); if (!(k2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } // // ECDSA Fp generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // PublicKey eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); PrivateKey eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // Named curve parameter g.initialize(new ECNamedCurveGenParameterSpec("P-256"), new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // // ECDSA F2m generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); if (!(eck2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } } private void checkEquals(Object o1, Object o2) { if (!o1.equals(o2)) { fail("comparison test failed"); } if (o1.hashCode() != o2.hashCode()) { fail("hashCode test failed"); } } private void testParameters() throws Exception { AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(512, random); AlgorithmParameters params = a.generateParameters(); byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } private void testDSA2Parameters() throws Exception { byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(2048, new DSATestSecureRandom(seed)); AlgorithmParameters params = a.generateParameters(); DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); if (!dsaP.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { fail("Q incorrect"); } if (!dsaP.getP().equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { fail("P incorrect"); } if (!dsaP.getG().equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { fail("G incorrect"); } KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new TestRandomBigInteger(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C"))); KeyPair p = g.generateKeyPair(); DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate(); DSAPublicKey vKey = (DSAPublicKey)p.getPublic(); if (!vKey.getY().equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { fail("Y value incorrect"); } if (!sKey.getX().equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { fail("X value incorrect"); } byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } private void testKeyGeneration(int keysize) throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA", "BC"); generator.initialize(keysize); KeyPair keyPair = generator.generateKeyPair(); DSAPrivateKey priv = (DSAPrivateKey)keyPair.getPrivate(); DSAParams params = priv.getParams(); isTrue("keysize mismatch", keysize == params.getP().bitLength()); // The NIST standard does not fully specify the size of q that // must be used for a given key size. Hence there are differences. // For example if keysize = 2048, then OpenSSL uses 256 bit q's by default, // but the SUN provider uses 224 bits. Both are acceptable sizes. // The tests below simply asserts that the size of q does not decrease the // overall security of the DSA. int qsize = params.getQ().bitLength(); switch (keysize) { case 1024: isTrue("Invalid qsize for 1024 bit key:" + qsize, qsize >= 160); break; case 2048: isTrue("Invalid qsize for 2048 bit key:" + qsize, qsize >= 224); break; case 3072: isTrue("Invalid qsize for 3072 bit key:" + qsize, qsize >= 256); break; default: fail("Invalid key size:" + keysize); } // Check the length of the private key. // For example GPG4Browsers or the KJUR library derived from it use // q.bitCount() instead of q.bitLength() to determine the size of the private key // and hence would generate keys that are much too small. isTrue("privkey error", priv.getX().bitLength() >= qsize - 32); } private void testKeyGenerationAll() throws Exception { testKeyGeneration(1024); testKeyGeneration(2048); testKeyGeneration(3072); } public void performTest() throws Exception { testCompat(); testNONEwithDSA(); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16)); testECDSA239bitPrime(); testNONEwithECDSA239bitPrime(); testECDSA239bitBinary(); testECDSA239bitBinary("RIPEMD160withECDSA", TeleTrusTObjectIdentifiers.ecSignWithRipemd160); testECDSA239bitBinary("SHA1withECDSA", TeleTrusTObjectIdentifiers.ecSignWithSha1); testECDSA239bitBinary("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); testECDSA239bitBinary("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); testECDSA239bitBinary("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); testECDSA239bitBinary("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); testECDSA239bitBinary("SHA1withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); testECDSA239bitBinary("SHA224withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); testECDSA239bitBinary("SHA256withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); testECDSA239bitBinary("SHA384withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); testECDSA239bitBinary("SHA512withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger("84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger("99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger("aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger("f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16", 16)); testGeneration(); testParameters(); testDSA2Parameters(); testNullParameters(); testValidate(); testModified(); testKeyGenerationAll(); } protected BigInteger[] derDecode( byte[] encoding) throws IOException { ByteArrayInputStream bIn = new ByteArrayInputStream(encoding); ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1Sequence s = (ASN1Sequence)aIn.readObject(); BigInteger[] sig = new BigInteger[2]; sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); return sig; } public String getName() { return "DSA/ECDSA"; } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new DSATest()); } private class DSATestSecureRandom extends TestRandomData { private boolean first = true; public DSATestSecureRandom(byte[] value) { super(value); } public void nextBytes(byte[] bytes) { if (first) { super.nextBytes(bytes); first = false; } else { bytes[bytes.length - 1] = 2; } } } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4760_1
crossvul-java_data_good_4761_1
package org.bouncycastle.jcajce.provider.asymmetric; import org.bouncycastle.asn1.bsi.BSIObjectIdentifiers; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.sec.SECObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; import org.bouncycastle.util.Properties; public class EC { private static final String PREFIX = "org.bouncycastle.jcajce.provider.asymmetric" + ".ec."; public static class Mappings extends AsymmetricAlgorithmProvider { public Mappings() { } public void configure(ConfigurableProvider provider) { provider.addAlgorithm("AlgorithmParameters.EC", PREFIX + "AlgorithmParametersSpi"); provider.addAlgorithm("KeyAgreement.ECDH", PREFIX + "KeyAgreementSpi$DH"); provider.addAlgorithm("KeyAgreement.ECDHC", PREFIX + "KeyAgreementSpi$DHC"); provider.addAlgorithm("KeyAgreement.ECCDH", PREFIX + "KeyAgreementSpi$DHC"); provider.addAlgorithm("KeyAgreement." + X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme, PREFIX + "KeyAgreementSpi$DHwithSHA1KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + X9ObjectIdentifiers.dhSinglePass_cofactorDH_sha1kdf_scheme, PREFIX + "KeyAgreementSpi$CDHwithSHA1KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_stdDH_sha224kdf_scheme, PREFIX + "KeyAgreementSpi$DHwithSHA224KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_cofactorDH_sha224kdf_scheme, PREFIX + "KeyAgreementSpi$CDHwithSHA224KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_stdDH_sha256kdf_scheme, PREFIX + "KeyAgreementSpi$DHwithSHA256KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_cofactorDH_sha256kdf_scheme, PREFIX + "KeyAgreementSpi$CDHwithSHA256KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_stdDH_sha384kdf_scheme, PREFIX + "KeyAgreementSpi$DHwithSHA384KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_cofactorDH_sha384kdf_scheme, PREFIX + "KeyAgreementSpi$CDHwithSHA384KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_stdDH_sha512kdf_scheme, PREFIX + "KeyAgreementSpi$DHwithSHA512KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_cofactorDH_sha512kdf_scheme, PREFIX + "KeyAgreementSpi$CDHwithSHA512KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement.ECDHWITHSHA1KDF", PREFIX + "KeyAgreementSpi$DHwithSHA1KDF"); provider.addAlgorithm("KeyAgreement.ECCDHWITHSHA1CKDF", PREFIX + "KeyAgreementSpi$DHwithSHA1CKDF"); provider.addAlgorithm("KeyAgreement.ECCDHWITHSHA256CKDF", PREFIX + "KeyAgreementSpi$DHwithSHA256CKDF"); provider.addAlgorithm("KeyAgreement.ECCDHWITHSHA384CKDF", PREFIX + "KeyAgreementSpi$DHwithSHA384CKDF"); provider.addAlgorithm("KeyAgreement.ECCDHWITHSHA512CKDF", PREFIX + "KeyAgreementSpi$DHwithSHA512CKDF"); registerOid(provider, X9ObjectIdentifiers.id_ecPublicKey, "EC", new KeyFactorySpi.EC()); registerOid(provider, X9ObjectIdentifiers.dhSinglePass_cofactorDH_sha1kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme, "ECMQV", new KeyFactorySpi.ECMQV()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha224kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha224kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha256kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha256kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha384kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha384kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha512kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha512kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOidAlgorithmParameters(provider, X9ObjectIdentifiers.id_ecPublicKey, "EC"); registerOidAlgorithmParameters(provider, X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, X9ObjectIdentifiers.dhSinglePass_cofactorDH_sha1kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha224kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha224kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha256kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha256kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha384kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha384kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha512kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha512kdf_scheme, "EC"); if (!Properties.isOverrideSet("org.bouncycastle.ec.disable_mqv")) { provider.addAlgorithm("KeyAgreement.ECMQV", PREFIX + "KeyAgreementSpi$MQV"); provider.addAlgorithm("KeyAgreement.ECMQVWITHSHA1CKDF", PREFIX + "KeyAgreementSpi$MQVwithSHA1CKDF"); provider.addAlgorithm("KeyAgreement.ECMQVWITHSHA224CKDF", PREFIX + "KeyAgreementSpi$MQVwithSHA224CKDF"); provider.addAlgorithm("KeyAgreement.ECMQVWITHSHA256CKDF", PREFIX + "KeyAgreementSpi$MQVwithSHA256CKDF"); provider.addAlgorithm("KeyAgreement.ECMQVWITHSHA384CKDF", PREFIX + "KeyAgreementSpi$MQVwithSHA384CKDF"); provider.addAlgorithm("KeyAgreement.ECMQVWITHSHA512CKDF", PREFIX + "KeyAgreementSpi$MQVwithSHA512CKDF"); provider.addAlgorithm("KeyAgreement." + X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme, PREFIX + "KeyAgreementSpi$MQVwithSHA1KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.mqvSinglePass_sha224kdf_scheme, PREFIX + "KeyAgreementSpi$MQVwithSHA224KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.mqvSinglePass_sha256kdf_scheme, PREFIX + "KeyAgreementSpi$MQVwithSHA256KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.mqvSinglePass_sha384kdf_scheme, PREFIX + "KeyAgreementSpi$MQVwithSHA384KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.mqvSinglePass_sha512kdf_scheme, PREFIX + "KeyAgreementSpi$MQVwithSHA512KDFAndSharedInfo"); registerOid(provider, X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOidAlgorithmParameters(provider, X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme, "EC"); registerOid(provider, SECObjectIdentifiers.mqvSinglePass_sha224kdf_scheme, "ECMQV", new KeyFactorySpi.ECMQV()); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.mqvSinglePass_sha256kdf_scheme, "EC"); registerOid(provider, SECObjectIdentifiers.mqvSinglePass_sha256kdf_scheme, "ECMQV", new KeyFactorySpi.ECMQV()); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.mqvSinglePass_sha224kdf_scheme, "EC"); registerOid(provider, SECObjectIdentifiers.mqvSinglePass_sha384kdf_scheme, "ECMQV", new KeyFactorySpi.ECMQV()); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.mqvSinglePass_sha384kdf_scheme, "EC"); registerOid(provider, SECObjectIdentifiers.mqvSinglePass_sha512kdf_scheme, "ECMQV", new KeyFactorySpi.ECMQV()); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.mqvSinglePass_sha512kdf_scheme, "EC"); provider.addAlgorithm("KeyFactory.ECMQV", PREFIX + "KeyFactorySpi$ECMQV"); provider.addAlgorithm("KeyPairGenerator.ECMQV", PREFIX + "KeyPairGeneratorSpi$ECMQV"); } provider.addAlgorithm("KeyFactory.EC", PREFIX + "KeyFactorySpi$EC"); provider.addAlgorithm("KeyFactory.ECDSA", PREFIX + "KeyFactorySpi$ECDSA"); provider.addAlgorithm("KeyFactory.ECDH", PREFIX + "KeyFactorySpi$ECDH"); provider.addAlgorithm("KeyFactory.ECDHC", PREFIX + "KeyFactorySpi$ECDHC"); provider.addAlgorithm("KeyPairGenerator.EC", PREFIX + "KeyPairGeneratorSpi$EC"); provider.addAlgorithm("KeyPairGenerator.ECDSA", PREFIX + "KeyPairGeneratorSpi$ECDSA"); provider.addAlgorithm("KeyPairGenerator.ECDH", PREFIX + "KeyPairGeneratorSpi$ECDH"); provider.addAlgorithm("KeyPairGenerator.ECDHWITHSHA1KDF", PREFIX + "KeyPairGeneratorSpi$ECDH"); provider.addAlgorithm("KeyPairGenerator.ECDHC", PREFIX + "KeyPairGeneratorSpi$ECDHC"); provider.addAlgorithm("KeyPairGenerator.ECIES", PREFIX + "KeyPairGeneratorSpi$ECDH"); provider.addAlgorithm("Cipher.ECIES", PREFIX + "IESCipher$ECIES"); provider.addAlgorithm("Cipher.ECIESwithAES-CBC", PREFIX + "IESCipher$ECIESwithAESCBC"); provider.addAlgorithm("Cipher.ECIESWITHAES-CBC", PREFIX + "IESCipher$ECIESwithAESCBC"); provider.addAlgorithm("Cipher.ECIESwithDESEDE-CBC", PREFIX + "IESCipher$ECIESwithDESedeCBC"); provider.addAlgorithm("Cipher.ECIESWITHDESEDE-CBC", PREFIX + "IESCipher$ECIESwithDESedeCBC"); provider.addAlgorithm("Signature.ECDSA", PREFIX + "SignatureSpi$ecDSA"); provider.addAlgorithm("Signature.NONEwithECDSA", PREFIX + "SignatureSpi$ecDSAnone"); provider.addAlgorithm("Alg.Alias.Signature.SHA1withECDSA", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.ECDSAwithSHA1", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA1WITHECDSA", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.ECDSAWITHSHA1", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA1WithECDSA", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.ECDSAWithSHA1", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.1.2.840.10045.4.1", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature." + TeleTrusTObjectIdentifiers.ecSignWithSha1, "ECDSA"); provider.addAlgorithm("Signature.ECDDSA", PREFIX + "SignatureSpi$ecDetDSA"); provider.addAlgorithm("Signature.SHA1WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSA"); provider.addAlgorithm("Signature.SHA224WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSA224"); provider.addAlgorithm("Signature.SHA256WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSA256"); provider.addAlgorithm("Signature.SHA384WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSA384"); provider.addAlgorithm("Signature.SHA512WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSA512"); provider.addAlgorithm("Signature.SHA3-224WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSASha3_224"); provider.addAlgorithm("Signature.SHA3-256WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSASha3_256"); provider.addAlgorithm("Signature.SHA3-384WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSASha3_384"); provider.addAlgorithm("Signature.SHA3-512WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSASha3_512"); provider.addAlgorithm("Alg.Alias.Signature.DETECDSA", "ECDDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA1WITHDETECDSA", "SHA1WITHECDDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA224WITHDETECDSA", "SHA224WITHECDDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA256WITHDETECDSA", "SHA256WITHECDDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA384WITHDETECDSA", "SHA384WITHECDDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA512WITHDETECDSA", "SHA512WITHECDDSA"); addSignatureAlgorithm(provider, "SHA224", "ECDSA", PREFIX + "SignatureSpi$ecDSA224", X9ObjectIdentifiers.ecdsa_with_SHA224); addSignatureAlgorithm(provider, "SHA256", "ECDSA", PREFIX + "SignatureSpi$ecDSA256", X9ObjectIdentifiers.ecdsa_with_SHA256); addSignatureAlgorithm(provider, "SHA384", "ECDSA", PREFIX + "SignatureSpi$ecDSA384", X9ObjectIdentifiers.ecdsa_with_SHA384); addSignatureAlgorithm(provider, "SHA512", "ECDSA", PREFIX + "SignatureSpi$ecDSA512", X9ObjectIdentifiers.ecdsa_with_SHA512); addSignatureAlgorithm(provider, "SHA3-224", "ECDSA", PREFIX + "SignatureSpi$ecDSASha3_224", NISTObjectIdentifiers.id_ecdsa_with_sha3_224); addSignatureAlgorithm(provider, "SHA3-256", "ECDSA", PREFIX + "SignatureSpi$ecDSASha3_256", NISTObjectIdentifiers.id_ecdsa_with_sha3_256); addSignatureAlgorithm(provider, "SHA3-384", "ECDSA", PREFIX + "SignatureSpi$ecDSASha3_384", NISTObjectIdentifiers.id_ecdsa_with_sha3_384); addSignatureAlgorithm(provider, "SHA3-512", "ECDSA", PREFIX + "SignatureSpi$ecDSASha3_512", NISTObjectIdentifiers.id_ecdsa_with_sha3_512); addSignatureAlgorithm(provider, "RIPEMD160", "ECDSA", PREFIX + "SignatureSpi$ecDSARipeMD160",TeleTrusTObjectIdentifiers.ecSignWithRipemd160); provider.addAlgorithm("Signature.SHA1WITHECNR", PREFIX + "SignatureSpi$ecNR"); provider.addAlgorithm("Signature.SHA224WITHECNR", PREFIX + "SignatureSpi$ecNR224"); provider.addAlgorithm("Signature.SHA256WITHECNR", PREFIX + "SignatureSpi$ecNR256"); provider.addAlgorithm("Signature.SHA384WITHECNR", PREFIX + "SignatureSpi$ecNR384"); provider.addAlgorithm("Signature.SHA512WITHECNR", PREFIX + "SignatureSpi$ecNR512"); addSignatureAlgorithm(provider, "SHA1", "CVC-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); addSignatureAlgorithm(provider, "SHA224", "CVC-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA224", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); addSignatureAlgorithm(provider, "SHA256", "CVC-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA256", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); addSignatureAlgorithm(provider, "SHA384", "CVC-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA384", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); addSignatureAlgorithm(provider, "SHA512", "CVC-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA512", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); addSignatureAlgorithm(provider, "SHA1", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA", BSIObjectIdentifiers.ecdsa_plain_SHA1); addSignatureAlgorithm(provider, "SHA224", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA224", BSIObjectIdentifiers.ecdsa_plain_SHA224); addSignatureAlgorithm(provider, "SHA256", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA256", BSIObjectIdentifiers.ecdsa_plain_SHA256); addSignatureAlgorithm(provider, "SHA384", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA384", BSIObjectIdentifiers.ecdsa_plain_SHA384); addSignatureAlgorithm(provider, "SHA512", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA512", BSIObjectIdentifiers.ecdsa_plain_SHA512); addSignatureAlgorithm(provider, "RIPEMD160", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecPlainDSARP160", BSIObjectIdentifiers.ecdsa_plain_RIPEMD160); } } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4761_1
crossvul-java_data_bad_4756_2
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) { throw new IllegalStateException("exception on doFinal()", e); } } 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; } } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4756_2
crossvul-java_data_good_4761_0
package org.bouncycastle.jcajce.provider.asymmetric; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.jcajce.provider.asymmetric.dh.KeyFactorySpi; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; public class DH { private static final String PREFIX = "org.bouncycastle.jcajce.provider.asymmetric" + ".dh."; public static class Mappings extends AsymmetricAlgorithmProvider { public Mappings() { } public void configure(ConfigurableProvider provider) { provider.addAlgorithm("KeyPairGenerator.DH", PREFIX + "KeyPairGeneratorSpi"); provider.addAlgorithm("Alg.Alias.KeyPairGenerator.DIFFIEHELLMAN", "DH"); provider.addAlgorithm("KeyAgreement.DH", PREFIX + "KeyAgreementSpi"); provider.addAlgorithm("Alg.Alias.KeyAgreement.DIFFIEHELLMAN", "DH"); provider.addAlgorithm("KeyAgreement", PKCSObjectIdentifiers.id_alg_ESDH, PREFIX + "KeyAgreementSpi$DHwithRFC2631KDF"); provider.addAlgorithm("KeyAgreement", PKCSObjectIdentifiers.id_alg_SSDH, PREFIX + "KeyAgreementSpi$DHwithRFC2631KDF"); provider.addAlgorithm("KeyFactory.DH", PREFIX + "KeyFactorySpi"); provider.addAlgorithm("Alg.Alias.KeyFactory.DIFFIEHELLMAN", "DH"); provider.addAlgorithm("AlgorithmParameters.DH", PREFIX + "AlgorithmParametersSpi"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.DIFFIEHELLMAN", "DH"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator.DIFFIEHELLMAN", "DH"); provider.addAlgorithm("AlgorithmParameterGenerator.DH", PREFIX + "AlgorithmParameterGeneratorSpi"); provider.addAlgorithm("Cipher.IES", PREFIX + "IESCipher$IES"); provider.addAlgorithm("Cipher.IESwithAES-CBC", PREFIX + "IESCipher$IESwithAESCBC"); provider.addAlgorithm("Cipher.IESWITHAES-CBC", PREFIX + "IESCipher$IESwithAESCBC"); provider.addAlgorithm("Cipher.IESWITHDESEDE-CBC", PREFIX + "IESCipher$IESwithDESedeCBC"); provider.addAlgorithm("Cipher.DHIES", PREFIX + "IESCipher$IES"); provider.addAlgorithm("Cipher.DHIESwithAES-CBC", PREFIX + "IESCipher$IESwithAESCBC"); provider.addAlgorithm("Cipher.DHIESWITHAES-CBC", PREFIX + "IESCipher$IESwithAESCBC"); provider.addAlgorithm("Cipher.DHIESWITHDESEDE-CBC", PREFIX + "IESCipher$IESwithDESedeCBC"); registerOid(provider, PKCSObjectIdentifiers.dhKeyAgreement, "DH", new KeyFactorySpi()); registerOid(provider, X9ObjectIdentifiers.dhpublicnumber, "DH", new KeyFactorySpi()); } } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4761_0
crossvul-java_data_bad_4756_1
package org.bouncycastle.jcajce.provider.drbg; import java.lang.reflect.Constructor; import java.security.SecureRandom; import java.security.SecureRandomSpi; import org.bouncycastle.crypto.digests.SHA512Digest; import org.bouncycastle.crypto.prng.SP800SecureRandomBuilder; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; import org.bouncycastle.util.Strings; public class DRBG { private static final String PREFIX = DRBG.class.getName(); private static SecureRandom secureRandom = new SecureRandom(); public static class Default extends SecureRandomSpi { private SecureRandom random = new SP800SecureRandomBuilder(secureRandom, true) .setPersonalizationString(generateDefaultPersonalizationString()) .buildHash(new SHA512Digest(), secureRandom.generateSeed(32), true); @Override protected void engineSetSeed(byte[] bytes) { random.setSeed(bytes); } @Override protected void engineNextBytes(byte[] bytes) { random.nextBytes(bytes); } @Override protected byte[] engineGenerateSeed(int numBytes) { return secureRandom.generateSeed(numBytes); } } public static class NonceAndIV extends SecureRandomSpi { private SecureRandom random = new SP800SecureRandomBuilder(secureRandom, true) .setPersonalizationString(generateNonceIVPersonalizationString()) .buildHash(new SHA512Digest(), secureRandom.generateSeed(32), false); @Override protected void engineSetSeed(byte[] bytes) { random.setSeed(bytes); } @Override protected void engineNextBytes(byte[] bytes) { random.nextBytes(bytes); } @Override protected byte[] engineGenerateSeed(int numBytes) { return secureRandom.generateSeed(numBytes); } } public static class Mappings extends AsymmetricAlgorithmProvider { public Mappings() { } public void configure(ConfigurableProvider provider) { provider.addAlgorithm("SecureRandom.DEFAULT", PREFIX + "$Default"); provider.addAlgorithm("SecureRandom.NONCEANDIV", PREFIX + "$NonceAndIV"); } } private static byte[] generateDefaultPersonalizationString() { return Arrays.concatenate(Strings.toByteArray("Default"), Strings.toUTF8ByteArray(getVIMID()), Pack.longToBigEndian(Thread.currentThread().getId()), Pack.longToBigEndian(System.currentTimeMillis())); } private static byte[] generateNonceIVPersonalizationString() { return Arrays.concatenate(Strings.toByteArray("Default"), Strings.toUTF8ByteArray(getVIMID()), Pack.longToLittleEndian(Thread.currentThread().getId()), Pack.longToLittleEndian(System.currentTimeMillis())); } private static final Constructor vimIDConstructor; static { Class vimIDClass = lookup("java.rmi.dgc.VMID"); if (vimIDClass != null) { vimIDConstructor = findConstructor(vimIDClass); } else { vimIDConstructor = null; } } private static Class lookup(String className) { try { Class def = DRBG.class.getClassLoader().loadClass(className); return def; } catch (Exception e) { return null; } } private static Constructor findConstructor(Class clazz) { try { return clazz.getConstructor(); } catch (Exception e) { return null; } } static String getVIMID() { if (vimIDConstructor != null) { Object vimID = null; try { vimID = vimIDConstructor.newInstance(); } catch (Exception i) { // might happen, fall through if it does } if (vimID != null) { return vimID.toString(); } } return "No VIM ID"; // TODO: maybe there is a system property we can use here. } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4756_1
crossvul-java_data_good_789_0
package org.airsonic.player.controller; import de.triology.recaptchav2java.ReCaptcha; import org.airsonic.player.domain.User; import org.airsonic.player.service.SecurityService; import org.airsonic.player.service.SettingsService; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.security.SecureRandom; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * Spring MVC Controller that serves the login page. */ @Controller @RequestMapping("/recover") public class RecoverController { private static final Logger LOG = LoggerFactory.getLogger(RecoverController.class); private static final String SYMBOLS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; private final SecureRandom random = new SecureRandom(); private static final int PASSWORD_LENGTH = 32; @Autowired private SettingsService settingsService; @Autowired private SecurityService securityService; @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}) public ModelAndView recover(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); String usernameOrEmail = StringUtils.trimToNull(request.getParameter("usernameOrEmail")); if (usernameOrEmail != null) { map.put("usernameOrEmail", usernameOrEmail); User user = getUserByUsernameOrEmail(usernameOrEmail); boolean captchaOk; if (settingsService.isCaptchaEnabled()) { String recaptchaResponse = request.getParameter("g-recaptcha-response"); ReCaptcha captcha = new ReCaptcha(settingsService.getRecaptchaSecretKey()); captchaOk = recaptchaResponse != null && captcha.isValid(recaptchaResponse); } else { captchaOk = true; } if (!captchaOk) { map.put("error", "recover.error.invalidcaptcha"); } else if (user == null) { map.put("error", "recover.error.usernotfound"); } else if (user.getEmail() == null) { map.put("error", "recover.error.noemail"); } else { StringBuilder sb = new StringBuilder(PASSWORD_LENGTH); for(int i=0; i<PASSWORD_LENGTH; i++) { int index = random.nextInt(SYMBOLS.length()); sb.append(SYMBOLS.charAt(index)); } String password = sb.toString(); if (emailPassword(password, user.getUsername(), user.getEmail())) { map.put("sentTo", user.getEmail()); user.setLdapAuthenticated(false); user.setPassword(password); securityService.updateUser(user); } else { map.put("error", "recover.error.sendfailed"); } } } if (settingsService.isCaptchaEnabled()) { map.put("recaptchaSiteKey", settingsService.getRecaptchaSiteKey()); } return new ModelAndView("recover", "model", map); } private User getUserByUsernameOrEmail(String usernameOrEmail) { if (usernameOrEmail != null) { User user = securityService.getUserByName(usernameOrEmail); if (user != null) { return user; } return securityService.getUserByEmail(usernameOrEmail); } return null; } /* * e-mail user new password via configured Smtp server */ private boolean emailPassword(String password, String username, String email) { /* Default to protocol smtp when SmtpEncryption is set to "None" */ String prot = "smtp"; if (settingsService.getSmtpServer() == null || settingsService.getSmtpServer().isEmpty()) { LOG.warn("Can not send email; no Smtp server configured."); return false; } Properties props = new Properties(); if (settingsService.getSmtpEncryption().equals("SSL/TLS")) { prot = "smtps"; props.put("mail." + prot + ".ssl.enable", "true"); } else if (settingsService.getSmtpEncryption().equals("STARTTLS")) { prot = "smtp"; props.put("mail." + prot + ".starttls.enable", "true"); } props.put("mail." + prot + ".host", settingsService.getSmtpServer()); props.put("mail." + prot + ".port", settingsService.getSmtpPort()); /* use authentication when SmtpUser is configured */ if (settingsService.getSmtpUser() != null && !settingsService.getSmtpUser().isEmpty()) { props.put("mail." + prot + ".auth", "true"); } Session session = Session.getInstance(props, null); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(settingsService.getSmtpFrom())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); message.setSubject("Airsonic Password"); message.setText("Hi there!\n\n" + "You have requested to reset your Airsonic password. Please find your new login details below.\n\n" + "Username: " + username + "\n" + "Password: " + password + "\n\n" + "--\n" + "Your Airsonic server\n" + "airsonic.github.io/"); message.setSentDate(new Date()); Transport trans = session.getTransport(prot); try { if (props.get("mail." + prot + ".auth") != null && props.get("mail." + prot + ".auth").equals("true")) { trans.connect(settingsService.getSmtpServer(), settingsService.getSmtpUser(), settingsService.getSmtpPassword()); } else { trans.connect(); } trans.sendMessage(message, message.getAllRecipients()); } finally { trans.close(); } return true; } catch (Exception x) { LOG.warn("Failed to send email.", x); return false; } } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_789_0
crossvul-java_data_bad_4755_1
package org.bouncycastle.crypto.params; import java.math.BigInteger; public class DHPublicKeyParameters extends DHKeyParameters { private static final BigInteger ONE = BigInteger.valueOf(1); private static final BigInteger TWO = BigInteger.valueOf(2); private BigInteger y; public DHPublicKeyParameters( BigInteger y, DHParameters params) { super(false, params); this.y = validate(y, params); } private BigInteger validate(BigInteger y, DHParameters dhParams) { if (y == null) { throw new NullPointerException("y value cannot be null"); } if (dhParams.getQ() != null) { if (ONE.equals(y.modPow(dhParams.getQ(), dhParams.getP()))) { return y; } throw new IllegalArgumentException("Y value does not appear to be in correct group"); } else { // TLS check if (y.compareTo(TWO) < 0 || y.compareTo(dhParams.getP().subtract(TWO)) > 0) { throw new IllegalArgumentException("invalid DH public key"); } return y; // we can't validate without Q. } } public BigInteger getY() { return y; } public int hashCode() { return y.hashCode() ^ super.hashCode(); } public boolean equals( Object obj) { if (!(obj instanceof DHPublicKeyParameters)) { return false; } DHPublicKeyParameters other = (DHPublicKeyParameters)obj; return other.getY().equals(y) && super.equals(obj); } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4755_1
crossvul-java_data_bad_4761_1
package org.bouncycastle.jcajce.provider.asymmetric; import org.bouncycastle.asn1.bsi.BSIObjectIdentifiers; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.sec.SECObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; import org.bouncycastle.util.Properties; public class EC { private static final String PREFIX = "org.bouncycastle.jcajce.provider.asymmetric" + ".ec."; public static class Mappings extends AsymmetricAlgorithmProvider { public Mappings() { } public void configure(ConfigurableProvider provider) { provider.addAlgorithm("AlgorithmParameters.EC", PREFIX + "AlgorithmParametersSpi"); provider.addAlgorithm("KeyAgreement.ECDH", PREFIX + "KeyAgreementSpi$DH"); provider.addAlgorithm("KeyAgreement.ECDHC", PREFIX + "KeyAgreementSpi$DHC"); provider.addAlgorithm("KeyAgreement.ECCDH", PREFIX + "KeyAgreementSpi$DHC"); provider.addAlgorithm("KeyAgreement." + X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme, PREFIX + "KeyAgreementSpi$DHwithSHA1KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + X9ObjectIdentifiers.dhSinglePass_cofactorDH_sha1kdf_scheme, PREFIX + "KeyAgreementSpi$CDHwithSHA1KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_stdDH_sha224kdf_scheme, PREFIX + "KeyAgreementSpi$DHwithSHA224KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_cofactorDH_sha224kdf_scheme, PREFIX + "KeyAgreementSpi$CDHwithSHA224KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_stdDH_sha256kdf_scheme, PREFIX + "KeyAgreementSpi$DHwithSHA256KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_cofactorDH_sha256kdf_scheme, PREFIX + "KeyAgreementSpi$CDHwithSHA256KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_stdDH_sha384kdf_scheme, PREFIX + "KeyAgreementSpi$DHwithSHA384KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_cofactorDH_sha384kdf_scheme, PREFIX + "KeyAgreementSpi$CDHwithSHA384KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_stdDH_sha512kdf_scheme, PREFIX + "KeyAgreementSpi$DHwithSHA512KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.dhSinglePass_cofactorDH_sha512kdf_scheme, PREFIX + "KeyAgreementSpi$CDHwithSHA512KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement.ECDHWITHSHA1KDF", PREFIX + "KeyAgreementSpi$DHwithSHA1KDF"); provider.addAlgorithm("KeyAgreement.ECCDHWITHSHA1CKDF", PREFIX + "KeyAgreementSpi$DHwithSHA1CKDF"); provider.addAlgorithm("KeyAgreement.ECCDHWITHSHA256CKDF", PREFIX + "KeyAgreementSpi$DHwithSHA256CKDF"); provider.addAlgorithm("KeyAgreement.ECCDHWITHSHA384CKDF", PREFIX + "KeyAgreementSpi$DHwithSHA384CKDF"); provider.addAlgorithm("KeyAgreement.ECCDHWITHSHA512CKDF", PREFIX + "KeyAgreementSpi$DHwithSHA512CKDF"); registerOid(provider, X9ObjectIdentifiers.id_ecPublicKey, "EC", new KeyFactorySpi.EC()); registerOid(provider, X9ObjectIdentifiers.dhSinglePass_cofactorDH_sha1kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme, "ECMQV", new KeyFactorySpi.ECMQV()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha224kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha224kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha256kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha256kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha384kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha384kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha512kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOid(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha512kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOidAlgorithmParameters(provider, X9ObjectIdentifiers.id_ecPublicKey, "EC"); registerOidAlgorithmParameters(provider, X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, X9ObjectIdentifiers.dhSinglePass_cofactorDH_sha1kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha224kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha224kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha256kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha256kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha384kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha384kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_stdDH_sha512kdf_scheme, "EC"); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.dhSinglePass_cofactorDH_sha512kdf_scheme, "EC"); if (!Properties.isOverrideSet("org.bouncycastle.ec.disable_mqv")) { provider.addAlgorithm("KeyAgreement.ECMQV", PREFIX + "KeyAgreementSpi$MQV"); provider.addAlgorithm("KeyAgreement.ECMQVWITHSHA1CKDF", PREFIX + "KeyAgreementSpi$MQVwithSHA1CKDF"); provider.addAlgorithm("KeyAgreement.ECMQVWITHSHA224CKDF", PREFIX + "KeyAgreementSpi$MQVwithSHA224CKDF"); provider.addAlgorithm("KeyAgreement.ECMQVWITHSHA256CKDF", PREFIX + "KeyAgreementSpi$MQVwithSHA256CKDF"); provider.addAlgorithm("KeyAgreement.ECMQVWITHSHA384CKDF", PREFIX + "KeyAgreementSpi$MQVwithSHA384CKDF"); provider.addAlgorithm("KeyAgreement.ECMQVWITHSHA512CKDF", PREFIX + "KeyAgreementSpi$MQVwithSHA512CKDF"); provider.addAlgorithm("KeyAgreement." + X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme, PREFIX + "KeyAgreementSpi$MQVwithSHA1KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.mqvSinglePass_sha224kdf_scheme, PREFIX + "KeyAgreementSpi$MQVwithSHA224KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.mqvSinglePass_sha256kdf_scheme, PREFIX + "KeyAgreementSpi$MQVwithSHA256KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.mqvSinglePass_sha384kdf_scheme, PREFIX + "KeyAgreementSpi$MQVwithSHA384KDFAndSharedInfo"); provider.addAlgorithm("KeyAgreement." + SECObjectIdentifiers.mqvSinglePass_sha512kdf_scheme, PREFIX + "KeyAgreementSpi$MQVwithSHA512KDFAndSharedInfo"); registerOid(provider, X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme, "EC", new KeyFactorySpi.EC()); registerOidAlgorithmParameters(provider, X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme, "EC"); registerOid(provider, SECObjectIdentifiers.mqvSinglePass_sha224kdf_scheme, "ECMQV", new KeyFactorySpi.ECMQV()); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.mqvSinglePass_sha256kdf_scheme, "EC"); registerOid(provider, SECObjectIdentifiers.mqvSinglePass_sha256kdf_scheme, "ECMQV", new KeyFactorySpi.ECMQV()); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.mqvSinglePass_sha224kdf_scheme, "EC"); registerOid(provider, SECObjectIdentifiers.mqvSinglePass_sha384kdf_scheme, "ECMQV", new KeyFactorySpi.ECMQV()); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.mqvSinglePass_sha384kdf_scheme, "EC"); registerOid(provider, SECObjectIdentifiers.mqvSinglePass_sha512kdf_scheme, "ECMQV", new KeyFactorySpi.ECMQV()); registerOidAlgorithmParameters(provider, SECObjectIdentifiers.mqvSinglePass_sha512kdf_scheme, "EC"); provider.addAlgorithm("KeyFactory.ECMQV", PREFIX + "KeyFactorySpi$ECMQV"); provider.addAlgorithm("KeyPairGenerator.ECMQV", PREFIX + "KeyPairGeneratorSpi$ECMQV"); } provider.addAlgorithm("KeyFactory.EC", PREFIX + "KeyFactorySpi$EC"); provider.addAlgorithm("KeyFactory.ECDSA", PREFIX + "KeyFactorySpi$ECDSA"); provider.addAlgorithm("KeyFactory.ECDH", PREFIX + "KeyFactorySpi$ECDH"); provider.addAlgorithm("KeyFactory.ECDHC", PREFIX + "KeyFactorySpi$ECDHC"); provider.addAlgorithm("KeyPairGenerator.EC", PREFIX + "KeyPairGeneratorSpi$EC"); provider.addAlgorithm("KeyPairGenerator.ECDSA", PREFIX + "KeyPairGeneratorSpi$ECDSA"); provider.addAlgorithm("KeyPairGenerator.ECDH", PREFIX + "KeyPairGeneratorSpi$ECDH"); provider.addAlgorithm("KeyPairGenerator.ECDHWITHSHA1KDF", PREFIX + "KeyPairGeneratorSpi$ECDH"); provider.addAlgorithm("KeyPairGenerator.ECDHC", PREFIX + "KeyPairGeneratorSpi$ECDHC"); provider.addAlgorithm("KeyPairGenerator.ECIES", PREFIX + "KeyPairGeneratorSpi$ECDH"); provider.addAlgorithm("Cipher.ECIES", PREFIX + "IESCipher$ECIES"); provider.addAlgorithm("Cipher.ECIESwithAES", PREFIX + "IESCipher$ECIESwithAES"); provider.addAlgorithm("Cipher.ECIESWITHAES", PREFIX + "IESCipher$ECIESwithAES"); provider.addAlgorithm("Cipher.ECIESwithDESEDE", PREFIX + "IESCipher$ECIESwithDESede"); provider.addAlgorithm("Cipher.ECIESWITHDESEDE", PREFIX + "IESCipher$ECIESwithDESede"); provider.addAlgorithm("Cipher.ECIESwithAES-CBC", PREFIX + "IESCipher$ECIESwithAESCBC"); provider.addAlgorithm("Cipher.ECIESWITHAES-CBC", PREFIX + "IESCipher$ECIESwithAESCBC"); provider.addAlgorithm("Cipher.ECIESwithDESEDE-CBC", PREFIX + "IESCipher$ECIESwithDESedeCBC"); provider.addAlgorithm("Cipher.ECIESWITHDESEDE-CBC", PREFIX + "IESCipher$ECIESwithDESedeCBC"); provider.addAlgorithm("Cipher.OldECIES", PREFIX + "IESCipher$OldECIES"); provider.addAlgorithm("Cipher.OldECIESwithAES", PREFIX + "IESCipher$OldECIESwithAES"); provider.addAlgorithm("Cipher.OldECIESWITHAES", PREFIX + "IESCipher$OldECIESwithAES"); provider.addAlgorithm("Cipher.OldECIESwithDESEDE", PREFIX + "IESCipher$OldECIESwithDESede"); provider.addAlgorithm("Cipher.OldECIESWITHDESEDE", PREFIX + "IESCipher$OldECIESwithDESede"); provider.addAlgorithm("Cipher.OldECIESwithAES-CBC", PREFIX + "IESCipher$OldECIESwithAESCBC"); provider.addAlgorithm("Cipher.OldECIESWITHAES-CBC", PREFIX + "IESCipher$OldECIESwithAESCBC"); provider.addAlgorithm("Cipher.OldECIESwithDESEDE-CBC", PREFIX + "IESCipher$OldECIESwithDESedeCBC"); provider.addAlgorithm("Cipher.OldECIESWITHDESEDE-CBC", PREFIX + "IESCipher$OldECIESwithDESedeCBC"); provider.addAlgorithm("Signature.ECDSA", PREFIX + "SignatureSpi$ecDSA"); provider.addAlgorithm("Signature.NONEwithECDSA", PREFIX + "SignatureSpi$ecDSAnone"); provider.addAlgorithm("Alg.Alias.Signature.SHA1withECDSA", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.ECDSAwithSHA1", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA1WITHECDSA", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.ECDSAWITHSHA1", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA1WithECDSA", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.ECDSAWithSHA1", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature.1.2.840.10045.4.1", "ECDSA"); provider.addAlgorithm("Alg.Alias.Signature." + TeleTrusTObjectIdentifiers.ecSignWithSha1, "ECDSA"); provider.addAlgorithm("Signature.ECDDSA", PREFIX + "SignatureSpi$ecDetDSA"); provider.addAlgorithm("Signature.SHA1WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSA"); provider.addAlgorithm("Signature.SHA224WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSA224"); provider.addAlgorithm("Signature.SHA256WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSA256"); provider.addAlgorithm("Signature.SHA384WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSA384"); provider.addAlgorithm("Signature.SHA512WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSA512"); provider.addAlgorithm("Signature.SHA3-224WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSASha3_224"); provider.addAlgorithm("Signature.SHA3-256WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSASha3_256"); provider.addAlgorithm("Signature.SHA3-384WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSASha3_384"); provider.addAlgorithm("Signature.SHA3-512WITHECDDSA", PREFIX + "SignatureSpi$ecDetDSASha3_512"); provider.addAlgorithm("Alg.Alias.Signature.DETECDSA", "ECDDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA1WITHDETECDSA", "SHA1WITHECDDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA224WITHDETECDSA", "SHA224WITHECDDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA256WITHDETECDSA", "SHA256WITHECDDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA384WITHDETECDSA", "SHA384WITHECDDSA"); provider.addAlgorithm("Alg.Alias.Signature.SHA512WITHDETECDSA", "SHA512WITHECDDSA"); addSignatureAlgorithm(provider, "SHA224", "ECDSA", PREFIX + "SignatureSpi$ecDSA224", X9ObjectIdentifiers.ecdsa_with_SHA224); addSignatureAlgorithm(provider, "SHA256", "ECDSA", PREFIX + "SignatureSpi$ecDSA256", X9ObjectIdentifiers.ecdsa_with_SHA256); addSignatureAlgorithm(provider, "SHA384", "ECDSA", PREFIX + "SignatureSpi$ecDSA384", X9ObjectIdentifiers.ecdsa_with_SHA384); addSignatureAlgorithm(provider, "SHA512", "ECDSA", PREFIX + "SignatureSpi$ecDSA512", X9ObjectIdentifiers.ecdsa_with_SHA512); addSignatureAlgorithm(provider, "SHA3-224", "ECDSA", PREFIX + "SignatureSpi$ecDSASha3_224", NISTObjectIdentifiers.id_ecdsa_with_sha3_224); addSignatureAlgorithm(provider, "SHA3-256", "ECDSA", PREFIX + "SignatureSpi$ecDSASha3_256", NISTObjectIdentifiers.id_ecdsa_with_sha3_256); addSignatureAlgorithm(provider, "SHA3-384", "ECDSA", PREFIX + "SignatureSpi$ecDSASha3_384", NISTObjectIdentifiers.id_ecdsa_with_sha3_384); addSignatureAlgorithm(provider, "SHA3-512", "ECDSA", PREFIX + "SignatureSpi$ecDSASha3_512", NISTObjectIdentifiers.id_ecdsa_with_sha3_512); addSignatureAlgorithm(provider, "RIPEMD160", "ECDSA", PREFIX + "SignatureSpi$ecDSARipeMD160",TeleTrusTObjectIdentifiers.ecSignWithRipemd160); provider.addAlgorithm("Signature.SHA1WITHECNR", PREFIX + "SignatureSpi$ecNR"); provider.addAlgorithm("Signature.SHA224WITHECNR", PREFIX + "SignatureSpi$ecNR224"); provider.addAlgorithm("Signature.SHA256WITHECNR", PREFIX + "SignatureSpi$ecNR256"); provider.addAlgorithm("Signature.SHA384WITHECNR", PREFIX + "SignatureSpi$ecNR384"); provider.addAlgorithm("Signature.SHA512WITHECNR", PREFIX + "SignatureSpi$ecNR512"); addSignatureAlgorithm(provider, "SHA1", "CVC-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); addSignatureAlgorithm(provider, "SHA224", "CVC-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA224", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); addSignatureAlgorithm(provider, "SHA256", "CVC-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA256", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); addSignatureAlgorithm(provider, "SHA384", "CVC-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA384", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); addSignatureAlgorithm(provider, "SHA512", "CVC-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA512", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); addSignatureAlgorithm(provider, "SHA1", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA", BSIObjectIdentifiers.ecdsa_plain_SHA1); addSignatureAlgorithm(provider, "SHA224", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA224", BSIObjectIdentifiers.ecdsa_plain_SHA224); addSignatureAlgorithm(provider, "SHA256", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA256", BSIObjectIdentifiers.ecdsa_plain_SHA256); addSignatureAlgorithm(provider, "SHA384", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA384", BSIObjectIdentifiers.ecdsa_plain_SHA384); addSignatureAlgorithm(provider, "SHA512", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecCVCDSA512", BSIObjectIdentifiers.ecdsa_plain_SHA512); addSignatureAlgorithm(provider, "RIPEMD160", "PLAIN-ECDSA", PREFIX + "SignatureSpi$ecPlainDSARP160", BSIObjectIdentifiers.ecdsa_plain_RIPEMD160); } } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4761_1
crossvul-java_data_bad_4756_0
package org.bouncycastle.crypto.engines; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.util.Pack; /** * an implementation of the AES (Rijndael), from FIPS-197. * <p> * For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>. * * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at * <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a> * * There are three levels of tradeoff of speed vs memory * Because java has no preprocessor, they are written as three separate classes from which to choose * * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption * and 4 for decryption. * * The middle performance version uses only one 256 word table for each, for a total of 2Kbytes, * adding 12 rotate operations per round to compute the values contained in the other tables from * the contents of the first * * The slowest version uses no static tables at all and computes the values in each round * <p> * This file contains the fast version with 8Kbytes of static tables for round precomputation * */ public class AESFastEngine implements BlockCipher { // The S box private static final byte[] S = { (byte)99, (byte)124, (byte)119, (byte)123, (byte)242, (byte)107, (byte)111, (byte)197, (byte)48, (byte)1, (byte)103, (byte)43, (byte)254, (byte)215, (byte)171, (byte)118, (byte)202, (byte)130, (byte)201, (byte)125, (byte)250, (byte)89, (byte)71, (byte)240, (byte)173, (byte)212, (byte)162, (byte)175, (byte)156, (byte)164, (byte)114, (byte)192, (byte)183, (byte)253, (byte)147, (byte)38, (byte)54, (byte)63, (byte)247, (byte)204, (byte)52, (byte)165, (byte)229, (byte)241, (byte)113, (byte)216, (byte)49, (byte)21, (byte)4, (byte)199, (byte)35, (byte)195, (byte)24, (byte)150, (byte)5, (byte)154, (byte)7, (byte)18, (byte)128, (byte)226, (byte)235, (byte)39, (byte)178, (byte)117, (byte)9, (byte)131, (byte)44, (byte)26, (byte)27, (byte)110, (byte)90, (byte)160, (byte)82, (byte)59, (byte)214, (byte)179, (byte)41, (byte)227, (byte)47, (byte)132, (byte)83, (byte)209, (byte)0, (byte)237, (byte)32, (byte)252, (byte)177, (byte)91, (byte)106, (byte)203, (byte)190, (byte)57, (byte)74, (byte)76, (byte)88, (byte)207, (byte)208, (byte)239, (byte)170, (byte)251, (byte)67, (byte)77, (byte)51, (byte)133, (byte)69, (byte)249, (byte)2, (byte)127, (byte)80, (byte)60, (byte)159, (byte)168, (byte)81, (byte)163, (byte)64, (byte)143, (byte)146, (byte)157, (byte)56, (byte)245, (byte)188, (byte)182, (byte)218, (byte)33, (byte)16, (byte)255, (byte)243, (byte)210, (byte)205, (byte)12, (byte)19, (byte)236, (byte)95, (byte)151, (byte)68, (byte)23, (byte)196, (byte)167, (byte)126, (byte)61, (byte)100, (byte)93, (byte)25, (byte)115, (byte)96, (byte)129, (byte)79, (byte)220, (byte)34, (byte)42, (byte)144, (byte)136, (byte)70, (byte)238, (byte)184, (byte)20, (byte)222, (byte)94, (byte)11, (byte)219, (byte)224, (byte)50, (byte)58, (byte)10, (byte)73, (byte)6, (byte)36, (byte)92, (byte)194, (byte)211, (byte)172, (byte)98, (byte)145, (byte)149, (byte)228, (byte)121, (byte)231, (byte)200, (byte)55, (byte)109, (byte)141, (byte)213, (byte)78, (byte)169, (byte)108, (byte)86, (byte)244, (byte)234, (byte)101, (byte)122, (byte)174, (byte)8, (byte)186, (byte)120, (byte)37, (byte)46, (byte)28, (byte)166, (byte)180, (byte)198, (byte)232, (byte)221, (byte)116, (byte)31, (byte)75, (byte)189, (byte)139, (byte)138, (byte)112, (byte)62, (byte)181, (byte)102, (byte)72, (byte)3, (byte)246, (byte)14, (byte)97, (byte)53, (byte)87, (byte)185, (byte)134, (byte)193, (byte)29, (byte)158, (byte)225, (byte)248, (byte)152, (byte)17, (byte)105, (byte)217, (byte)142, (byte)148, (byte)155, (byte)30, (byte)135, (byte)233, (byte)206, (byte)85, (byte)40, (byte)223, (byte)140, (byte)161, (byte)137, (byte)13, (byte)191, (byte)230, (byte)66, (byte)104, (byte)65, (byte)153, (byte)45, (byte)15, (byte)176, (byte)84, (byte)187, (byte)22, }; // The inverse S-box private static final byte[] Si = { (byte)82, (byte)9, (byte)106, (byte)213, (byte)48, (byte)54, (byte)165, (byte)56, (byte)191, (byte)64, (byte)163, (byte)158, (byte)129, (byte)243, (byte)215, (byte)251, (byte)124, (byte)227, (byte)57, (byte)130, (byte)155, (byte)47, (byte)255, (byte)135, (byte)52, (byte)142, (byte)67, (byte)68, (byte)196, (byte)222, (byte)233, (byte)203, (byte)84, (byte)123, (byte)148, (byte)50, (byte)166, (byte)194, (byte)35, (byte)61, (byte)238, (byte)76, (byte)149, (byte)11, (byte)66, (byte)250, (byte)195, (byte)78, (byte)8, (byte)46, (byte)161, (byte)102, (byte)40, (byte)217, (byte)36, (byte)178, (byte)118, (byte)91, (byte)162, (byte)73, (byte)109, (byte)139, (byte)209, (byte)37, (byte)114, (byte)248, (byte)246, (byte)100, (byte)134, (byte)104, (byte)152, (byte)22, (byte)212, (byte)164, (byte)92, (byte)204, (byte)93, (byte)101, (byte)182, (byte)146, (byte)108, (byte)112, (byte)72, (byte)80, (byte)253, (byte)237, (byte)185, (byte)218, (byte)94, (byte)21, (byte)70, (byte)87, (byte)167, (byte)141, (byte)157, (byte)132, (byte)144, (byte)216, (byte)171, (byte)0, (byte)140, (byte)188, (byte)211, (byte)10, (byte)247, (byte)228, (byte)88, (byte)5, (byte)184, (byte)179, (byte)69, (byte)6, (byte)208, (byte)44, (byte)30, (byte)143, (byte)202, (byte)63, (byte)15, (byte)2, (byte)193, (byte)175, (byte)189, (byte)3, (byte)1, (byte)19, (byte)138, (byte)107, (byte)58, (byte)145, (byte)17, (byte)65, (byte)79, (byte)103, (byte)220, (byte)234, (byte)151, (byte)242, (byte)207, (byte)206, (byte)240, (byte)180, (byte)230, (byte)115, (byte)150, (byte)172, (byte)116, (byte)34, (byte)231, (byte)173, (byte)53, (byte)133, (byte)226, (byte)249, (byte)55, (byte)232, (byte)28, (byte)117, (byte)223, (byte)110, (byte)71, (byte)241, (byte)26, (byte)113, (byte)29, (byte)41, (byte)197, (byte)137, (byte)111, (byte)183, (byte)98, (byte)14, (byte)170, (byte)24, (byte)190, (byte)27, (byte)252, (byte)86, (byte)62, (byte)75, (byte)198, (byte)210, (byte)121, (byte)32, (byte)154, (byte)219, (byte)192, (byte)254, (byte)120, (byte)205, (byte)90, (byte)244, (byte)31, (byte)221, (byte)168, (byte)51, (byte)136, (byte)7, (byte)199, (byte)49, (byte)177, (byte)18, (byte)16, (byte)89, (byte)39, (byte)128, (byte)236, (byte)95, (byte)96, (byte)81, (byte)127, (byte)169, (byte)25, (byte)181, (byte)74, (byte)13, (byte)45, (byte)229, (byte)122, (byte)159, (byte)147, (byte)201, (byte)156, (byte)239, (byte)160, (byte)224, (byte)59, (byte)77, (byte)174, (byte)42, (byte)245, (byte)176, (byte)200, (byte)235, (byte)187, (byte)60, (byte)131, (byte)83, (byte)153, (byte)97, (byte)23, (byte)43, (byte)4, (byte)126, (byte)186, (byte)119, (byte)214, (byte)38, (byte)225, (byte)105, (byte)20, (byte)99, (byte)85, (byte)33, (byte)12, (byte)125, }; // vector used in calculating key schedule (powers of x in GF(256)) private static final int[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; // precomputation tables of calculations for rounds private static final int[] T = { // T0 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c, // T1 0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f, 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db, 0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, 0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, 0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a, // T2 0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05, 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49, 0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, 0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, 0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16, // T3 0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505, 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, 0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616}; private static final int[] Tinv = { // Tinv0 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0, // Tinv1 0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, 0x459d1ff1, 0x58faacab, 0x03e34b93, 0xfa302055, 0x6d76adf6, 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0x0eea4598, 0xc0fe5de1, 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b, 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19, 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x024b72e2, 0x8f1fe357, 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x0837d3a5, 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b, 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51, 0x8a213ef9, 0x06dd963d, 0x053eddae, 0xbde64d46, 0x8d5491b5, 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, 0xeec879db, 0x0a7ca147, 0x0f427ce9, 0x1e84f8c9, 0x00000000, 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2, 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0x0d090e0b, 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x0775af4c, 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d, 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef, 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0x0bd49836, 0x81f5a6cf, 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x099fead4, 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d, 0x4daacc54, 0x0496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c, 0x0ca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886, 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x01a83971, 0xb30c08de, 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, 0x57b8d042, // Tinv2 0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, 0xcc889176, 0x02f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e, 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, 0x6bbb84ae, 0x81fe1ca0, 0x08f9942b, 0x48705868, 0x458f19fd, 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, 0x2830f287, 0xbf23b2a5, 0x0302ba6a, 0x16ed5c82, 0xcf8a2b1c, 0x79a792b4, 0x07f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x0506d5be, 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110, 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, 0xc471055d, 0x06046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x00000000, 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0x0efdfbff, 0x850f5638, 0xae3d1ed5, 0x2d362739, 0x0f0a64d9, 0x5c6821a6, 0x5b9bd154, 0x36243a2e, 0x0a0cb167, 0x57930fe7, 0xeeb4d296, 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x090e0b0d, 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07, 0x99eebbdd, 0x7fa3fd60, 0x01f79f26, 0x725cbcf5, 0x6644c53b, 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24, 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90, 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409, 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x04f14a98, 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0, 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0x0bfb2e41, 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61, 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db, 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, 0xe2bc0c25, 0x3c288b49, 0x0dff4195, 0xa8397101, 0x0c08deb3, 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, 0xb8d04257, // Tinv3 0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x03e75f8f, 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58, 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45, 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, 0x30f28728, 0x23b2a5bf, 0x02ba6a03, 0xed5c8216, 0x8a2b1ccf, 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x06d5be05, 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x0532e18a, 0xa475ebf6, 0x0b39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e, 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, 0x71055dc4, 0x046fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x07888b89, 0xe7385b19, 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x00000000, 0x09838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, 0x0f563885, 0x3d1ed5ae, 0x3627392d, 0x0a64d90f, 0x6821a65c, 0x9bd1545b, 0x243a2e36, 0x0cb1670a, 0x930fe757, 0xb4d296ee, 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0x0e0b0d09, 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775, 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a, 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, 0x0dec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033, 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f, 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef, 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, 0x467f5165, 0x9d04ea5e, 0x015d358c, 0xfa737487, 0xfb2e410b, 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7, 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44, 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x08deb30c, 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, 0xd04257b8}; private static int shift(int r, int shift) { return (r >>> shift) | (r << -shift); } /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ private static final int m1 = 0x80808080; private static final int m2 = 0x7f7f7f7f; private static final int m3 = 0x0000001b; private static final int m4 = 0xC0C0C0C0; private static final int m5 = 0x3f3f3f3f; private static int FFmulX(int x) { return (((x & m2) << 1) ^ (((x & m1) >>> 7) * m3)); } private static int FFmulX2(int x) { int t0 = (x & m5) << 2; int t1 = (x & m4); t1 ^= (t1 >>> 1); return t0 ^ (t1 >>> 2) ^ (t1 >>> 5); } /* The following defines provide alternative definitions of FFmulX that might give improved performance if a fast 32-bit multiply is not available. private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = 0x1b1b1b1b; private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } */ private static int inv_mcol(int x) { int t0, t1; t0 = x; t1 = t0 ^ shift(t0, 8); t0 ^= FFmulX(t1); t1 ^= FFmulX2(t0); t0 ^= t1 ^ shift(t1, 16); return t0; } private static int subWord(int x) { int i0 = x, i1 = x >>> 8, i2 = x >>> 16, i3 = x >>> 24; i0 = S[i0 & 255] & 255; i1 = S[i1 & 255] & 255; i2 = S[i2 & 255] & 255; i3 = S[i3 & 255] & 255; return i0 | i1 << 8 | i2 << 16 | i3 << 24; } /** * Calculate the necessary round keys * The number of calculations depends on key size and block size * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ private int[][] generateWorkingKey(byte[] key, boolean forEncryption) { int keyLen = key.length; if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) { throw new IllegalArgumentException("Key length not 128/192/256 bits."); } int KC = keyLen >>> 2; ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes int[][] W = new int[ROUNDS+1][4]; // 4 words in a block switch (KC) { case 4: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; for (int i = 1; i <= 10; ++i) { int u = subWord(shift(t3, 8)) ^ rcon[i - 1]; t0 ^= u; W[i][0] = t0; t1 ^= t0; W[i][1] = t1; t2 ^= t1; W[i][2] = t2; t3 ^= t2; W[i][3] = t3; } break; } case 6: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; int t4 = Pack.littleEndianToInt(key, 16); W[1][0] = t4; int t5 = Pack.littleEndianToInt(key, 20); W[1][1] = t5; int rcon = 1; int u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[1][2] = t0; t1 ^= t0; W[1][3] = t1; t2 ^= t1; W[2][0] = t2; t3 ^= t2; W[2][1] = t3; t4 ^= t3; W[2][2] = t4; t5 ^= t4; W[2][3] = t5; for (int i = 3; i < 12; i += 3) { u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i ][0] = t0; t1 ^= t0; W[i ][1] = t1; t2 ^= t1; W[i ][2] = t2; t3 ^= t2; W[i ][3] = t3; t4 ^= t3; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i + 1][2] = t0; t1 ^= t0; W[i + 1][3] = t1; t2 ^= t1; W[i + 2][0] = t2; t3 ^= t2; W[i + 2][1] = t3; t4 ^= t3; W[i + 2][2] = t4; t5 ^= t4; W[i + 2][3] = t5; } u = subWord(shift(t5, 8)) ^ rcon; t0 ^= u; W[12][0] = t0; t1 ^= t0; W[12][1] = t1; t2 ^= t1; W[12][2] = t2; t3 ^= t2; W[12][3] = t3; break; } case 8: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; int t4 = Pack.littleEndianToInt(key, 16); W[1][0] = t4; int t5 = Pack.littleEndianToInt(key, 20); W[1][1] = t5; int t6 = Pack.littleEndianToInt(key, 24); W[1][2] = t6; int t7 = Pack.littleEndianToInt(key, 28); W[1][3] = t7; int u, rcon = 1; for (int i = 2; i < 14; i += 2) { u = subWord(shift(t7, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i ][0] = t0; t1 ^= t0; W[i ][1] = t1; t2 ^= t1; W[i ][2] = t2; t3 ^= t2; W[i ][3] = t3; u = subWord(t3); t4 ^= u; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; t6 ^= t5; W[i + 1][2] = t6; t7 ^= t6; W[i + 1][3] = t7; } u = subWord(shift(t7, 8)) ^ rcon; t0 ^= u; W[14][0] = t0; t1 ^= t0; W[14][1] = t1; t2 ^= t1; W[14][2] = t2; t3 ^= t2; W[14][3] = t3; break; } default: { throw new IllegalStateException("Should never get here"); } } if (!forEncryption) { for (int j = 1; j < ROUNDS; j++) { for (int i = 0; i < 4; i++) { W[j][i] = inv_mcol(W[j][i]); } } } return W; } private int ROUNDS; private int[][] WorkingKey = null; private int C0, C1, C2, C3; private boolean forEncryption; private static final int BLOCK_SIZE = 16; /** * default constructor - 128 bit block size. */ public AESFastEngine() { } /** * initialise an AES cipher. * * @param forEncryption whether or not we are for encryption. * @param params the parameters required to set up the cipher. * @exception IllegalArgumentException if the params argument is * inappropriate. */ public void init( boolean forEncryption, CipherParameters params) { if (params instanceof KeyParameter) { WorkingKey = generateWorkingKey(((KeyParameter)params).getKey(), forEncryption); this.forEncryption = forEncryption; return; } throw new IllegalArgumentException("invalid parameter passed to AES init - " + params.getClass().getName()); } public String getAlgorithmName() { return "AES"; } public int getBlockSize() { return BLOCK_SIZE; } public int processBlock( byte[] in, int inOff, byte[] out, int outOff) { if (WorkingKey == null) { throw new IllegalStateException("AES engine not initialised"); } if ((inOff + (32 / 2)) > in.length) { throw new DataLengthException("input buffer too short"); } if ((outOff + (32 / 2)) > out.length) { throw new OutputLengthException("output buffer too short"); } unpackBlock(in, inOff); if (forEncryption) { encryptBlock(WorkingKey); } else { decryptBlock(WorkingKey); } packBlock(out, outOff); return BLOCK_SIZE; } public void reset() { } private void unpackBlock(byte[] bytes, int off) { this.C0 = Pack.littleEndianToInt(bytes, off); this.C1 = Pack.littleEndianToInt(bytes, off + 4); this.C2 = Pack.littleEndianToInt(bytes, off + 8); this.C3 = Pack.littleEndianToInt(bytes, off + 12); } private void packBlock(byte[] bytes, int off) { Pack.intToLittleEndian(this.C0, bytes, off); Pack.intToLittleEndian(this.C1, bytes, off + 4); Pack.intToLittleEndian(this.C2, bytes, off + 8); Pack.intToLittleEndian(this.C3, bytes, off + 12); } private void encryptBlock(int[][] KW) { int t0 = this.C0 ^ KW[0][0]; int t1 = this.C1 ^ KW[0][1]; int t2 = this.C2 ^ KW[0][2]; /* * Fast engine has precomputed rotr(T0, 8/16/24) tables T1/T2/T3. * * Placing all precomputes in one array requires offsets additions for 8/16/24 rotations but * avoids additional array range checks on 3 more arrays (which on HotSpot are more * expensive than the offset additions). */ int r = 1, r0, r1, r2, r3 = this.C3 ^ KW[0][3]; int i0, i1, i2, i3; while (r < ROUNDS - 1) { i0 = t0; i1 = t1 >>> 8; i2 = t2 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r0 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][0]; i0 = t1; i1 = t2 >>> 8; i2 = r3 >>> 16; i3 = t0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r1 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][1]; i0 = t2; i1 = r3 >>> 8; i2 = t0 >>> 16; i3 = t1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r2 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][2]; i0 = r3; i1 = t0 >>> 8; i2 = t1 >>> 16; i3 = t2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r++][3]; i0 = r0; i1 = r1 >>> 8; i2 = r2 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t0 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][0]; i0 = r1; i1 = r2 >>> 8; i2 = r3 >>> 16; i3 = r0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t1 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][1]; i0 = r2; i1 = r3 >>> 8; i2 = r0 >>> 16; i3 = r1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t2 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][2]; i0 = r3; i1 = r0 >>> 8; i2 = r1 >>> 16; i3 = r2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r++][3]; } i0 = t0; i1 = t1 >>> 8; i2 = t2 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r0 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][0]; i0 = t1; i1 = t2 >>> 8; i2 = r3 >>> 16; i3 = t0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r1 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][1]; i0 = t2; i1 = r3 >>> 8; i2 = t0 >>> 16; i3 = t1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r2 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r][2]; i0 = r3; i1 = t0 >>> 8; i2 = t1 >>> 16; i3 = t2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = T[i0] ^ T[256 + i1] ^ T[512 + i2] ^ T[768 + i3] ^ KW[r++][3]; // the final round's table is a simple function of S so we don't use a whole other four tables for it i0 = r0; i1 = r1 >>> 8; i2 = r2 >>> 16; i3 = r3 >>> 24; i0 = S[i0 & 255] & 255; i1 = S[i1 & 255] & 255; i2 = S[i2 & 255] & 255; i3 = S[i3 & 255] & 255; this.C0 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[r][0]; i0 = r1; i1 = r2 >>> 8; i2 = r3 >>> 16; i3 = r0 >>> 24; i0 = S[i0 & 255] & 255; i1 = S[i1 & 255] & 255; i2 = S[i2 & 255] & 255; i3 = S[i3 & 255] & 255; this.C1 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[r][1]; i0 = r2; i1 = r3 >>> 8; i2 = r0 >>> 16; i3 = r1 >>> 24; i0 = S[i0 & 255] & 255; i1 = S[i1 & 255] & 255; i2 = S[i2 & 255] & 255; i3 = S[i3 & 255] & 255; this.C2 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[r][2]; i0 = r3; i1 = r0 >>> 8; i2 = r1 >>> 16; i3 = r2 >>> 24; i0 = S[i0 & 255] & 255; i1 = S[i1 & 255] & 255; i2 = S[i2 & 255] & 255; i3 = S[i3 & 255] & 255; this.C3 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[r][3]; } private void decryptBlock(int[][] KW) { int t0 = this.C0 ^ KW[ROUNDS][0]; int t1 = this.C1 ^ KW[ROUNDS][1]; int t2 = this.C2 ^ KW[ROUNDS][2]; int r = ROUNDS - 1, r0, r1, r2, r3 = this.C3 ^ KW[ROUNDS][3]; int i0, i1, i2, i3; while (r > 1) { i0 = t0; i1 = r3 >>> 8; i2 = t2 >>> 16; i3 = t1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r0 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][0]; i0 = t1; i1 = t0 >>> 8; i2 = r3 >>> 16; i3 = t2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r1 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][1]; i0 = t2; i1 = t1 >>> 8; i2 = t0 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r2 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][2]; i0 = r3; i1 = t2 >>> 8; i2 = t1 >>> 16; i3 = t0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r--][3]; i0 = r0; i1 = r3 >>> 8; i2 = r2 >>> 16; i3 = r1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t0 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][0]; i0 = r1; i1 = r0 >>> 8; i2 = r3 >>> 16; i3 = r2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t1 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][1]; i0 = r2; i1 = r1 >>> 8; i2 = r0 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; t2 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r][2]; i0 = r3; i1 = r2 >>> 8; i2 = r1 >>> 16; i3 = r0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[r--][3]; } i0 = t0; i1 = r3 >>> 8; i2 = t2 >>> 16; i3 = t1 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r0 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[1][0]; i0 = t1; i1 = t0 >>> 8; i2 = r3 >>> 16; i3 = t2 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r1 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[1][1]; i0 = t2; i1 = t1 >>> 8; i2 = t0 >>> 16; i3 = r3 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r2 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[1][2]; i0 = r3; i1 = t2 >>> 8; i2 = t1 >>> 16; i3 = t0 >>> 24; i0 &= 255; i1 &= 255; i2 &= 255; i3 &= 255; r3 = Tinv[i0] ^ Tinv[256 + i1] ^ Tinv[512 + i2] ^ Tinv[768 + i3] ^ KW[1][3]; // the final round's table is a simple function of Si so we don't use a whole other four tables for it i0 = r0; i1 = r3 >>> 8; i2 = r2 >>> 16; i3 = r1 >>> 24; i0 = Si[i0 & 255] & 255; i1 = Si[i1 & 255] & 255; i2 = Si[i2 & 255] & 255; i3 = Si[i3 & 255] & 255; this.C0 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[0][0]; i0 = r1; i1 = r0 >>> 8; i2 = r3 >>> 16; i3 = r2 >>> 24; i0 = Si[i0 & 255] & 255; i1 = Si[i1 & 255] & 255; i2 = Si[i2 & 255] & 255; i3 = Si[i3 & 255] & 255; this.C1 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[0][1]; i0 = r2; i1 = r1 >>> 8; i2 = r0 >>> 16; i3 = r3 >>> 24; i0 = Si[i0 & 255] & 255; i1 = Si[i1 & 255] & 255; i2 = Si[i2 & 255] & 255; i3 = Si[i3 & 255] & 255; this.C2 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[0][2]; i0 = r3; i1 = r2 >>> 8; i2 = r1 >>> 16; i3 = r0 >>> 24; i0 = Si[i0 & 255] & 255; i1 = Si[i1 & 255] & 255; i2 = Si[i2 & 255] & 255; i3 = Si[i3 & 255] & 255; this.C3 = i0 ^ i1 << 8 ^ i2 << 16 ^ i3 << 24 ^ KW[0][3]; } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4756_0
crossvul-java_data_good_4755_5
package org.bouncycastle.jcajce.provider.asymmetric.util; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPrivateKeyParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.jcajce.provider.asymmetric.dh.BCDHPublicKey; /** * utility class for converting jce/jca DH objects * objects into their org.bouncycastle.crypto counterparts. */ public class DHUtil { static public AsymmetricKeyParameter generatePublicKeyParameter( PublicKey key) throws InvalidKeyException { if (key instanceof BCDHPublicKey) { return ((BCDHPublicKey)key).engineGetKeyParameters(); } if (key instanceof DHPublicKey) { DHPublicKey k = (DHPublicKey)key; return new DHPublicKeyParameters(k.getY(), new DHParameters(k.getParams().getP(), k.getParams().getG(), null, k.getParams().getL())); } throw new InvalidKeyException("can't identify DH public key."); } static public AsymmetricKeyParameter generatePrivateKeyParameter( PrivateKey key) throws InvalidKeyException { if (key instanceof DHPrivateKey) { DHPrivateKey k = (DHPrivateKey)key; return new DHPrivateKeyParameters(k.getX(), new DHParameters(k.getParams().getP(), k.getParams().getG(), null, k.getParams().getL())); } throw new InvalidKeyException("can't identify DH private key."); } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4755_5
crossvul-java_data_good_4755_2
package org.bouncycastle.jcajce.provider.asymmetric.dh; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import javax.crypto.spec.DHPublicKeySpec; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.pkcs.DHParameter; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.DomainParameters; import org.bouncycastle.asn1.x9.ValidationParams; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.crypto.params.DHValidationParameters; import org.bouncycastle.jcajce.provider.asymmetric.util.KeyUtil; public class BCDHPublicKey implements DHPublicKey { static final long serialVersionUID = -216691575254424324L; private BigInteger y; private transient DHPublicKeyParameters dhPublicKey; private transient DHParameterSpec dhSpec; private transient SubjectPublicKeyInfo info; BCDHPublicKey( DHPublicKeySpec spec) { this.y = spec.getY(); this.dhSpec = new DHParameterSpec(spec.getP(), spec.getG()); this.dhPublicKey = new DHPublicKeyParameters(y, new DHParameters(spec.getP(), spec.getG())); } BCDHPublicKey( DHPublicKey key) { this.y = key.getY(); this.dhSpec = key.getParams(); this.dhPublicKey = new DHPublicKeyParameters(y, new DHParameters(dhSpec.getP(), dhSpec.getG())); } BCDHPublicKey( DHPublicKeyParameters params) { this.y = params.getY(); this.dhSpec = new DHParameterSpec(params.getParameters().getP(), params.getParameters().getG(), params.getParameters().getL()); this.dhPublicKey = params; } BCDHPublicKey( BigInteger y, DHParameterSpec dhSpec) { this.y = y; this.dhSpec = dhSpec; this.dhPublicKey = new DHPublicKeyParameters(y, new DHParameters(dhSpec.getP(), dhSpec.getG())); } public BCDHPublicKey( SubjectPublicKeyInfo info) { this.info = info; ASN1Integer derY; try { derY = (ASN1Integer)info.parsePublicKey(); } catch (IOException e) { throw new IllegalArgumentException("invalid info structure in DH public key"); } this.y = derY.getValue(); ASN1Sequence seq = ASN1Sequence.getInstance(info.getAlgorithm().getParameters()); ASN1ObjectIdentifier id = info.getAlgorithm().getAlgorithm(); // we need the PKCS check to handle older keys marked with the X9 oid. if (id.equals(PKCSObjectIdentifiers.dhKeyAgreement) || isPKCSParam(seq)) { DHParameter params = DHParameter.getInstance(seq); if (params.getL() != null) { this.dhSpec = new DHParameterSpec(params.getP(), params.getG(), params.getL().intValue()); } else { this.dhSpec = new DHParameterSpec(params.getP(), params.getG()); } this.dhPublicKey = new DHPublicKeyParameters(y, new DHParameters(dhSpec.getP(), dhSpec.getG())); } else if (id.equals(X9ObjectIdentifiers.dhpublicnumber)) { DomainParameters params = DomainParameters.getInstance(seq); this.dhSpec = new DHParameterSpec(params.getP(), params.getG()); ValidationParams validationParams = params.getValidationParams(); if (validationParams != null) { this.dhPublicKey = new DHPublicKeyParameters(y, new DHParameters(params.getP(), params.getG(), params.getQ(), params.getJ(), new DHValidationParameters(validationParams.getSeed(), validationParams.getPgenCounter().intValue()))); } else { this.dhPublicKey = new DHPublicKeyParameters(y, new DHParameters(params.getP(), params.getG(), params.getQ(), params.getJ(), null)); } } else { throw new IllegalArgumentException("unknown algorithm type: " + id); } } public String getAlgorithm() { return "DH"; } public String getFormat() { return "X.509"; } public byte[] getEncoded() { if (info != null) { return KeyUtil.getEncodedSubjectPublicKeyInfo(info); } return KeyUtil.getEncodedSubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.dhKeyAgreement, new DHParameter(dhSpec.getP(), dhSpec.getG(), dhSpec.getL()).toASN1Primitive()), new ASN1Integer(y)); } public DHParameterSpec getParams() { return dhSpec; } public BigInteger getY() { return y; } public DHPublicKeyParameters engineGetKeyParameters() { return dhPublicKey; } private boolean isPKCSParam(ASN1Sequence seq) { if (seq.size() == 2) { return true; } if (seq.size() > 3) { return false; } ASN1Integer l = ASN1Integer.getInstance(seq.getObjectAt(2)); ASN1Integer p = ASN1Integer.getInstance(seq.getObjectAt(0)); if (l.getValue().compareTo(BigInteger.valueOf(p.getValue().bitLength())) > 0) { return false; } return true; } public int hashCode() { return this.getY().hashCode() ^ this.getParams().getG().hashCode() ^ this.getParams().getP().hashCode() ^ this.getParams().getL(); } public boolean equals( Object o) { if (!(o instanceof DHPublicKey)) { return false; } DHPublicKey other = (DHPublicKey)o; return this.getY().equals(other.getY()) && this.getParams().getG().equals(other.getParams().getG()) && this.getParams().getP().equals(other.getParams().getP()) && this.getParams().getL() == other.getParams().getL(); } private void readObject( ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.dhSpec = new DHParameterSpec((BigInteger)in.readObject(), (BigInteger)in.readObject(), in.readInt()); this.info = null; } private void writeObject( ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(dhSpec.getP()); out.writeObject(dhSpec.getG()); out.writeInt(dhSpec.getL()); } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4755_2
crossvul-java_data_good_2093_1
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Romain Seguy * * 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.model; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.DataBoundConstructor; import hudson.Extension; import hudson.util.Secret; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.DoNotUse; /** * Parameter whose value is a {@link Secret} and is hidden from the UI. * * @author Kohsuke Kawaguchi * @since 1.319 */ public class PasswordParameterDefinition extends SimpleParameterDefinition { private Secret defaultValue; @DataBoundConstructor public PasswordParameterDefinition(String name, String defaultValue, String description) { super(name, description); this.defaultValue = Secret.fromString(defaultValue); } @Override public ParameterDefinition copyWithDefaultValue(ParameterValue defaultValue) { if (defaultValue instanceof PasswordParameterValue) { PasswordParameterValue value = (PasswordParameterValue) defaultValue; return new PasswordParameterDefinition(getName(), Secret.toString(value.getValue()), getDescription()); } else { return this; } } @Override public ParameterValue createValue(String value) { return new PasswordParameterValue(getName(), value, getDescription()); } @Override public PasswordParameterValue createValue(StaplerRequest req, JSONObject jo) { PasswordParameterValue value = req.bindJSON(PasswordParameterValue.class, jo); value.setDescription(getDescription()); return value; } @Override public ParameterValue getDefaultParameterValue() { return new PasswordParameterValue(getName(), getDefaultValue(), getDescription()); } public String getDefaultValue() { return Secret.toString(defaultValue); } @Restricted(DoNotUse.class) // used from Jelly public Secret getDefaultValueAsSecret() { return defaultValue; } // kept for backward compatibility public void setDefaultValue(String defaultValue) { this.defaultValue = Secret.fromString(defaultValue); } @Extension public final static class ParameterDescriptorImpl extends ParameterDescriptor { @Override public String getDisplayName() { return Messages.PasswordParameterDefinition_DisplayName(); } @Override public String getHelpFile() { return "/help/parameter/string.html"; } } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_2093_1
crossvul-java_data_bad_4755_5
package org.bouncycastle.jcajce.provider.asymmetric.util; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPrivateKeyParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; /** * utility class for converting jce/jca DH objects * objects into their org.bouncycastle.crypto counterparts. */ public class DHUtil { static public AsymmetricKeyParameter generatePublicKeyParameter( PublicKey key) throws InvalidKeyException { if (key instanceof DHPublicKey) { DHPublicKey k = (DHPublicKey)key; return new DHPublicKeyParameters(k.getY(), new DHParameters(k.getParams().getP(), k.getParams().getG(), null, k.getParams().getL())); } throw new InvalidKeyException("can't identify DH public key."); } static public AsymmetricKeyParameter generatePrivateKeyParameter( PrivateKey key) throws InvalidKeyException { if (key instanceof DHPrivateKey) { DHPrivateKey k = (DHPrivateKey)key; return new DHPrivateKeyParameters(k.getX(), new DHParameters(k.getParams().getP(), k.getParams().getG(), null, k.getParams().getL())); } throw new InvalidKeyException("can't identify DH private key."); } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4755_5
crossvul-java_data_good_44_2
/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.DocumentFactory; import org.dom4j.Namespace; import org.dom4j.QName; import java.util.*; /** * <p> * <code>QNameCache</code> caches instances of <code>QName</code> for reuse * both across documents and within documents. * * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a> * @version $Revision: 1.16 $ * */ public class QNameCache { /** Cache of {@link QName}instances with no namespace */ protected Map<String, QName> noNamespaceCache = Collections.synchronizedMap(new WeakHashMap<String, QName>()); /** * Cache of {@link Map}instances indexed by namespace which contain caches * of {@link QName}for each name */ protected Map<Namespace, Map<String, QName>> namespaceCache = Collections.synchronizedMap(new WeakHashMap<Namespace, Map<String, QName>>()); /** * The document factory associated with new QNames instances in this cache * or null if no instances should be associated by default */ private DocumentFactory documentFactory; public QNameCache() { } public QNameCache(DocumentFactory documentFactory) { this.documentFactory = documentFactory; } /** * Returns a list of all the QName instances currently used * * @return DOCUMENT ME! */ public List<QName> getQNames() { List<QName> answer = new ArrayList<QName>(); answer.addAll(noNamespaceCache.values()); for (Map<String, QName> map : namespaceCache.values()) { answer.addAll(map.values()); } return answer; } /** * DOCUMENT ME! * * @param name * DOCUMENT ME! * * @return the QName for the given name and no namepsace */ public QName get(String name) { QName answer = null; if (name != null) { answer = noNamespaceCache.get(name); } else { name = ""; } if (answer == null) { answer = createQName(name); answer.setDocumentFactory(documentFactory); noNamespaceCache.put(name, answer); } return answer; } /** * DOCUMENT ME! * * @param name * DOCUMENT ME! * @param namespace * DOCUMENT ME! * * @return the QName for the given local name and namepsace */ public QName get(String name, Namespace namespace) { Map<String, QName> cache = getNamespaceCache(namespace); QName answer = null; if (name != null) { answer = cache.get(name); } else { name = ""; } if (answer == null) { answer = createQName(name, namespace); answer.setDocumentFactory(documentFactory); cache.put(name, answer); } return answer; } /** * DOCUMENT ME! * * @param localName * DOCUMENT ME! * @param namespace * DOCUMENT ME! * @param qName * DOCUMENT ME! * * @return the QName for the given local name, qualified name and namepsace */ public QName get(String localName, Namespace namespace, String qName) { Map<String, QName> cache = getNamespaceCache(namespace); QName answer = null; if (localName != null) { answer = cache.get(localName); } else { localName = ""; } if (answer == null) { answer = createQName(localName, namespace, qName); answer.setDocumentFactory(documentFactory); cache.put(localName, answer); } return answer; } public QName get(String qualifiedName, String uri) { int index = qualifiedName.indexOf(':'); if (index < 0) { return get(qualifiedName, Namespace.get(uri)); } else if (index == 0){ throw new IllegalArgumentException("Qualified name cannot start with ':'."); } else { String name = qualifiedName.substring(index + 1); String prefix = qualifiedName.substring(0, index); return get(name, Namespace.get(prefix, uri)); } } /** * DOCUMENT ME! * * @param qname * DOCUMENT ME! * * @return the cached QName instance if there is one or adds the given qname * to the cache if not */ public QName intern(QName qname) { return get(qname.getName(), qname.getNamespace(), qname .getQualifiedName()); } /** * DOCUMENT ME! * * @param namespace * DOCUMENT ME! * * @return the cache for the given namespace. If one does not currently * exist it is created. */ protected Map<String, QName> getNamespaceCache(Namespace namespace) { if (namespace == Namespace.NO_NAMESPACE) { return noNamespaceCache; } Map<String, QName> answer = null; if (namespace != null) { answer = namespaceCache.get(namespace); } if (answer == null) { answer = createMap(); namespaceCache.put(namespace, answer); } return answer; } /** * A factory method * * @return a newly created {@link Map}instance. */ protected Map<String, QName> createMap() { return Collections.synchronizedMap(new HashMap<String, QName>()); } /** * Factory method to create a new QName object which can be overloaded to * create derived QName instances * * @param name * DOCUMENT ME! * * @return DOCUMENT ME! */ protected QName createQName(String name) { return new QName(name); } /** * Factory method to create a new QName object which can be overloaded to * create derived QName instances * * @param name * DOCUMENT ME! * @param namespace * DOCUMENT ME! * * @return DOCUMENT ME! */ protected QName createQName(String name, Namespace namespace) { return new QName(name, namespace); } /** * Factory method to create a new QName object which can be overloaded to * create derived QName instances * * @param name * DOCUMENT ME! * @param namespace * DOCUMENT ME! * @param qualifiedName * DOCUMENT ME! * * @return DOCUMENT ME! */ protected QName createQName(String name, Namespace namespace, String qualifiedName) { return new QName(name, namespace, qualifiedName); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */
./CrossVul/dataset_final_sorted/CWE-91/java/good_44_2
crossvul-java_data_good_1130_3
/* ### * IP: GHIDRA * * 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 ghidra.bitpatterns.info; import java.math.BigInteger; import org.jdom.Element; /** * class for representing the values a specific context register assumes within a function body. */ public class ContextRegisterInfo { static final String XML_ELEMENT_NAME = "ContextRegisterInfo"; String contextRegister;//the context register BigInteger value;//the value it assumes /** * Default constructor (used by XMLEncoder) */ public ContextRegisterInfo() { } /** * Creates a {@link ContextRegisterInfo} object for a specified context register * @param contextRegister */ public ContextRegisterInfo(String contextRegister) { this.contextRegister = contextRegister; } /** * Returns the context register associated with this {@link ContextRegisterInfo} object * @return */ public String getContextRegister() { return contextRegister; } /** * Sets the context register associated with this {@link ContextRegisterInfo} object * @param contextRegister */ public void setContextRegister(String contextRegister) { this.contextRegister = contextRegister; } /** * Sets the value associated with this {@link ContextRegisterInfo} object * @param value */ public void setValue(BigInteger value) { this.value = value; } /** * Returns the value associated with this {@link ContextRegisterInfo} object as a * {@link String}. * @return */ public BigInteger getValue() { return value; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(contextRegister); sb.append(" "); sb.append(value); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ContextRegisterInfo other = (ContextRegisterInfo) obj; if (!contextRegister.equals(other.getContextRegister())) { return false; } if (value == null) { return (other.getValue() == null); } if (other.getValue() == null) { //in this case we know that value != null return false; } return value.equals(other.getValue()); } @Override public int hashCode() { int hashCode = 17; hashCode = 31 * hashCode + contextRegister.hashCode(); hashCode = 31 * hashCode + value.hashCode(); return hashCode; } /** * Creates a {@link ContextRegisterInfo} object using data in the supplied XML node. * * @param ele xml Element * @return new {@link ContextRegisterInfo} object, never null */ public static ContextRegisterInfo fromXml(Element ele) { String contextRegister = ele.getAttributeValue("contextRegister"); String value = ele.getAttributeValue("value"); ContextRegisterInfo result = new ContextRegisterInfo(); result.setContextRegister(contextRegister); result.setValue(value != null ? new BigInteger(value) : null); return result; } /** * Converts this object into XML * * @return new jdom Element */ public Element toXml() { Element e = new Element(XML_ELEMENT_NAME); e.setAttribute("contextRegister", contextRegister); if (value != null) { e.setAttribute("value", value.toString()); } return e; } }
./CrossVul/dataset_final_sorted/CWE-91/java/good_1130_3
crossvul-java_data_bad_44_1
/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.dom4j.tree.QNameCache; import org.dom4j.util.SingletonStrategy; /** * <code>QName</code> represents a qualified name value of an XML element or * attribute. It consists of a local name and a {@link Namespace}instance. This * object is immutable. * * @author <a href="mailto:jstrachan@apache.org">James Strachan </a> */ public class QName implements Serializable { /** The Singleton instance */ private static SingletonStrategy<QNameCache> singleton = null; static { try { String defaultSingletonClass = "org.dom4j.util.SimpleSingleton"; Class<SingletonStrategy> clazz = null; try { String singletonClass = defaultSingletonClass; singletonClass = System.getProperty( "org.dom4j.QName.singleton.strategy", singletonClass); clazz = (Class<SingletonStrategy>) Class.forName(singletonClass); } catch (Exception exc1) { try { String singletonClass = defaultSingletonClass; clazz = (Class<SingletonStrategy>) Class.forName(singletonClass); } catch (Exception exc2) { } } singleton = clazz.newInstance(); singleton.setSingletonClassName(QNameCache.class.getName()); } catch (Exception exc3) { } } /** The local name of the element or attribute */ private String name; /** The qualified name of the element or attribute */ private String qualifiedName; /** The Namespace of this element or attribute */ private transient Namespace namespace; /** A cached version of the hashcode for efficiency */ private int hashCode; /** The document factory used for this QName if specified or null */ private DocumentFactory documentFactory; public QName(String name) { this(name, Namespace.NO_NAMESPACE); } public QName(String name, Namespace namespace) { this.name = (name == null) ? "" : name; this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE : namespace; } public QName(String name, Namespace namespace, String qualifiedName) { this.name = (name == null) ? "" : name; this.qualifiedName = qualifiedName; this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE : namespace; } public static QName get(String name) { return getCache().get(name); } public static QName get(String name, Namespace namespace) { return getCache().get(name, namespace); } public static QName get(String name, String prefix, String uri) { if (((prefix == null) || (prefix.length() == 0)) && (uri == null)) { return QName.get(name); } else if ((prefix == null) || (prefix.length() == 0)) { return getCache().get(name, Namespace.get(uri)); } else if (uri == null) { return QName.get(name); } else { return getCache().get(name, Namespace.get(prefix, uri)); } } public static QName get(String qualifiedName, String uri) { if (uri == null) { return getCache().get(qualifiedName); } else { return getCache().get(qualifiedName, uri); } } public static QName get(String localName, Namespace namespace, String qualifiedName) { return getCache().get(localName, namespace, qualifiedName); } /** * DOCUMENT ME! * * @return the local name */ public String getName() { return name; } /** * DOCUMENT ME! * * @return the qualified name in the format <code>prefix:localName</code> */ public String getQualifiedName() { if (qualifiedName == null) { String prefix = getNamespacePrefix(); if ((prefix != null) && (prefix.length() > 0)) { qualifiedName = prefix + ":" + name; } else { qualifiedName = name; } } return qualifiedName; } /** * DOCUMENT ME! * * @return the namespace of this QName */ public Namespace getNamespace() { return namespace; } /** * DOCUMENT ME! * * @return the namespace URI of this QName */ public String getNamespacePrefix() { if (namespace == null) { return ""; } return namespace.getPrefix(); } /** * DOCUMENT ME! * * @return the namespace URI of this QName */ public String getNamespaceURI() { if (namespace == null) { return ""; } return namespace.getURI(); } /** * DOCUMENT ME! * * @return the hash code based on the qualified name and the URI of the * namespace. */ public int hashCode() { if (hashCode == 0) { hashCode = getName().hashCode() ^ getNamespaceURI().hashCode(); if (hashCode == 0) { hashCode = 0xbabe; } } return hashCode; } public boolean equals(Object object) { if (this == object) { return true; } else if (object instanceof QName) { QName that = (QName) object; // we cache hash codes so this should be quick if (hashCode() == that.hashCode()) { return getName().equals(that.getName()) && getNamespaceURI().equals(that.getNamespaceURI()); } } return false; } public String toString() { return super.toString() + " [name: " + getName() + " namespace: \"" + getNamespace() + "\"]"; } /** * DOCUMENT ME! * * @return the factory that should be used for Elements of this QName */ public DocumentFactory getDocumentFactory() { return documentFactory; } public void setDocumentFactory(DocumentFactory documentFactory) { this.documentFactory = documentFactory; } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); // We use writeObject() and not writeUTF() to minimize space // This allows for writing pointers to already written strings out.writeObject(namespace.getPrefix()); out.writeObject(namespace.getURI()); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); String prefix = (String) in.readObject(); String uri = (String) in.readObject(); namespace = Namespace.get(prefix, uri); } private static QNameCache getCache() { QNameCache cache = singleton.instance(); return cache; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */
./CrossVul/dataset_final_sorted/CWE-91/java/bad_44_1
crossvul-java_data_bad_1130_4
/* ### * IP: GHIDRA * * 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 ghidra.bitpatterns.info; import java.util.ArrayList; import java.util.List; /** * An object of this class stores all the function bit pattern information for an executable. * It records the number of bytes and instructions for each category (first, pre, and return), as * well as the language ID and ghidraURL of the executable. Using JAXB, objects of this class converted * to/from XML files for analysis and storage. */ public class FileBitPatternInfo { private int numFirstBytes = 0; private int numFirstInstructions = 0; private int numPreBytes = 0; private int numPreInstructions = 0; private int numReturnBytes = 0; private int numReturnInstructions = 0; private String languageID = null; private String ghidraURL = null; private List<FunctionBitPatternInfo> funcBitPatternInfo; //possible TODO: Use SaveState instead of JAXB to do the XML serialization? /** * Default no-arg constructor. Used by JAXB for XML serialization. */ public FileBitPatternInfo() { funcBitPatternInfo = new ArrayList<FunctionBitPatternInfo>(); } /** * Get the number of bytes gathered, starting at the entry point of a function. * @return number of first bytes */ public int getNumFirstBytes() { return numFirstBytes; } /** * Set the number of bytes gathered, starting at the entry point of a function * @param numFirstBytes number of bytes */ public void setNumFirstBytes(int numFirstBytes) { this.numFirstBytes = numFirstBytes; } /** * Get the number of instructions gathered, starting with instruction at the * entry point of the function * @return number of instructions */ public int getNumFirstInstructions() { return numFirstInstructions; } /** * Set the number of initial instructions gathered. * @param numFirstInstructions number of instructions */ public void setNumFirstInstructions(int numFirstInstructions) { this.numFirstInstructions = numFirstInstructions; } /** * Get the number of bytes gathered immediately before (but not including) the entry point * of a function * @return number of bytes gathered */ public int getNumPreBytes() { return numPreBytes; } /** * Set the number of bytes gathered immediately before (but not including) the entry point * of a function * @param numPreBytes number of bytes */ public void setNumPreBytes(int numPreBytes) { this.numPreBytes = numPreBytes; } /** * Get the number of instructions gathered immediately before (but not including) a function start * @return number of instructions */ public int getNumPreInstructions() { return numPreInstructions; } /** * Set the number of instructions gathered immediately before (but not including) a function start * * @param numPreInstructions number of instructions */ public void setNumPreInstructions(int numPreInstructions) { this.numPreInstructions = numPreInstructions; } /** * Get the list of {@link FunctionBitPatternInfo} objects for the program (one object per function) * @return List whose elements record information about each function start in the program */ public List<FunctionBitPatternInfo> getFuncBitPatternInfo() { return funcBitPatternInfo; } /** * Set the list of {@link FunctionBitPatternInfo} objects for the program (one object per function) * @param funcStartInfo List whose elements record information about each function start in the * program */ public void setFuncBitPatternInfo(List<FunctionBitPatternInfo> funcBitPatternInfo) { this.funcBitPatternInfo = funcBitPatternInfo; } /** * Get the language ID string of the program * @return the language ID */ public String getLanguageID() { return languageID; } /** * Set the language ID string of the program * @param id the language id */ public void setLanguageID(String id) { this.languageID = id; } /** * Set the GhidraURL of the program * @param url the url */ public void setGhidraURL(String url) { this.ghidraURL = url; } /** * Get the GhidraURL of the program * @return the url */ public String getGhidraURL() { return ghidraURL; } /** * Get the number of return bytes gathered, i.e., the number of bytes gathered immediately before * (and including) a return instruction. * @return number of return bytes */ public int getNumReturnBytes() { return numReturnBytes; } /** * Set the number of return bytes, i.e., the number of bytes gathered immediately before * (and including) a return instruction. * @param numReturnBytes number of return bytes */ public void setNumReturnBytes(int numReturnBytes) { this.numReturnBytes = numReturnBytes; } /** * Get the number of instructions immediately before (and including) a return instruction * @return number of return instructions */ public int getNumReturnInstructions() { return numReturnInstructions; } /** * Set the number of instructions immediately before (and including) a return instruction * @param numReturnInstructions number of return instructions */ public void setNumReturnInstructions(int numReturnInstructions) { this.numReturnInstructions = numReturnInstructions; } }
./CrossVul/dataset_final_sorted/CWE-91/java/bad_1130_4
crossvul-java_data_bad_44_3
404: Not Found
./CrossVul/dataset_final_sorted/CWE-91/java/bad_44_3
crossvul-java_data_bad_1130_2
/* ### * IP: GHIDRA * * 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 ghidra.bitpatterns.info; import java.math.BigInteger; import java.util.*; /** * Objects of this class are used to filter lists of {@link ContextRegisterInfo}s */ public class ContextRegisterFilter { private Set<String> contextRegisters;//the context registers under consideration private Map<String, BigInteger> values;//for each context register, the value the filter allows public ContextRegisterFilter() { contextRegisters = new HashSet<String>(); values = new HashMap<String, BigInteger>(); } /** * Add a pair (register,value) to the filter. * * @param contextRegister - the context register * @param value - the value the filter allows * @throws IllegalStateException if you add a value for a register that already has a value in the filter */ public void addRegAndValueToFilter(String contextRegister, BigInteger value) { if (contextRegisters.contains(contextRegister)) { throw new IllegalStateException("Filter can have only one value per register!"); } contextRegisters.add(contextRegister); values.put(contextRegister, value); } /** * Determines whether a list of {@link ContextRegisterInfo} objects passes the filter. * * @param contextRegisterInfos * @return {@code true} precisely when each {@link ContextRegisterInfo} in {@link ContextRegisterInfos} passes * the filter. */ public boolean allows(List<ContextRegisterInfo> contextRegisterInfos) { for (ContextRegisterInfo cInfo : contextRegisterInfos) { if (contextRegisters.contains(cInfo.getContextRegister())) { if (!values.get(cInfo.getContextRegister()).equals(cInfo.getValueAsBigInteger())) { return false; } } } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Context Register Filter: \n"); for (String cReg : contextRegisters) { sb.append(cReg); sb.append(": "); sb.append(values.get(cReg).toString()); sb.append("\n"); } sb.append("\n"); return sb.toString(); } /** * Returns a compact string representation of the filter for displaying in rows of a table * @return string representation */ public String getCompactString() { StringBuilder sb = new StringBuilder(); String[] registers = contextRegisters.toArray(new String[0]); for (int i = 0, max = registers.length; i < max; ++i) { sb.append(registers[i]); sb.append("="); sb.append(values.get(registers[i]).toString()); if (i < max - 1) { sb.append(";"); } } return sb.toString(); } @Override public int hashCode() { int hash = 17; hash = 31 * hash + contextRegisters.hashCode(); hash = 31 * hash + values.hashCode(); return hash; } @Override public boolean equals(Object o) { if (!(o instanceof ContextRegisterFilter)) { return false; } ContextRegisterFilter otherFilter = (ContextRegisterFilter) o; if (!otherFilter.contextRegisters.equals(contextRegisters)) { return false; } if (!otherFilter.values.equals(values)) { return false; } return true; } /** * Get the filter map * @return the map */ public Map<String, BigInteger> getValueMap() { return values; } }
./CrossVul/dataset_final_sorted/CWE-91/java/bad_1130_2
crossvul-java_data_good_1130_2
/* ### * IP: GHIDRA * * 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 ghidra.bitpatterns.info; import java.math.BigInteger; import java.util.*; /** * Objects of this class are used to filter lists of {@link ContextRegisterInfo}s */ public class ContextRegisterFilter { private Set<String> contextRegisters;//the context registers under consideration private Map<String, BigInteger> values;//for each context register, the value the filter allows public ContextRegisterFilter() { contextRegisters = new HashSet<String>(); values = new HashMap<String, BigInteger>(); } /** * Add a pair (register,value) to the filter. * * @param contextRegister - the context register * @param value - the value the filter allows * @throws IllegalStateException if you add a value for a register that already has a value in the filter */ public void addRegAndValueToFilter(String contextRegister, BigInteger value) { if (contextRegisters.contains(contextRegister)) { throw new IllegalStateException("Filter can have only one value per register!"); } contextRegisters.add(contextRegister); values.put(contextRegister, value); } /** * Determines whether a list of {@link ContextRegisterInfo} objects passes the filter. * * @param contextRegisterInfos * @return {@code true} precisely when each {@link ContextRegisterInfo} in {@link ContextRegisterInfos} passes * the filter. */ public boolean allows(List<ContextRegisterInfo> contextRegisterInfos) { for (ContextRegisterInfo cInfo : contextRegisterInfos) { if (contextRegisters.contains(cInfo.getContextRegister())) { if (!values.get(cInfo.getContextRegister()).equals(cInfo.getValue())) { return false; } } } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Context Register Filter: \n"); for (String cReg : contextRegisters) { sb.append(cReg); sb.append(": "); sb.append(values.get(cReg).toString()); sb.append("\n"); } sb.append("\n"); return sb.toString(); } /** * Returns a compact string representation of the filter for displaying in rows of a table * @return string representation */ public String getCompactString() { StringBuilder sb = new StringBuilder(); String[] registers = contextRegisters.toArray(new String[0]); for (int i = 0, max = registers.length; i < max; ++i) { sb.append(registers[i]); sb.append("="); sb.append(values.get(registers[i]).toString()); if (i < max - 1) { sb.append(";"); } } return sb.toString(); } @Override public int hashCode() { int hash = 17; hash = 31 * hash + contextRegisters.hashCode(); hash = 31 * hash + values.hashCode(); return hash; } @Override public boolean equals(Object o) { if (!(o instanceof ContextRegisterFilter)) { return false; } ContextRegisterFilter otherFilter = (ContextRegisterFilter) o; if (!otherFilter.contextRegisters.equals(contextRegisters)) { return false; } if (!otherFilter.values.equals(values)) { return false; } return true; } /** * Get the filter map * @return the map */ public Map<String, BigInteger> getValueMap() { return values; } }
./CrossVul/dataset_final_sorted/CWE-91/java/good_1130_2
crossvul-java_data_bad_1130_3
/* ### * IP: GHIDRA * * 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 ghidra.bitpatterns.info; import java.math.BigInteger; /** * class for representing the values a specific context register assumes within a function body. */ public class ContextRegisterInfo { String contextRegister;//the context register String value;//the value it assumes (needed because a BigInteger will not serialize to xml) BigInteger valueAsBigInteger;//the value it assumes /** * Default constructor (used by XMLEncoder) */ public ContextRegisterInfo() { } /** * Creates a {@link ContextRegisterInfo} object for a specified context register * @param contextRegister */ public ContextRegisterInfo(String contextRegister) { this.contextRegister = contextRegister; } /** * Returns the context register associated with this {@link ContextRegisterInfo} object * @return */ public String getContextRegister() { return contextRegister; } /** * Sets the context register associated with this {@link ContextRegisterInfo} object * @param contextRegister */ public void setContextRegister(String contextRegister) { this.contextRegister = contextRegister; } /** * Returns the value associated with this {@link ContextRegisterInfo} object as a * {@link BigInteger}. * @return */ public BigInteger getValueAsBigInteger() { return valueAsBigInteger; } /** * Sets the value associated with this {@link ContextRegisterInfo} object * @param valueAsBigInteger */ public void setValue(BigInteger valueAsBigInteger) { this.valueAsBigInteger = valueAsBigInteger; this.value = valueAsBigInteger.toString(); } /** * Returns the value associated with this {@link ContextRegisterInfo} object as a * {@link String}. * @return */ public String getValue() { return value; } /** * Sets the value associated with this {@link ContextRegisterInfo} object * @param value */ public void setValue(String value) { this.value = value; this.valueAsBigInteger = new BigInteger(value); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(contextRegister); sb.append(" "); sb.append(value); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ContextRegisterInfo other = (ContextRegisterInfo) obj; if (!contextRegister.equals(other.getContextRegister())) { return false; } if (value == null) { return (other.getValue() == null); } if (other.getValue() == null) { //in this case we know that value != null return false; } return value.equals(other.getValue()); } @Override public int hashCode() { int hashCode = 17; hashCode = 31 * hashCode + contextRegister.hashCode(); hashCode = 31 * hashCode + value.hashCode(); return hashCode; } }
./CrossVul/dataset_final_sorted/CWE-91/java/bad_1130_3
crossvul-java_data_good_1130_0
/* ### * IP: GHIDRA * * 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. */ //This script dumps information about byte and instructions in neighborhoods around function starts //and returns to an XML file //@category FunctionStartPatterns import java.io.*; import java.util.List; import ghidra.app.script.GhidraScript; import ghidra.bitpatterns.info.*; import ghidra.program.model.address.AddressSetView; import ghidra.program.model.listing.Function; import ghidra.program.model.listing.FunctionIterator; import ghidra.util.Msg; /** * Example of command to run this script headlessly: * ./analyzeHeadless /local/ghidraProjects/nonShared/ arm -recursive -process -noanalysis -postScript DumpFunctionPatternInfo.java */ public class DumpFunctionPatternInfoScript extends GhidraScript { private static int totalFuncs = 0; private static int programsAnalyzed = 0; @Override protected void run() throws Exception { if (!isRunningHeadless()) { totalFuncs = 0; programsAnalyzed = 0; } int numFirstBytes = askInt("Number of first bytes", "bytes"); int numFirstInstructions = askInt("Number of first instructions", "instructions"); int numPreBytes = askInt("Number of pre bytes", "bytes"); int numPreInstructions = askInt("Number of pre instructions", "instructions"); int numReturnBytes = askInt("Number of return bytes", "bytes"); int numReturnInstructions = askInt("Number of return instructions", "instructions"); String saveDirName = askString("Directory to save results", "directory"); String contextRegsCSV = askString("Context register csv", "csv"); File saveDir = new File(saveDirName); if (!saveDir.isDirectory()) { Msg.info(this, "Invalid save directory: " + saveDirName); return; } List<String> contextRegisters = DataGatheringParams.getContextRegisterList(contextRegsCSV); programsAnalyzed++; if (currentProgram == null) { Msg.info(this, "null current program: try again with the -process option"); return; } if (currentProgram.getFunctionManager().getFunctionCount() == 0) { Msg.info(this, "No functions found in " + currentProgram.getName() + ", skipping."); return; } FunctionIterator fIter = currentProgram.getFunctionManager().getFunctions(true); DataGatheringParams params = new DataGatheringParams(); params.setNumPreBytes(numPreBytes); params.setNumFirstBytes(numFirstBytes); params.setNumReturnBytes(numReturnBytes); params.setNumPreInstructions(numPreInstructions); params.setNumFirstInstructions(numFirstInstructions); params.setNumReturnInstructions(numReturnInstructions); params.setContextRegisters(contextRegisters); FileBitPatternInfo funcPatternList = new FileBitPatternInfo(); funcPatternList.setLanguageID(currentProgram.getLanguageID().getIdAsString()); funcPatternList.setGhidraURL("TODO: url"); funcPatternList.setNumPreBytes(numPreBytes); funcPatternList.setNumPreInstructions(numPreInstructions); funcPatternList.setNumFirstBytes(numFirstBytes); funcPatternList.setNumFirstInstructions(numFirstInstructions); funcPatternList.setNumReturnBytes(numReturnBytes); funcPatternList.setNumReturnInstructions(numReturnInstructions); AddressSetView initialized = currentProgram.getMemory().getLoadedAndInitializedAddressSet(); while (fIter.hasNext()) { monitor.checkCanceled(); Function func = fIter.next(); if (func.isThunk()) { continue; } if (func.isExternal()) { continue; } if (!initialized.contains(func.getEntryPoint())) { continue; } if (currentProgram.getListing().getInstructionAt(func.getEntryPoint()) == null) { continue; } FunctionBitPatternInfo fStart = new FunctionBitPatternInfo(currentProgram, func, params); if (fStart.getFirstBytes() != null) { funcPatternList.getFuncBitPatternInfo().add(fStart); totalFuncs++; } } File savedFile = new File(saveDir.getAbsolutePath() + File.separator + currentProgram.getDomainFile().getPathname().replaceAll("/", "_") + "_" + currentProgram.getExecutableMD5() + "_funcInfo.xml"); funcPatternList.toXmlFile(savedFile); Msg.info(this, "Programs analyzed: " + programsAnalyzed + "; total functions: " + totalFuncs); } }
./CrossVul/dataset_final_sorted/CWE-91/java/good_1130_0
crossvul-java_data_bad_1130_5
/* ### * IP: GHIDRA * * 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 ghidra.bitpatterns.info; import java.awt.Component; import java.beans.XMLDecoder; import java.io.*; import java.util.*; import org.apache.commons.io.FileUtils; import ghidra.program.model.address.AddressSetView; import ghidra.program.model.listing.*; import ghidra.util.Msg; import ghidra.util.task.*; /** * An object of this class stores information about function starts (and returns) to analyze. * * <p> There are two possible sources for this information. The first is a directory containing * XML files produced by JAXB from FunctionBitPatternInfo objects. The second is a single program. */ public class FileBitPatternInfoReader { private List<FunctionBitPatternInfo> fInfoList; //list of all function starts and returns to analyze private List<Long> startingAddresses; //list of all the starting addresses of the functions private ContextRegisterExtent registerExtent;//information about all context register values seen in all the xml files private int numFuncs = 0;//number of function seen in all the xml files private int numFiles = 0;//number of xml files in the directory private DataGatheringParams params; /** * Gathers function start information from a program. * * @param program The program to mine. * @param params The parameters controlling how much information to gather. * @param parent parent component */ public FileBitPatternInfoReader(Program program, DataGatheringParams params, Component parent) { startingAddresses = new ArrayList<Long>(); fInfoList = new ArrayList<FunctionBitPatternInfo>(); registerExtent = new ContextRegisterExtent(); this.params = params; numFiles = 1; MineProgramTask mineTask = new MineProgramTask(program); new TaskLauncher(mineTask, parent); } /** * Gathers function start information from a directory of XML-serialized {@link FunctionBitPatternInfo} * objects * @param xmlDir directory containing the xml files * @param monitor */ public FileBitPatternInfoReader(File xmlDir, Component parent) { if (!xmlDir.isDirectory()) { throw new IllegalArgumentException(xmlDir.getName() + " is not a directory"); } startingAddresses = new ArrayList<Long>(); fInfoList = new ArrayList<FunctionBitPatternInfo>(); registerExtent = new ContextRegisterExtent(); File[] dataFiles = xmlDir.listFiles(); ReadDirectoryTask readTask = new ReadDirectoryTask(dataFiles); new TaskLauncher(readTask, parent); } /** * Constructor used for testing * @param xmlDir */ FileBitPatternInfoReader(File xmlDir) { if (!xmlDir.isDirectory()) { throw new IllegalArgumentException(xmlDir.getName() + " is not a directory"); } startingAddresses = new ArrayList<Long>(); fInfoList = new ArrayList<FunctionBitPatternInfo>(); registerExtent = new ContextRegisterExtent(); params = null; Iterator<File> dataFiles = FileUtils.iterateFiles(xmlDir, null, false); while (dataFiles.hasNext()) { File dataFile = dataFiles.next(); processXmlFile(dataFile); } } private void processFBPIList(List<FunctionBitPatternInfo> fList) { for (FunctionBitPatternInfo fInfo : fList) { numFuncs++; fInfoList.add(fInfo); //record the starting address startingAddresses.add(Long.parseUnsignedLong(fInfo.getAddress(), 16)); //add the context register values to the context register extent registerExtent.addContextInfo(fInfo.getContextRegisters()); } } /** * Get the list of addresses of the functions * @return the addresses */ public List<Long> getStartingAddresses() { return startingAddresses; } /** * Get the total number of functions * @return number of functions */ public int getNumFuncs() { return numFuncs; } /** * Get the number of files examined * @return number of files */ public int getNumFiles() { return numFiles; } /** * Get the information gathered about context registers * @return context register information */ public ContextRegisterExtent getContextRegisterExtent() { return registerExtent; } /** * Get the list of {@link FunctionBitPatternInfo} objects, one object per function examined. * @return a list of the gathered information */ public List<FunctionBitPatternInfo> getFInfoList() { return fInfoList; } /** * Returns the list of starting addresses for functions which pass registerFilter * @param registerFilter - the context register filter * @return the list of functions passing the filter */ public List<Long> getFilteredAddresses(ContextRegisterFilter registerFilter) { List<Long> filteredAddresses = new ArrayList<Long>(); for (FunctionBitPatternInfo fInfo : fInfoList) { if (registerFilter.allows(fInfo.getContextRegisters())) { filteredAddresses.add(Long.parseUnsignedLong(fInfo.getAddress(), 16)); } } return filteredAddresses; } /** * Get the parameters used to gather this information * @return the data gathering paramaters */ public DataGatheringParams getDataGatheringParams() { return params; } private void processXmlFile(File dataFile) { if (!dataFile.getName().endsWith(".xml")) { Msg.info(this, "Skipping " + dataFile.getName()); return; } numFiles++; FileBitPatternInfo fileInfo = null; try (XMLDecoder xmlDecoder = new XMLDecoder(new FileInputStream(dataFile))) { fileInfo = (FileBitPatternInfo) xmlDecoder.readObject(); } catch (ArrayIndexOutOfBoundsException e) { // Probably wrong type of XML file...skip } catch (IOException e) { Msg.error(this, "IOException", e); } if (fileInfo == null) { Msg.info(this, "null FileBitPatternInfo for " + dataFile); return; } if (fileInfo.getFuncBitPatternInfo() == null) { Msg.info(this, "fList.getFuncBitPatternInfoList null for " + dataFile); return; } if (params == null) { //TODO: this will set the params to the params of the first valid file //these should agree with the parameters for all of the files //warn user if they don't? params = new DataGatheringParams(); params.setNumFirstBytes(fileInfo.getNumFirstBytes()); params.setNumPreBytes(fileInfo.getNumPreBytes()); params.setNumReturnBytes(fileInfo.getNumReturnBytes()); params.setNumFirstInstructions(fileInfo.getNumFirstInstructions()); params.setNumPreInstructions(fileInfo.getNumPreInstructions()); params.setNumReturnInstructions(fileInfo.getNumReturnInstructions()); } processFBPIList(fileInfo.getFuncBitPatternInfo()); } /** * Task for mining a single program */ class MineProgramTask extends Task { private AddressSetView initialized; private FunctionIterator fIter; private List<FunctionBitPatternInfo> fList; private Program program; /** * Creates a {@link Task} for mining function bit pattern information from a given program * @param program source program */ public MineProgramTask(Program program) { super("Mining Program", true, true, true); this.program = program; initialized = program.getMemory().getLoadedAndInitializedAddressSet(); fIter = program.getFunctionManager().getFunctions(true); fList = new ArrayList<>(); } @Override public void run(TaskMonitor monitor) { monitor.setMaximum(program.getFunctionManager().getFunctionCount()); while (fIter.hasNext() && !monitor.isCancelled()) { monitor.incrementProgress(1); Function func = fIter.next(); if (func.isThunk()) { continue; } if (func.isExternal()) { continue; } if (!initialized.contains(func.getEntryPoint())) { continue; } if (program.getListing().getInstructionAt(func.getEntryPoint()) == null) { continue; } FunctionBitPatternInfo fStart = new FunctionBitPatternInfo(program, func, params); if (fStart.getFirstBytes() != null) { fList.add(fStart); } } processFBPIList(fList); } } /** * {@link Task} for processing an array of XML-serialized FileBitPatternInfo objects */ class ReadDirectoryTask extends Task { private File[] dataFiles; /** * Creates a Task for restoring an array of XML-serialized FileBitPatternInfo objects * @param dataFiles array file files * @param unmarshaller Unmarshaller for serialized xml */ public ReadDirectoryTask(File[] dataFiles) { super("Reading XML", true, true, true); this.dataFiles = dataFiles; } @Override public void run(TaskMonitor monitor) { monitor.setMaximum(dataFiles.length); params = null; for (File dataFile : dataFiles) { monitor.incrementProgress(1); processXmlFile(dataFile); } } } }
./CrossVul/dataset_final_sorted/CWE-91/java/bad_1130_5
crossvul-java_data_bad_44_0
/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import org.dom4j.tree.AbstractNode; import org.dom4j.tree.DefaultNamespace; import org.dom4j.tree.NamespaceCache; /** * <code>Namespace</code> is a Flyweight Namespace that can be shared amongst * nodes. * * @author <a href="mailto:jstrachan@apache.org">James Strachan </a> * @version $Revision: 1.22 $ */ public class Namespace extends AbstractNode { /** Cache of Namespace instances */ protected static final NamespaceCache CACHE = new NamespaceCache(); /** XML Namespace */ public static final Namespace XML_NAMESPACE = CACHE.get("xml", "http://www.w3.org/XML/1998/namespace"); /** No Namespace present */ public static final Namespace NO_NAMESPACE = CACHE.get("", ""); /** The prefix mapped to this namespace */ private String prefix; /** The URI for this namespace */ private String uri; /** A cached version of the hashcode for efficiency */ private int hashCode; /** * DOCUMENT ME! * * @param prefix * is the prefix for this namespace * @param uri * is the URI for this namespace */ public Namespace(String prefix, String uri) { this.prefix = (prefix != null) ? prefix : ""; this.uri = (uri != null) ? uri : ""; } /** * A helper method to return the Namespace instance for the given prefix and * URI * * @param prefix * DOCUMENT ME! * @param uri * DOCUMENT ME! * * @return an interned Namespace object */ public static Namespace get(String prefix, String uri) { return CACHE.get(prefix, uri); } /** * A helper method to return the Namespace instance for no prefix and the * URI * * @param uri * DOCUMENT ME! * * @return an interned Namespace object */ public static Namespace get(String uri) { return CACHE.get(uri); } public short getNodeType() { return NAMESPACE_NODE; } /** * DOCUMENT ME! * * @return the hash code based on the qualified name and the URI of the * namespace. */ public int hashCode() { if (hashCode == 0) { hashCode = createHashCode(); } return hashCode; } /** * Factory method to create the hashcode allowing derived classes to change * the behaviour * * @return DOCUMENT ME! */ protected int createHashCode() { int result = uri.hashCode() ^ prefix.hashCode(); if (result == 0) { result = 0xbabe; } return result; } /** * Checks whether this Namespace equals the given Namespace. Two Namespaces * are equals if their URI and prefix are equal. * * @param object * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean equals(Object object) { if (this == object) { return true; } else if (object instanceof Namespace) { Namespace that = (Namespace) object; // we cache hash codes so this should be quick if (hashCode() == that.hashCode()) { return uri.equals(that.getURI()) && prefix.equals(that.getPrefix()); } } return false; } public String getText() { return uri; } public String getStringValue() { return uri; } /** * DOCUMENT ME! * * @return the prefix for this <code>Namespace</code>. */ public String getPrefix() { return prefix; } /** * DOCUMENT ME! * * @return the URI for this <code>Namespace</code>. */ public String getURI() { return uri; } public String getXPathNameStep() { if ((prefix != null) && !"".equals(prefix)) { return "namespace::" + prefix; } return "namespace::*[name()='']"; } public String getPath(Element context) { StringBuffer path = new StringBuffer(10); Element parent = getParent(); if ((parent != null) && (parent != context)) { path.append(parent.getPath(context)); path.append('/'); } path.append(getXPathNameStep()); return path.toString(); } public String getUniquePath(Element context) { StringBuffer path = new StringBuffer(10); Element parent = getParent(); if ((parent != null) && (parent != context)) { path.append(parent.getUniquePath(context)); path.append('/'); } path.append(getXPathNameStep()); return path.toString(); } public String toString() { return super.toString() + " [Namespace: prefix " + getPrefix() + " mapped to URI \"" + getURI() + "\"]"; } public String asXML() { StringBuffer asxml = new StringBuffer(10); String pref = getPrefix(); if ((pref != null) && (pref.length() > 0)) { asxml.append("xmlns:"); asxml.append(pref); asxml.append("=\""); } else { asxml.append("xmlns=\""); } asxml.append(getURI()); asxml.append("\""); return asxml.toString(); } public void accept(Visitor visitor) { visitor.visit(this); } protected Node createXPathResult(Element parent) { return new DefaultNamespace(parent, getPrefix(), getURI()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */
./CrossVul/dataset_final_sorted/CWE-91/java/bad_44_0
crossvul-java_data_good_1130_5
/* ### * IP: GHIDRA * * 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 ghidra.bitpatterns.info; import java.awt.Component; import java.io.*; import java.util.*; import org.apache.commons.io.FileUtils; import ghidra.program.model.address.AddressSetView; import ghidra.program.model.listing.*; import ghidra.util.Msg; import ghidra.util.task.*; /** * An object of this class stores information about function starts (and returns) to analyze. * * <p> There are two possible sources for this information. The first is a directory containing * XML files produced by JAXB from FunctionBitPatternInfo objects. The second is a single program. */ public class FileBitPatternInfoReader { private List<FunctionBitPatternInfo> fInfoList; //list of all function starts and returns to analyze private List<Long> startingAddresses; //list of all the starting addresses of the functions private ContextRegisterExtent registerExtent;//information about all context register values seen in all the xml files private int numFuncs = 0;//number of function seen in all the xml files private int numFiles = 0;//number of xml files in the directory private DataGatheringParams params; /** * Gathers function start information from a program. * * @param program The program to mine. * @param params The parameters controlling how much information to gather. * @param parent parent component */ public FileBitPatternInfoReader(Program program, DataGatheringParams params, Component parent) { startingAddresses = new ArrayList<Long>(); fInfoList = new ArrayList<FunctionBitPatternInfo>(); registerExtent = new ContextRegisterExtent(); this.params = params; numFiles = 1; MineProgramTask mineTask = new MineProgramTask(program); new TaskLauncher(mineTask, parent); } /** * Gathers function start information from a directory of XML-serialized {@link FunctionBitPatternInfo} * objects * @param xmlDir directory containing the xml files * @param monitor */ public FileBitPatternInfoReader(File xmlDir, Component parent) { if (!xmlDir.isDirectory()) { throw new IllegalArgumentException(xmlDir.getName() + " is not a directory"); } startingAddresses = new ArrayList<Long>(); fInfoList = new ArrayList<FunctionBitPatternInfo>(); registerExtent = new ContextRegisterExtent(); File[] dataFiles = xmlDir.listFiles(); ReadDirectoryTask readTask = new ReadDirectoryTask(dataFiles); new TaskLauncher(readTask, parent); } /** * Constructor used for testing * @param xmlDir */ FileBitPatternInfoReader(File xmlDir) { if (!xmlDir.isDirectory()) { throw new IllegalArgumentException(xmlDir.getName() + " is not a directory"); } startingAddresses = new ArrayList<Long>(); fInfoList = new ArrayList<FunctionBitPatternInfo>(); registerExtent = new ContextRegisterExtent(); params = null; Iterator<File> dataFiles = FileUtils.iterateFiles(xmlDir, null, false); while (dataFiles.hasNext()) { File dataFile = dataFiles.next(); processXmlFile(dataFile); } } private void processFBPIList(List<FunctionBitPatternInfo> fList) { for (FunctionBitPatternInfo fInfo : fList) { numFuncs++; fInfoList.add(fInfo); //record the starting address startingAddresses.add(Long.parseUnsignedLong(fInfo.getAddress(), 16)); //add the context register values to the context register extent registerExtent.addContextInfo(fInfo.getContextRegisters()); } } /** * Get the list of addresses of the functions * @return the addresses */ public List<Long> getStartingAddresses() { return startingAddresses; } /** * Get the total number of functions * @return number of functions */ public int getNumFuncs() { return numFuncs; } /** * Get the number of files examined * @return number of files */ public int getNumFiles() { return numFiles; } /** * Get the information gathered about context registers * @return context register information */ public ContextRegisterExtent getContextRegisterExtent() { return registerExtent; } /** * Get the list of {@link FunctionBitPatternInfo} objects, one object per function examined. * @return a list of the gathered information */ public List<FunctionBitPatternInfo> getFInfoList() { return fInfoList; } /** * Returns the list of starting addresses for functions which pass registerFilter * @param registerFilter - the context register filter * @return the list of functions passing the filter */ public List<Long> getFilteredAddresses(ContextRegisterFilter registerFilter) { List<Long> filteredAddresses = new ArrayList<Long>(); for (FunctionBitPatternInfo fInfo : fInfoList) { if (registerFilter.allows(fInfo.getContextRegisters())) { filteredAddresses.add(Long.parseUnsignedLong(fInfo.getAddress(), 16)); } } return filteredAddresses; } /** * Get the parameters used to gather this information * @return the data gathering paramaters */ public DataGatheringParams getDataGatheringParams() { return params; } private void processXmlFile(File dataFile) { if (!dataFile.getName().endsWith(".xml")) { Msg.info(this, "Skipping " + dataFile.getName()); return; } numFiles++; FileBitPatternInfo fileInfo = null; try { fileInfo = FileBitPatternInfo.fromXmlFile(dataFile); } catch (IOException e) { Msg.error(this, "Error reading FileBitPatternInfo file " + dataFile, e); return; } if (fileInfo.getFuncBitPatternInfo() == null) { Msg.info(this, "fList.getFuncBitPatternInfoList null for " + dataFile); return; } if (params == null) { //TODO: this will set the params to the params of the first valid file //these should agree with the parameters for all of the files //warn user if they don't? params = new DataGatheringParams(); params.setNumFirstBytes(fileInfo.getNumFirstBytes()); params.setNumPreBytes(fileInfo.getNumPreBytes()); params.setNumReturnBytes(fileInfo.getNumReturnBytes()); params.setNumFirstInstructions(fileInfo.getNumFirstInstructions()); params.setNumPreInstructions(fileInfo.getNumPreInstructions()); params.setNumReturnInstructions(fileInfo.getNumReturnInstructions()); } processFBPIList(fileInfo.getFuncBitPatternInfo()); } /** * Task for mining a single program */ class MineProgramTask extends Task { private AddressSetView initialized; private FunctionIterator fIter; private List<FunctionBitPatternInfo> fList; private Program program; /** * Creates a {@link Task} for mining function bit pattern information from a given program * @param program source program */ public MineProgramTask(Program program) { super("Mining Program", true, true, true); this.program = program; initialized = program.getMemory().getLoadedAndInitializedAddressSet(); fIter = program.getFunctionManager().getFunctions(true); fList = new ArrayList<>(); } @Override public void run(TaskMonitor monitor) { monitor.setMaximum(program.getFunctionManager().getFunctionCount()); while (fIter.hasNext() && !monitor.isCancelled()) { monitor.incrementProgress(1); Function func = fIter.next(); if (func.isThunk()) { continue; } if (func.isExternal()) { continue; } if (!initialized.contains(func.getEntryPoint())) { continue; } if (program.getListing().getInstructionAt(func.getEntryPoint()) == null) { continue; } FunctionBitPatternInfo fStart = new FunctionBitPatternInfo(program, func, params); if (fStart.getFirstBytes() != null) { fList.add(fStart); } } processFBPIList(fList); } } /** * {@link Task} for processing an array of XML-serialized FileBitPatternInfo objects */ class ReadDirectoryTask extends Task { private File[] dataFiles; /** * Creates a Task for restoring an array of XML-serialized FileBitPatternInfo objects * @param dataFiles array file files * @param unmarshaller Unmarshaller for serialized xml */ public ReadDirectoryTask(File[] dataFiles) { super("Reading XML", true, true, true); this.dataFiles = dataFiles; } @Override public void run(TaskMonitor monitor) { monitor.setMaximum(dataFiles.length); params = null; for (File dataFile : dataFiles) { monitor.incrementProgress(1); processXmlFile(dataFile); } } } }
./CrossVul/dataset_final_sorted/CWE-91/java/good_1130_5
crossvul-java_data_bad_44_2
/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.tree; import org.dom4j.DocumentFactory; import org.dom4j.Namespace; import org.dom4j.QName; import java.util.*; /** * <p> * <code>QNameCache</code> caches instances of <code>QName</code> for reuse * both across documents and within documents. * * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a> * @version $Revision: 1.16 $ * */ public class QNameCache { /** Cache of {@link QName}instances with no namespace */ protected Map<String, QName> noNamespaceCache = Collections.synchronizedMap(new WeakHashMap<String, QName>()); /** * Cache of {@link Map}instances indexed by namespace which contain caches * of {@link QName}for each name */ protected Map<Namespace, Map<String, QName>> namespaceCache = Collections.synchronizedMap(new WeakHashMap<Namespace, Map<String, QName>>()); /** * The document factory associated with new QNames instances in this cache * or null if no instances should be associated by default */ private DocumentFactory documentFactory; public QNameCache() { } public QNameCache(DocumentFactory documentFactory) { this.documentFactory = documentFactory; } /** * Returns a list of all the QName instances currently used * * @return DOCUMENT ME! */ public List<QName> getQNames() { List<QName> answer = new ArrayList<QName>(); answer.addAll(noNamespaceCache.values()); for (Map<String, QName> map : namespaceCache.values()) { answer.addAll(map.values()); } return answer; } /** * DOCUMENT ME! * * @param name * DOCUMENT ME! * * @return the QName for the given name and no namepsace */ public QName get(String name) { QName answer = null; if (name != null) { answer = noNamespaceCache.get(name); } else { name = ""; } if (answer == null) { answer = createQName(name); answer.setDocumentFactory(documentFactory); noNamespaceCache.put(name, answer); } return answer; } /** * DOCUMENT ME! * * @param name * DOCUMENT ME! * @param namespace * DOCUMENT ME! * * @return the QName for the given local name and namepsace */ public QName get(String name, Namespace namespace) { Map<String, QName> cache = getNamespaceCache(namespace); QName answer = null; if (name != null) { answer = cache.get(name); } else { name = ""; } if (answer == null) { answer = createQName(name, namespace); answer.setDocumentFactory(documentFactory); cache.put(name, answer); } return answer; } /** * DOCUMENT ME! * * @param localName * DOCUMENT ME! * @param namespace * DOCUMENT ME! * @param qName * DOCUMENT ME! * * @return the QName for the given local name, qualified name and namepsace */ public QName get(String localName, Namespace namespace, String qName) { Map<String, QName> cache = getNamespaceCache(namespace); QName answer = null; if (localName != null) { answer = cache.get(localName); } else { localName = ""; } if (answer == null) { answer = createQName(localName, namespace, qName); answer.setDocumentFactory(documentFactory); cache.put(localName, answer); } return answer; } public QName get(String qualifiedName, String uri) { int index = qualifiedName.indexOf(':'); if (index < 0) { return get(qualifiedName, Namespace.get(uri)); } else { String name = qualifiedName.substring(index + 1); String prefix = qualifiedName.substring(0, index); return get(name, Namespace.get(prefix, uri)); } } /** * DOCUMENT ME! * * @param qname * DOCUMENT ME! * * @return the cached QName instance if there is one or adds the given qname * to the cache if not */ public QName intern(QName qname) { return get(qname.getName(), qname.getNamespace(), qname .getQualifiedName()); } /** * DOCUMENT ME! * * @param namespace * DOCUMENT ME! * * @return the cache for the given namespace. If one does not currently * exist it is created. */ protected Map<String, QName> getNamespaceCache(Namespace namespace) { if (namespace == Namespace.NO_NAMESPACE) { return noNamespaceCache; } Map<String, QName> answer = null; if (namespace != null) { answer = namespaceCache.get(namespace); } if (answer == null) { answer = createMap(); namespaceCache.put(namespace, answer); } return answer; } /** * A factory method * * @return a newly created {@link Map}instance. */ protected Map<String, QName> createMap() { return Collections.synchronizedMap(new HashMap<String, QName>()); } /** * Factory method to create a new QName object which can be overloaded to * create derived QName instances * * @param name * DOCUMENT ME! * * @return DOCUMENT ME! */ protected QName createQName(String name) { return new QName(name); } /** * Factory method to create a new QName object which can be overloaded to * create derived QName instances * * @param name * DOCUMENT ME! * @param namespace * DOCUMENT ME! * * @return DOCUMENT ME! */ protected QName createQName(String name, Namespace namespace) { return new QName(name, namespace); } /** * Factory method to create a new QName object which can be overloaded to * create derived QName instances * * @param name * DOCUMENT ME! * @param namespace * DOCUMENT ME! * @param qualifiedName * DOCUMENT ME! * * @return DOCUMENT ME! */ protected QName createQName(String name, Namespace namespace, String qualifiedName) { return new QName(name, namespace, qualifiedName); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */
./CrossVul/dataset_final_sorted/CWE-91/java/bad_44_2
crossvul-java_data_good_44_3
package org.dom4j; import org.testng.annotations.Test; /** * @author Filip Jirsák */ public class AllowedCharsTest { @Test public void localName() { QName.get("element"); QName.get(":element"); QName.get("elem:ent"); } @Test(expectedExceptions = IllegalArgumentException.class) public void localNameFail() { QName.get("!element"); } @Test public void qname() { QName.get("element", "http://example.com/namespace"); QName.get("ns:element", "http://example.com/namespace"); } @Test(expectedExceptions = IllegalArgumentException.class) public void qnameFail1() { QName.get("ns:elem:ent", "http://example.com/namespace"); } @Test(expectedExceptions = IllegalArgumentException.class) public void qnameFail2() { QName.get(":nselement", "http://example.com/namespace"); } @Test(expectedExceptions = IllegalArgumentException.class) public void createElementLT() { DocumentHelper.createElement("element<name"); } @Test(expectedExceptions = IllegalArgumentException.class) public void createElementGT() { DocumentHelper.createElement("element>name"); } @Test(expectedExceptions = IllegalArgumentException.class) public void createElementAmpersand() { DocumentHelper.createElement("element&name"); } @Test(expectedExceptions = IllegalArgumentException.class) public void addElement() { Element root = DocumentHelper.createElement("root"); root.addElement("element>name"); } @Test(expectedExceptions = IllegalArgumentException.class) public void addElementQualified() { Element root = DocumentHelper.createElement("root"); root.addElement("element>name", "http://example.com/namespace"); } @Test(expectedExceptions = IllegalArgumentException.class) public void addElementQualifiedPrefix() { Element root = DocumentHelper.createElement("root"); root.addElement("ns:element>name", "http://example.com/namespace"); } @Test(expectedExceptions = IllegalArgumentException.class) public void addElementPrefix() { Element root = DocumentHelper.createElement("root"); root.addElement("ns>:element", "http://example.com/namespace"); } //TODO It is illegal to create element or attribute with namespace prefix and empty namespace IRI. //See https://www.w3.org/TR/2006/REC-xml-names11-20060816/#scoping }
./CrossVul/dataset_final_sorted/CWE-91/java/good_44_3
crossvul-java_data_good_1130_1
/* ### * IP: GHIDRA * * 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 ghidra.bitpatterns.info; import java.math.BigInteger; import java.util.*; /** * A class for representing accumulated context register information. */ public class ContextRegisterExtent { private Set<String> contextRegisters;//names of the context registers private Map<String, Set<BigInteger>> regsToValues;//for each register, a list of values it can take /** * Create a empty {@link ContextRegisterExtent} */ public ContextRegisterExtent() { contextRegisters = new HashSet<String>(); regsToValues = new HashMap<String, Set<BigInteger>>(); } /** * Accumulates the information in each element of {@code contextRegisterInfo} into the extent. * @param contextRegisterInfo */ public void addContextInfo(List<ContextRegisterInfo> contextRegisterInfo) { if ((contextRegisterInfo == null) || (contextRegisterInfo.isEmpty())) { return; } for (ContextRegisterInfo cRegInfo : contextRegisterInfo) { addRegisterAndValue(cRegInfo.getContextRegister(), cRegInfo.getValue()); } } private void addRegisterAndValue(String register, BigInteger value) { if (!contextRegisters.contains(register)) { contextRegisters.add(register); Set<BigInteger> valueSet = new HashSet<BigInteger>(); regsToValues.put(register, valueSet); } regsToValues.get(register).add(value); } /** * Returns an alphabetized list of context registers. * @return the list */ public List<String> getContextRegisters() { List<String> contextRegisterList = new ArrayList<String>(contextRegisters.size()); contextRegisterList.addAll(contextRegisters); Collections.sort(contextRegisterList); return contextRegisterList; } /** * Returns a list of values the register takes in the extent. * @param register - the register to query against the extent * @return - a list of values (may be empty); */ public List<BigInteger> getValuesForRegister(String register) { List<BigInteger> valuesList = new ArrayList<BigInteger>(); Set<BigInteger> values = regsToValues.get(register); if ((register != null) && (values != null)) { valuesList.addAll(values); Collections.sort(valuesList); } return valuesList; } @Override public String toString() { if (getContextRegisters().isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); List<String> registers = getContextRegisters(); for (String register : registers) { sb.append("Register: "); sb.append(register); sb.append("\n"); sb.append("Values: "); List<BigInteger> values = getValuesForRegister(register); for (int i = 0; i < values.size(); ++i) { sb.append(values.get(i)); if (i != (values.size() - 1)) { sb.append(", "); } else { sb.append("\n\n"); } } } return sb.toString(); } }
./CrossVul/dataset_final_sorted/CWE-91/java/good_1130_1
crossvul-java_data_bad_1130_0
/* ### * IP: GHIDRA * * 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. */ //This script dumps information about byte and instructions in neighborhoods around function starts //and returns to an XML file //@category FunctionStartPatterns import java.beans.XMLEncoder; import java.io.*; import java.util.List; import ghidra.app.script.GhidraScript; import ghidra.bitpatterns.info.*; import ghidra.program.model.address.AddressSetView; import ghidra.program.model.listing.Function; import ghidra.program.model.listing.FunctionIterator; import ghidra.util.Msg; /** * Example of command to run this script headlessly: * ./analyzeHeadless /local/ghidraProjects/nonShared/ arm -recursive -process -noanalysis -postScript DumpFunctionPatternInfo.java */ public class DumpFunctionPatternInfoScript extends GhidraScript { private static int totalFuncs = 0; private static int programsAnalyzed = 0; @Override protected void run() throws Exception { if (!isRunningHeadless()) { totalFuncs = 0; programsAnalyzed = 0; } int numFirstBytes = askInt("Number of first bytes", "bytes"); int numFirstInstructions = askInt("Number of first instructions", "instructions"); int numPreBytes = askInt("Number of pre bytes", "bytes"); int numPreInstructions = askInt("Number of pre instructions", "instructions"); int numReturnBytes = askInt("Number of return bytes", "bytes"); int numReturnInstructions = askInt("Number of return instructions", "instructions"); String saveDirName = askString("Directory to save results", "directory"); String contextRegsCSV = askString("Context register csv", "csv"); File saveDir = new File(saveDirName); if (!saveDir.isDirectory()) { Msg.info(this, "Invalid save directory: " + saveDirName); return; } List<String> contextRegisters = DataGatheringParams.getContextRegisterList(contextRegsCSV); programsAnalyzed++; if (currentProgram == null) { Msg.info(this, "null current program: try again with the -process option"); return; } if (currentProgram.getFunctionManager().getFunctionCount() == 0) { Msg.info(this, "No functions found in " + currentProgram.getName() + ", skipping."); return; } FunctionIterator fIter = currentProgram.getFunctionManager().getFunctions(true); DataGatheringParams params = new DataGatheringParams(); params.setNumPreBytes(numPreBytes); params.setNumFirstBytes(numFirstBytes); params.setNumReturnBytes(numReturnBytes); params.setNumPreInstructions(numPreInstructions); params.setNumFirstInstructions(numFirstInstructions); params.setNumReturnInstructions(numReturnInstructions); params.setContextRegisters(contextRegisters); FileBitPatternInfo funcPatternList = new FileBitPatternInfo(); funcPatternList.setLanguageID(currentProgram.getLanguageID().getIdAsString()); funcPatternList.setGhidraURL("TODO: url"); funcPatternList.setNumPreBytes(numPreBytes); funcPatternList.setNumPreInstructions(numPreInstructions); funcPatternList.setNumFirstBytes(numFirstBytes); funcPatternList.setNumFirstInstructions(numFirstInstructions); funcPatternList.setNumReturnBytes(numReturnBytes); funcPatternList.setNumReturnInstructions(numReturnInstructions); AddressSetView initialized = currentProgram.getMemory().getLoadedAndInitializedAddressSet(); while (fIter.hasNext()) { monitor.checkCanceled(); Function func = fIter.next(); if (func.isThunk()) { continue; } if (func.isExternal()) { continue; } if (!initialized.contains(func.getEntryPoint())) { continue; } if (currentProgram.getListing().getInstructionAt(func.getEntryPoint()) == null) { continue; } FunctionBitPatternInfo fStart = new FunctionBitPatternInfo(currentProgram, func, params); if (fStart.getFirstBytes() != null) { funcPatternList.getFuncBitPatternInfo().add(fStart); totalFuncs++; } } File savedFile = new File(saveDir.getAbsolutePath() + File.separator + currentProgram.getDomainFile().getPathname().replaceAll("/", "_") + "_" + currentProgram.getExecutableMD5() + "_funcInfo.xml"); try (XMLEncoder xmlEncoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(savedFile)))) { xmlEncoder.writeObject(funcPatternList); } Msg.info(this, "Programs analyzed: " + programsAnalyzed + "; total functions: " + totalFuncs); } }
./CrossVul/dataset_final_sorted/CWE-91/java/bad_1130_0
crossvul-java_data_bad_1130_1
/* ### * IP: GHIDRA * * 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 ghidra.bitpatterns.info; import java.math.BigInteger; import java.util.*; /** * A class for representing accumulated context register information. */ public class ContextRegisterExtent { private Set<String> contextRegisters;//names of the context registers private Map<String, Set<BigInteger>> regsToValues;//for each register, a list of values it can take /** * Create a empty {@link ContextRegisterExtent} */ public ContextRegisterExtent() { contextRegisters = new HashSet<String>(); regsToValues = new HashMap<String, Set<BigInteger>>(); } /** * Accumulates the information in each element of {@code contextRegisterInfo} into the extent. * @param contextRegisterInfo */ public void addContextInfo(List<ContextRegisterInfo> contextRegisterInfo) { if ((contextRegisterInfo == null) || (contextRegisterInfo.isEmpty())) { return; } for (ContextRegisterInfo cRegInfo : contextRegisterInfo) { addRegisterAndValue(cRegInfo.getContextRegister(), cRegInfo.getValueAsBigInteger()); } } private void addRegisterAndValue(String register, BigInteger value) { if (!contextRegisters.contains(register)) { contextRegisters.add(register); Set<BigInteger> valueSet = new HashSet<BigInteger>(); regsToValues.put(register, valueSet); } regsToValues.get(register).add(value); } /** * Returns an alphabetized list of context registers. * @return the list */ public List<String> getContextRegisters() { List<String> contextRegisterList = new ArrayList<String>(contextRegisters.size()); contextRegisterList.addAll(contextRegisters); Collections.sort(contextRegisterList); return contextRegisterList; } /** * Returns a list of values the register takes in the extent. * @param register - the register to query against the extent * @return - a list of values (may be empty); */ public List<BigInteger> getValuesForRegister(String register) { List<BigInteger> valuesList = new ArrayList<BigInteger>(); Set<BigInteger> values = regsToValues.get(register); if ((register != null) && (values != null)) { valuesList.addAll(values); Collections.sort(valuesList); } return valuesList; } @Override public String toString() { if (getContextRegisters().isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); List<String> registers = getContextRegisters(); for (String register : registers) { sb.append("Register: "); sb.append(register); sb.append("\n"); sb.append("Values: "); List<BigInteger> values = getValuesForRegister(register); for (int i = 0; i < values.size(); ++i) { sb.append(values.get(i)); if (i != (values.size() - 1)) { sb.append(", "); } else { sb.append("\n\n"); } } } return sb.toString(); } }
./CrossVul/dataset_final_sorted/CWE-91/java/bad_1130_1
crossvul-java_data_good_1130_4
/* ### * IP: GHIDRA * * 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 ghidra.bitpatterns.info; import java.io.*; import java.util.ArrayList; import java.util.List; import org.jdom.*; import org.jdom.input.SAXBuilder; import ghidra.util.Msg; import ghidra.util.xml.XmlUtilities; /** * An object of this class stores all the function bit pattern information for an executable. * It records the number of bytes and instructions for each category (first, pre, and return), as * well as the language ID and ghidraURL of the executable. Using JAXB, objects of this class converted * to/from XML files for analysis and storage. */ public class FileBitPatternInfo { static final String XML_ELEMENT_NAME = "FileBitPatternInfo"; private int numFirstBytes = 0; private int numFirstInstructions = 0; private int numPreBytes = 0; private int numPreInstructions = 0; private int numReturnBytes = 0; private int numReturnInstructions = 0; private String languageID = null; private String ghidraURL = null; private List<FunctionBitPatternInfo> funcBitPatternInfo; //possible TODO: Use SaveState instead of JAXB to do the XML serialization? /** * Default no-arg constructor. Used by JAXB for XML serialization. */ public FileBitPatternInfo() { funcBitPatternInfo = new ArrayList<FunctionBitPatternInfo>(); } /** * Get the number of bytes gathered, starting at the entry point of a function. * @return number of first bytes */ public int getNumFirstBytes() { return numFirstBytes; } /** * Set the number of bytes gathered, starting at the entry point of a function * @param numFirstBytes number of bytes */ public void setNumFirstBytes(int numFirstBytes) { this.numFirstBytes = numFirstBytes; } /** * Get the number of instructions gathered, starting with instruction at the * entry point of the function * @return number of instructions */ public int getNumFirstInstructions() { return numFirstInstructions; } /** * Set the number of initial instructions gathered. * @param numFirstInstructions number of instructions */ public void setNumFirstInstructions(int numFirstInstructions) { this.numFirstInstructions = numFirstInstructions; } /** * Get the number of bytes gathered immediately before (but not including) the entry point * of a function * @return number of bytes gathered */ public int getNumPreBytes() { return numPreBytes; } /** * Set the number of bytes gathered immediately before (but not including) the entry point * of a function * @param numPreBytes number of bytes */ public void setNumPreBytes(int numPreBytes) { this.numPreBytes = numPreBytes; } /** * Get the number of instructions gathered immediately before (but not including) a function start * @return number of instructions */ public int getNumPreInstructions() { return numPreInstructions; } /** * Set the number of instructions gathered immediately before (but not including) a function start * * @param numPreInstructions number of instructions */ public void setNumPreInstructions(int numPreInstructions) { this.numPreInstructions = numPreInstructions; } /** * Get the list of {@link FunctionBitPatternInfo} objects for the program (one object per function) * @return List whose elements record information about each function start in the program */ public List<FunctionBitPatternInfo> getFuncBitPatternInfo() { return funcBitPatternInfo; } /** * Set the list of {@link FunctionBitPatternInfo} objects for the program (one object per function) * @param funcStartInfo List whose elements record information about each function start in the * program */ public void setFuncBitPatternInfo(List<FunctionBitPatternInfo> funcBitPatternInfo) { this.funcBitPatternInfo = funcBitPatternInfo; } /** * Get the language ID string of the program * @return the language ID */ public String getLanguageID() { return languageID; } /** * Set the language ID string of the program * @param id the language id */ public void setLanguageID(String id) { this.languageID = id; } /** * Set the GhidraURL of the program * @param url the url */ public void setGhidraURL(String url) { this.ghidraURL = url; } /** * Get the GhidraURL of the program * @return the url */ public String getGhidraURL() { return ghidraURL; } /** * Get the number of return bytes gathered, i.e., the number of bytes gathered immediately before * (and including) a return instruction. * @return number of return bytes */ public int getNumReturnBytes() { return numReturnBytes; } /** * Set the number of return bytes, i.e., the number of bytes gathered immediately before * (and including) a return instruction. * @param numReturnBytes number of return bytes */ public void setNumReturnBytes(int numReturnBytes) { this.numReturnBytes = numReturnBytes; } /** * Get the number of instructions immediately before (and including) a return instruction * @return number of return instructions */ public int getNumReturnInstructions() { return numReturnInstructions; } /** * Set the number of instructions immediately before (and including) a return instruction * @param numReturnInstructions number of return instructions */ public void setNumReturnInstructions(int numReturnInstructions) { this.numReturnInstructions = numReturnInstructions; } /** * Converts this object into XML * * @return new jdom {@link Element} */ public Element toXml() { Element result = new Element(XML_ELEMENT_NAME); XmlUtilities.setStringAttr(result, "ghidraURL", ghidraURL); XmlUtilities.setStringAttr(result, "languageID", languageID); XmlUtilities.setIntAttr(result, "numFirstBytes", numFirstBytes); XmlUtilities.setIntAttr(result, "numFirstInstructions", numFirstInstructions); XmlUtilities.setIntAttr(result, "numPreBytes", numPreBytes); XmlUtilities.setIntAttr(result, "numPreInstructions", numPreInstructions); XmlUtilities.setIntAttr(result, "numReturnBytes", numReturnBytes); XmlUtilities.setIntAttr(result, "numReturnInstructions", numReturnInstructions); Element funcBitPatternInfoListEle = new Element("funcBitPatternInfoList"); for (FunctionBitPatternInfo fbpi : funcBitPatternInfo) { funcBitPatternInfoListEle.addContent(fbpi.toXml()); } result.addContent(funcBitPatternInfoListEle); return result; } /** * Creates a {@link FileBitPatternInfo} instance from XML. * * @param e XML element to convert * @return new {@link FileBitPatternInfo}, never null * @throws IOException if file IO error or xml data problem */ public static FileBitPatternInfo fromXml(Element e) throws IOException { String ghidraURL = e.getAttributeValue("ghidraURL"); String languageID = e.getAttributeValue("languageID"); int numFirstBytes = XmlUtilities.parseInt(XmlUtilities.requireStringAttr(e, "numFirstBytes")); int numFirstInstructions = XmlUtilities.parseInt(XmlUtilities.requireStringAttr(e, "numFirstInstructions")); int numPreBytes = XmlUtilities.parseInt(XmlUtilities.requireStringAttr(e, "numPreBytes")); int numPreInstructions = XmlUtilities.parseInt(XmlUtilities.requireStringAttr(e, "numPreInstructions")); int numReturnBytes = XmlUtilities.parseInt(XmlUtilities.requireStringAttr(e, "numReturnBytes")); int numReturnInstructions = XmlUtilities.parseInt(XmlUtilities.requireStringAttr(e, "numReturnInstructions")); List<FunctionBitPatternInfo> funcBitPatternInfoList = new ArrayList<>(); Element funcBitPatternInfoListEle = e.getChild("funcBitPatternInfoList"); if (funcBitPatternInfoListEle != null) { for (Element childElement : XmlUtilities.getChildren(funcBitPatternInfoListEle, FunctionBitPatternInfo.XML_ELEMENT_NAME)) { funcBitPatternInfoList.add(FunctionBitPatternInfo.fromXml(childElement)); } } FileBitPatternInfo result = new FileBitPatternInfo(); result.setFuncBitPatternInfo(funcBitPatternInfoList); result.setGhidraURL(ghidraURL); result.setLanguageID(languageID); result.setNumFirstBytes(numFirstBytes); result.setNumFirstInstructions(numFirstInstructions); result.setNumPreBytes(numPreBytes); result.setNumPreInstructions(numPreInstructions); result.setNumReturnBytes(numReturnBytes); result.setNumReturnInstructions(numReturnInstructions); return result; } /** * Converts this object to XML and writes it to the specified file. * * @param destFile name of xml file to create * @throws IOException if file io error */ public void toXmlFile(File destFile) throws IOException { Element rootEle = toXml(); Document doc = new Document(rootEle); XmlUtilities.writePrettyDocToFile(doc, destFile); } /** * Creates a {@link FileBitPatternInfo} instance from a XML file. * * @param inputFile name of xml file to read * @return new {@link FileBitPatternInfo} instance, never null * @throws IOException if file io error or xml data format problem */ public static FileBitPatternInfo fromXmlFile(File inputFile) throws IOException { SAXBuilder sax = XmlUtilities.createSecureSAXBuilder(false, false); try (InputStream fis = new FileInputStream(inputFile)) { Document doc = sax.build(fis); Element rootElem = doc.getRootElement(); return fromXml(rootElem); } catch (JDOMException | IOException e) { Msg.error(FileBitPatternInfo.class, "Bad file bit pattern file " + inputFile, e); throw new IOException("Failed to read file bit pattern " + inputFile, e); } } }
./CrossVul/dataset_final_sorted/CWE-91/java/good_1130_4
crossvul-java_data_good_44_1
/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.regex.Pattern; import org.dom4j.tree.QNameCache; import org.dom4j.util.SingletonStrategy; /** * <code>QName</code> represents a qualified name value of an XML element or * attribute. It consists of a local name and a {@link Namespace}instance. This * object is immutable. * * @author <a href="mailto:jstrachan@apache.org">James Strachan </a> * @author Filip Jirsák */ public class QName implements Serializable { /** The Singleton instance */ private static SingletonStrategy<QNameCache> singleton = null; /** * {@code NameStartChar} without colon. * * <pre>NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]</pre> * * @see <a href="https://www.w3.org/TR/xml/#sec-common-syn">XML 1.0 – 2.3 Common Syntactic Constructs</a> * @see <a href="https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-common-syn">XML 1.1 – 2.3 Common Syntactic Constructs</a> */ private static final String NAME_START_CHAR = "_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD"; /** * {@code NameChar} without colon. * * <pre>NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]</pre> * * @see <a href="https://www.w3.org/TR/xml/#sec-common-syn">XML 1.0 – 2.3 Common Syntactic Constructs</a> * @see <a href="https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-common-syn">XML 1.1 – 2.3 Common Syntactic Constructs</a> */ private static final String NAME_CHAR = NAME_START_CHAR + "-.0-9\u00B7\u0300-\u036F\u203F-\u2040"; /** * {@code NCName} * * <pre> * NCName ::= NCNameStartChar NCNameChar* (An XML Name, minus the ":") * NCNameChar ::= NameChar -':' * NCNameStartChar ::= NameStartChar -':' * </pre> * * @see <a href="https://www.w3.org/TR/xml-names/#ns-qualnames">Namespaces in XML 1.0 – 4 Qualified Names</a> * @see <a href="https://www.w3.org/TR/2006/REC-xml-names11-20060816/#ns-qualnames">Namespaces in XML 1.1 – 4 Qualified Names</a> */ private static final String NCNAME = "["+NAME_START_CHAR+"]["+NAME_CHAR+"]*"; /** * Regular expression for {@code Name} (with colon). * * <pre>Name ::= NameStartChar (NameChar)*</pre> * * @see <a href="https://www.w3.org/TR/xml/#sec-common-syn">XML 1.0 – 2.3 Common Syntactic Constructs</a> * @see <a href="https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-common-syn">XML 1.1 – 2.3 Common Syntactic Constructs</a> */ private static final Pattern RE_NAME = Pattern.compile("[:"+NAME_START_CHAR+"][:"+NAME_CHAR+"]*"); /** * Regular expression for {@code NCName}. * * <pre> * NCName ::= NCNameStartChar NCNameChar* (An XML Name, minus the ":") * NCNameChar ::= NameChar -':' * NCNameStartChar ::= NameStartChar -':' * </pre> * * @see <a href="https://www.w3.org/TR/xml-names/#ns-qualnames">Namespaces in XML 1.0 – 4 Qualified Names</a> * @see <a href="https://www.w3.org/TR/2006/REC-xml-names11-20060816/#ns-qualnames">Namespaces in XML 1.1 – 4 Qualified Names</a> */ private static final Pattern RE_NCNAME = Pattern.compile(NCNAME); /** * Regular expression for {@code QName}. * * <pre> * QName ::= PrefixedName | UnprefixedName * PrefixedName ::= Prefix ':' LocalPart * UnprefixedName ::= LocalPart * Prefix ::= NCName * LocalPart ::= NCName * </pre> * * @see <a href="https://www.w3.org/TR/xml-names/#ns-qualnames">Namespaces in XML 1.0 – 4 Qualified Names</a> * @see <a href="https://www.w3.org/TR/2006/REC-xml-names11-20060816/#ns-qualnames">Namespaces in XML 1.1 – 4 Qualified Names</a> */ private static final Pattern RE_QNAME = Pattern.compile("(?:"+NCNAME+":)?"+NCNAME); static { try { String defaultSingletonClass = "org.dom4j.util.SimpleSingleton"; Class<SingletonStrategy> clazz = null; try { String singletonClass = defaultSingletonClass; singletonClass = System.getProperty( "org.dom4j.QName.singleton.strategy", singletonClass); clazz = (Class<SingletonStrategy>) Class.forName(singletonClass); } catch (Exception exc1) { try { String singletonClass = defaultSingletonClass; clazz = (Class<SingletonStrategy>) Class.forName(singletonClass); } catch (Exception exc2) { } } singleton = clazz.newInstance(); singleton.setSingletonClassName(QNameCache.class.getName()); } catch (Exception exc3) { } } /** The local name of the element or attribute */ private String name; /** The qualified name of the element or attribute */ private String qualifiedName; /** The Namespace of this element or attribute */ private transient Namespace namespace; /** A cached version of the hashcode for efficiency */ private int hashCode; /** The document factory used for this QName if specified or null */ private DocumentFactory documentFactory; public QName(String name) { this(name, Namespace.NO_NAMESPACE); } public QName(String name, Namespace namespace) { this.name = (name == null) ? "" : name; this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE : namespace; if (this.namespace.equals(Namespace.NO_NAMESPACE)) { validateName(this.name); } else { validateNCName(this.name); } } public QName(String name, Namespace namespace, String qualifiedName) { this.name = (name == null) ? "" : name; this.qualifiedName = qualifiedName; this.namespace = (namespace == null) ? Namespace.NO_NAMESPACE : namespace; validateNCName(this.name); validateQName(this.qualifiedName); } public static QName get(String name) { return getCache().get(name); } public static QName get(String name, Namespace namespace) { return getCache().get(name, namespace); } public static QName get(String name, String prefix, String uri) { if (((prefix == null) || (prefix.length() == 0)) && (uri == null)) { return QName.get(name); } else if ((prefix == null) || (prefix.length() == 0)) { return getCache().get(name, Namespace.get(uri)); } else if (uri == null) { return QName.get(name); } else { return getCache().get(name, Namespace.get(prefix, uri)); } } public static QName get(String qualifiedName, String uri) { if (uri == null) { return getCache().get(qualifiedName); } else { return getCache().get(qualifiedName, uri); } } public static QName get(String localName, Namespace namespace, String qualifiedName) { return getCache().get(localName, namespace, qualifiedName); } /** * DOCUMENT ME! * * @return the local name */ public String getName() { return name; } /** * DOCUMENT ME! * * @return the qualified name in the format <code>prefix:localName</code> */ public String getQualifiedName() { if (qualifiedName == null) { String prefix = getNamespacePrefix(); if ((prefix != null) && (prefix.length() > 0)) { qualifiedName = prefix + ":" + name; } else { qualifiedName = name; } } return qualifiedName; } /** * DOCUMENT ME! * * @return the namespace of this QName */ public Namespace getNamespace() { return namespace; } /** * DOCUMENT ME! * * @return the namespace URI of this QName */ public String getNamespacePrefix() { if (namespace == null) { return ""; } return namespace.getPrefix(); } /** * DOCUMENT ME! * * @return the namespace URI of this QName */ public String getNamespaceURI() { if (namespace == null) { return ""; } return namespace.getURI(); } /** * DOCUMENT ME! * * @return the hash code based on the qualified name and the URI of the * namespace. */ public int hashCode() { if (hashCode == 0) { hashCode = getName().hashCode() ^ getNamespaceURI().hashCode(); if (hashCode == 0) { hashCode = 0xbabe; } } return hashCode; } public boolean equals(Object object) { if (this == object) { return true; } else if (object instanceof QName) { QName that = (QName) object; // we cache hash codes so this should be quick if (hashCode() == that.hashCode()) { return getName().equals(that.getName()) && getNamespaceURI().equals(that.getNamespaceURI()); } } return false; } public String toString() { return super.toString() + " [name: " + getName() + " namespace: \"" + getNamespace() + "\"]"; } /** * DOCUMENT ME! * * @return the factory that should be used for Elements of this QName */ public DocumentFactory getDocumentFactory() { return documentFactory; } public void setDocumentFactory(DocumentFactory documentFactory) { this.documentFactory = documentFactory; } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); // We use writeObject() and not writeUTF() to minimize space // This allows for writing pointers to already written strings out.writeObject(namespace.getPrefix()); out.writeObject(namespace.getURI()); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); String prefix = (String) in.readObject(); String uri = (String) in.readObject(); namespace = Namespace.get(prefix, uri); } private static QNameCache getCache() { QNameCache cache = singleton.instance(); return cache; } private static void validateName(String name) { if (!RE_NAME.matcher(name).matches()) { throw new IllegalArgumentException(String.format("Illegal character in name: '%s'.", name)); } } protected static void validateNCName(String ncname) { if (!RE_NCNAME.matcher(ncname).matches()) { throw new IllegalArgumentException(String.format("Illegal character in local name: '%s'.", ncname)); } } private static void validateQName(String qname) { if (!RE_QNAME.matcher(qname).matches()) { throw new IllegalArgumentException(String.format("Illegal character in qualified name: '%s'.", qname)); } } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */
./CrossVul/dataset_final_sorted/CWE-91/java/good_44_1
crossvul-java_data_good_44_0
/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import org.dom4j.tree.AbstractNode; import org.dom4j.tree.DefaultNamespace; import org.dom4j.tree.NamespaceCache; /** * <code>Namespace</code> is a Flyweight Namespace that can be shared amongst * nodes. * * @author <a href="mailto:jstrachan@apache.org">James Strachan </a> * @version $Revision: 1.22 $ */ public class Namespace extends AbstractNode { /** Cache of Namespace instances */ protected static final NamespaceCache CACHE = new NamespaceCache(); /** XML Namespace */ public static final Namespace XML_NAMESPACE = CACHE.get("xml", "http://www.w3.org/XML/1998/namespace"); /** No Namespace present */ public static final Namespace NO_NAMESPACE = CACHE.get("", ""); /** The prefix mapped to this namespace */ private String prefix; /** The URI for this namespace */ private String uri; /** A cached version of the hashcode for efficiency */ private int hashCode; /** * DOCUMENT ME! * * @param prefix * is the prefix for this namespace * @param uri * is the URI for this namespace */ public Namespace(String prefix, String uri) { this.prefix = (prefix != null) ? prefix : ""; this.uri = (uri != null) ? uri : ""; if (!this.prefix.isEmpty()) { QName.validateNCName(this.prefix); } } /** * A helper method to return the Namespace instance for the given prefix and * URI * * @param prefix * DOCUMENT ME! * @param uri * DOCUMENT ME! * * @return an interned Namespace object */ public static Namespace get(String prefix, String uri) { return CACHE.get(prefix, uri); } /** * A helper method to return the Namespace instance for no prefix and the * URI * * @param uri * DOCUMENT ME! * * @return an interned Namespace object */ public static Namespace get(String uri) { return CACHE.get(uri); } public short getNodeType() { return NAMESPACE_NODE; } /** * DOCUMENT ME! * * @return the hash code based on the qualified name and the URI of the * namespace. */ public int hashCode() { if (hashCode == 0) { hashCode = createHashCode(); } return hashCode; } /** * Factory method to create the hashcode allowing derived classes to change * the behaviour * * @return DOCUMENT ME! */ protected int createHashCode() { int result = uri.hashCode() ^ prefix.hashCode(); if (result == 0) { result = 0xbabe; } return result; } /** * Checks whether this Namespace equals the given Namespace. Two Namespaces * are equals if their URI and prefix are equal. * * @param object * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean equals(Object object) { if (this == object) { return true; } else if (object instanceof Namespace) { Namespace that = (Namespace) object; // we cache hash codes so this should be quick if (hashCode() == that.hashCode()) { return uri.equals(that.getURI()) && prefix.equals(that.getPrefix()); } } return false; } public String getText() { return uri; } public String getStringValue() { return uri; } /** * DOCUMENT ME! * * @return the prefix for this <code>Namespace</code>. */ public String getPrefix() { return prefix; } /** * DOCUMENT ME! * * @return the URI for this <code>Namespace</code>. */ public String getURI() { return uri; } public String getXPathNameStep() { if ((prefix != null) && !"".equals(prefix)) { return "namespace::" + prefix; } return "namespace::*[name()='']"; } public String getPath(Element context) { StringBuffer path = new StringBuffer(10); Element parent = getParent(); if ((parent != null) && (parent != context)) { path.append(parent.getPath(context)); path.append('/'); } path.append(getXPathNameStep()); return path.toString(); } public String getUniquePath(Element context) { StringBuffer path = new StringBuffer(10); Element parent = getParent(); if ((parent != null) && (parent != context)) { path.append(parent.getUniquePath(context)); path.append('/'); } path.append(getXPathNameStep()); return path.toString(); } public String toString() { return super.toString() + " [Namespace: prefix " + getPrefix() + " mapped to URI \"" + getURI() + "\"]"; } public String asXML() { StringBuffer asxml = new StringBuffer(10); String pref = getPrefix(); if ((pref != null) && (pref.length() > 0)) { asxml.append("xmlns:"); asxml.append(pref); asxml.append("=\""); } else { asxml.append("xmlns=\""); } asxml.append(getURI()); asxml.append("\""); return asxml.toString(); } public void accept(Visitor visitor) { visitor.visit(this); } protected Node createXPathResult(Element parent) { return new DefaultNamespace(parent, getPrefix(), getURI()); } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */
./CrossVul/dataset_final_sorted/CWE-91/java/good_44_0
crossvul-java_data_bad_3889_0
package com.eebbk.greenbrowser.util; import android.content.Intent; import android.net.Uri; import android.webkit.WebView; import android.webkit.WebViewClient; @SuppressWarnings("unused") class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url); if (uri.getHost() != null && uri.getHost().endsWith("example.com")) { return false; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); view.getContext().startActivity(intent); return true; } }
./CrossVul/dataset_final_sorted/CWE-862/java/bad_3889_0
crossvul-java_data_bad_4619_0
/* * Copyright (c) 2012 Google Inc. * * 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 com.google.api.client.auth.oauth2; import com.google.api.client.auth.oauth2.Credential.AccessMethod; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import com.google.api.client.util.Clock; import com.google.api.client.util.Joiner; import com.google.api.client.util.Lists; import com.google.api.client.util.Preconditions; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import java.io.IOException; import java.util.Collection; import java.util.Collections; import static com.google.api.client.util.Strings.isNullOrEmpty; /** * Thread-safe OAuth 2.0 authorization code flow that manages and persists end-user credentials. * * <p> * This is designed to simplify the flow in which an end-user authorizes the application to access * their protected data, and then the application has access to their data based on an access token * and a refresh token to refresh that access token when it expires. * </p> * * <p> * The first step is to call {@link #loadCredential(String)} based on the known user ID to check if * the end-user's credentials are already known. If not, call {@link #newAuthorizationUrl()} and * direct the end-user's browser to an authorization page. The web browser will then redirect to the * redirect URL with a {@code "code"} query parameter which can then be used to request an access * token using {@link #newTokenRequest(String)}. Finally, use * {@link #createAndStoreCredential(TokenResponse, String)} to store and obtain a credential for * accessing protected resources. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class AuthorizationCodeFlow { /** * Method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}). */ private final AccessMethod method; /** HTTP transport. */ private final HttpTransport transport; /** JSON factory. */ private final JsonFactory jsonFactory; /** Token server encoded URL. */ private final String tokenServerEncodedUrl; /** * Client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). */ private final HttpExecuteInterceptor clientAuthentication; /** Client identifier. */ private final String clientId; /** Authorization server encoded URL. */ private final String authorizationServerEncodedUrl; /** Credential persistence store or {@code null} for none. */ @Beta @Deprecated private final CredentialStore credentialStore; /** Stored credential data store or {@code null} for none. */ @Beta private final DataStore<StoredCredential> credentialDataStore; /** HTTP request initializer or {@code null} for none. */ private final HttpRequestInitializer requestInitializer; /** Clock passed along to Credential. */ private final Clock clock; /** Collection of scopes. */ private final Collection<String> scopes; /** Credential created listener or {@code null} for none. */ private final CredentialCreatedListener credentialCreatedListener; /** Refresh listeners provided by the client. */ private final Collection<CredentialRefreshListener> refreshListeners; /** * @param method method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}) * @param transport HTTP transport * @param jsonFactory JSON factory * @param tokenServerUrl token server URL * @param clientAuthentication client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}) * @param clientId client identifier * @param authorizationServerEncodedUrl authorization server encoded URL * * @since 1.14 */ public AuthorizationCodeFlow(AccessMethod method, HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl, HttpExecuteInterceptor clientAuthentication, String clientId, String authorizationServerEncodedUrl) { this(new Builder(method, transport, jsonFactory, tokenServerUrl, clientAuthentication, clientId, authorizationServerEncodedUrl)); } /** * @param builder authorization code flow builder * * @since 1.14 */ protected AuthorizationCodeFlow(Builder builder) { method = Preconditions.checkNotNull(builder.method); transport = Preconditions.checkNotNull(builder.transport); jsonFactory = Preconditions.checkNotNull(builder.jsonFactory); tokenServerEncodedUrl = Preconditions.checkNotNull(builder.tokenServerUrl).build(); clientAuthentication = builder.clientAuthentication; clientId = Preconditions.checkNotNull(builder.clientId); authorizationServerEncodedUrl = Preconditions.checkNotNull(builder.authorizationServerEncodedUrl); requestInitializer = builder.requestInitializer; credentialStore = builder.credentialStore; credentialDataStore = builder.credentialDataStore; scopes = Collections.unmodifiableCollection(builder.scopes); clock = Preconditions.checkNotNull(builder.clock); credentialCreatedListener = builder.credentialCreatedListener; refreshListeners = Collections.unmodifiableCollection(builder.refreshListeners); } /** * Returns a new instance of an authorization code request URL. * * <p> * This is a builder for an authorization web page to allow the end user to authorize the * application to access their protected resources and that returns an authorization code. It uses * the {@link #getAuthorizationServerEncodedUrl()}, {@link #getClientId()}, and * {@link #getScopes()}. Sample usage: * </p> * * <pre> private AuthorizationCodeFlow flow; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String url = flow.newAuthorizationUrl().setState("xyz") .setRedirectUri("https://client.example.com/rd").build(); response.sendRedirect(url); } * </pre> */ public AuthorizationCodeRequestUrl newAuthorizationUrl() { return new AuthorizationCodeRequestUrl(authorizationServerEncodedUrl, clientId).setScopes( scopes); } /** * Returns a new instance of an authorization code token request based on the given authorization * code. * * <p> * This is used to make a request for an access token using the authorization code. It uses * {@link #getTransport()}, {@link #getJsonFactory()}, {@link #getTokenServerEncodedUrl()}, * {@link #getClientAuthentication()}, {@link #getRequestInitializer()}, and {@link #getScopes()}. * </p> * * <pre> static TokenResponse requestAccessToken(AuthorizationCodeFlow flow, String code) throws IOException, TokenResponseException { return flow.newTokenRequest(code).setRedirectUri("https://client.example.com/rd").execute(); } * </pre> * * @param authorizationCode authorization code. */ public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) { return new AuthorizationCodeTokenRequest(transport, jsonFactory, new GenericUrl(tokenServerEncodedUrl), authorizationCode).setClientAuthentication( clientAuthentication).setRequestInitializer(requestInitializer).setScopes(scopes); } /** * Creates a new credential for the given user ID based on the given token response * and stores it in the credential store. * * @param response token response * @param userId user ID or {@code null} if not using a persisted credential store * @return newly created credential */ @SuppressWarnings("deprecation") public Credential createAndStoreCredential(TokenResponse response, String userId) throws IOException { Credential credential = newCredential(userId).setFromTokenResponse(response); if (credentialStore != null) { credentialStore.store(userId, credential); } if (credentialDataStore != null) { credentialDataStore.set(userId, new StoredCredential(credential)); } if (credentialCreatedListener != null) { credentialCreatedListener.onCredentialCreated(credential, response); } return credential; } /** * Loads the credential of the given user ID from the credential store. * * @param userId user ID or {@code null} if not using a persisted credential store * @return credential found in the credential store of the given user ID or {@code null} for none * found */ @SuppressWarnings("deprecation") public Credential loadCredential(String userId) throws IOException { // No requests need to be performed when userId is not specified. if (isNullOrEmpty(userId)) { return null; } if (credentialDataStore == null && credentialStore == null) { return null; } Credential credential = newCredential(userId); if (credentialDataStore != null) { StoredCredential stored = credentialDataStore.get(userId); if (stored == null) { return null; } credential.setAccessToken(stored.getAccessToken()); credential.setRefreshToken(stored.getRefreshToken()); credential.setExpirationTimeMilliseconds(stored.getExpirationTimeMilliseconds()); } else if (!credentialStore.load(userId, credential)) { return null; } return credential; } /** * Returns a new credential instance based on the given user ID. * * @param userId user ID or {@code null} if not using a persisted credential store */ @SuppressWarnings("deprecation") private Credential newCredential(String userId) { Credential.Builder builder = new Credential.Builder(method).setTransport(transport) .setJsonFactory(jsonFactory) .setTokenServerEncodedUrl(tokenServerEncodedUrl) .setClientAuthentication(clientAuthentication) .setRequestInitializer(requestInitializer) .setClock(clock); if (credentialDataStore != null) { builder.addRefreshListener( new DataStoreCredentialRefreshListener(userId, credentialDataStore)); } else if (credentialStore != null) { builder.addRefreshListener(new CredentialStoreRefreshListener(userId, credentialStore)); } builder.getRefreshListeners().addAll(refreshListeners); return builder.build(); } /** * Returns the method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}). */ public final AccessMethod getMethod() { return method; } /** Returns the HTTP transport. */ public final HttpTransport getTransport() { return transport; } /** Returns the JSON factory. */ public final JsonFactory getJsonFactory() { return jsonFactory; } /** Returns the token server encoded URL. */ public final String getTokenServerEncodedUrl() { return tokenServerEncodedUrl; } /** * Returns the client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). */ public final HttpExecuteInterceptor getClientAuthentication() { return clientAuthentication; } /** Returns the client identifier. */ public final String getClientId() { return clientId; } /** Returns the authorization server encoded URL. */ public final String getAuthorizationServerEncodedUrl() { return authorizationServerEncodedUrl; } /** * {@link Beta} <br/> * Returns the credential persistence store or {@code null} for none. * @deprecated (to be removed in the future) Use {@link #getCredentialDataStore()} instead. */ @Beta @Deprecated public final CredentialStore getCredentialStore() { return credentialStore; } /** * {@link Beta} <br/> * Returns the stored credential data store or {@code null} for none. * * @since 1.16 */ @Beta public final DataStore<StoredCredential> getCredentialDataStore() { return credentialDataStore; } /** Returns the HTTP request initializer or {@code null} for none. */ public final HttpRequestInitializer getRequestInitializer() { return requestInitializer; } /** * Returns the space-separated list of scopes. * * @since 1.15 */ public final String getScopesAsString() { return Joiner.on(' ').join(scopes); } /** Returns the a collection of scopes. */ public final Collection<String> getScopes() { return scopes; } /** * Returns the clock which will be passed along to the Credential. * @since 1.9 */ public final Clock getClock() { return clock; } /** * Returns the unmodifiable list of listeners for refresh token results. * * @since 1.15 */ public final Collection<CredentialRefreshListener> getRefreshListeners() { return refreshListeners; } /** * Listener for a created credential after a successful token response in * {@link #createAndStoreCredential}. * * @since 1.14 */ public interface CredentialCreatedListener { /** * Notifies of a created credential after a successful token response in * {@link #createAndStoreCredential}. * * <p> * Typical use is to parse additional fields from the credential created, such as an ID token. * </p> * * @param credential created credential * @param tokenResponse successful token response */ void onCredentialCreated(Credential credential, TokenResponse tokenResponse) throws IOException; } /** * Authorization code flow builder. * * <p> * Implementation is not thread-safe. * </p> */ public static class Builder { /** * Method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}). */ AccessMethod method; /** HTTP transport. */ HttpTransport transport; /** JSON factory. */ JsonFactory jsonFactory; /** Token server URL. */ GenericUrl tokenServerUrl; /** * Client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). */ HttpExecuteInterceptor clientAuthentication; /** Client identifier. */ String clientId; /** Authorization server encoded URL. */ String authorizationServerEncodedUrl; /** Credential persistence store or {@code null} for none. */ @Deprecated @Beta CredentialStore credentialStore; /** Stored credential data store or {@code null} for none. */ @Beta DataStore<StoredCredential> credentialDataStore; /** HTTP request initializer or {@code null} for none. */ HttpRequestInitializer requestInitializer; /** Collection of scopes. */ Collection<String> scopes = Lists.newArrayList(); /** Clock passed along to the Credential. */ Clock clock = Clock.SYSTEM; /** Credential created listener or {@code null} for none. */ CredentialCreatedListener credentialCreatedListener; /** Refresh listeners provided by the client. */ Collection<CredentialRefreshListener> refreshListeners = Lists.newArrayList(); /** * @param method method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}) * @param transport HTTP transport * @param jsonFactory JSON factory * @param tokenServerUrl token server URL * @param clientAuthentication client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}) * @param clientId client identifier * @param authorizationServerEncodedUrl authorization server encoded URL */ public Builder(AccessMethod method, HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl, HttpExecuteInterceptor clientAuthentication, String clientId, String authorizationServerEncodedUrl) { setMethod(method); setTransport(transport); setJsonFactory(jsonFactory); setTokenServerUrl(tokenServerUrl); setClientAuthentication(clientAuthentication); setClientId(clientId); setAuthorizationServerEncodedUrl(authorizationServerEncodedUrl); } /** Returns a new instance of an authorization code flow based on this builder. */ public AuthorizationCodeFlow build() { return new AuthorizationCodeFlow(this); } /** * Returns the method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}). */ public final AccessMethod getMethod() { return method; } /** * Sets the method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}). * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setMethod(AccessMethod method) { this.method = Preconditions.checkNotNull(method); return this; } /** Returns the HTTP transport. */ public final HttpTransport getTransport() { return transport; } /** * Sets the HTTP transport. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setTransport(HttpTransport transport) { this.transport = Preconditions.checkNotNull(transport); return this; } /** Returns the JSON factory. */ public final JsonFactory getJsonFactory() { return jsonFactory; } /** * Sets the JSON factory. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setJsonFactory(JsonFactory jsonFactory) { this.jsonFactory = Preconditions.checkNotNull(jsonFactory); return this; } /** Returns the token server URL. */ public final GenericUrl getTokenServerUrl() { return tokenServerUrl; } /** * Sets the token server URL. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setTokenServerUrl(GenericUrl tokenServerUrl) { this.tokenServerUrl = Preconditions.checkNotNull(tokenServerUrl); return this; } /** * Returns the client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). */ public final HttpExecuteInterceptor getClientAuthentication() { return clientAuthentication; } /** * Sets the client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { this.clientAuthentication = clientAuthentication; return this; } /** Returns the client identifier. */ public final String getClientId() { return clientId; } /** * Sets the client identifier. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setClientId(String clientId) { this.clientId = Preconditions.checkNotNull(clientId); return this; } /** Returns the authorization server encoded URL. */ public final String getAuthorizationServerEncodedUrl() { return authorizationServerEncodedUrl; } /** * Sets the authorization server encoded URL. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setAuthorizationServerEncodedUrl(String authorizationServerEncodedUrl) { this.authorizationServerEncodedUrl = Preconditions.checkNotNull(authorizationServerEncodedUrl); return this; } /** * {@link Beta} <br/> * Returns the credential persistence store or {@code null} for none. * @deprecated (to be removed in the future) Use {@link #getCredentialDataStore()} instead. */ @Beta @Deprecated public final CredentialStore getCredentialStore() { return credentialStore; } /** * {@link Beta} <br/> * Returns the stored credential data store or {@code null} for none. * * @since 1.16 */ @Beta public final DataStore<StoredCredential> getCredentialDataStore() { return credentialDataStore; } /** * Returns the clock passed along to the Credential or {@link Clock#SYSTEM} when system default * is used. * @since 1.9 */ public final Clock getClock() { return clock; } /** * Sets the clock to pass to the Credential. * * <p> * The default value for this parameter is {@link Clock#SYSTEM} * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.9 */ public Builder setClock(Clock clock) { this.clock = Preconditions.checkNotNull(clock); return this; } /** * {@link Beta} <br/> * Sets the credential persistence store or {@code null} for none. * * <p> * Warning: not compatible with {@link #setDataStoreFactory} or {@link #setCredentialDataStore}, * and if either of those is called before this method is called, this method will throw an * {@link IllegalArgumentException}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @deprecated (to be removed in the future) Use * {@link #setDataStoreFactory(DataStoreFactory)} or * {@link #setCredentialDataStore(DataStore)} instead. */ @Beta @Deprecated public Builder setCredentialStore(CredentialStore credentialStore) { Preconditions.checkArgument(credentialDataStore == null); this.credentialStore = credentialStore; return this; } /** * {@link Beta} <br/> * Sets the data store factory or {@code null} for none. * * <p> * Warning: not compatible with {@link #setCredentialStore}, and if it is called before this * method is called, this method will throw an {@link IllegalArgumentException}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.16 */ @Beta public Builder setDataStoreFactory(DataStoreFactory dataStoreFactory) throws IOException { return setCredentialDataStore(StoredCredential.getDefaultDataStore(dataStoreFactory)); } /** * {@link Beta} <br/> * Sets the stored credential data store or {@code null} for none. * * <p> * Warning: not compatible with {@link #setCredentialStore}, and if it is called before this * method is called, this method will throw an {@link IllegalArgumentException}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.16 */ @Beta public Builder setCredentialDataStore(DataStore<StoredCredential> credentialDataStore) { Preconditions.checkArgument(credentialStore == null); this.credentialDataStore = credentialDataStore; return this; } /** Returns the HTTP request initializer or {@code null} for none. */ public final HttpRequestInitializer getRequestInitializer() { return requestInitializer; } /** * Sets the HTTP request initializer or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) { this.requestInitializer = requestInitializer; return this; } /** * Sets the collection of scopes. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param scopes collection of scopes * @since 1.15 */ public Builder setScopes(Collection<String> scopes) { this.scopes = Preconditions.checkNotNull(scopes); return this; } /** Returns a collection of scopes. */ public final Collection<String> getScopes() { return scopes; } /** * Sets the credential created listener or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.14 */ public Builder setCredentialCreatedListener( CredentialCreatedListener credentialCreatedListener) { this.credentialCreatedListener = credentialCreatedListener; return this; } /** * Adds a listener for refresh token results. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param refreshListener refresh listener * @since 1.15 */ public Builder addRefreshListener(CredentialRefreshListener refreshListener) { refreshListeners.add(Preconditions.checkNotNull(refreshListener)); return this; } /** * Returns the listeners for refresh token results. * * @since 1.15 */ public final Collection<CredentialRefreshListener> getRefreshListeners() { return refreshListeners; } /** * Sets the listeners for refresh token results. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.15 */ public Builder setRefreshListeners(Collection<CredentialRefreshListener> refreshListeners) { this.refreshListeners = Preconditions.checkNotNull(refreshListeners); return this; } /** * Returns the credential created listener or {@code null} for none. * * @since 1.14 */ public final CredentialCreatedListener getCredentialCreatedListener() { return credentialCreatedListener; } } }
./CrossVul/dataset_final_sorted/CWE-862/java/bad_4619_0
crossvul-java_data_bad_4619_2
/* * Copyright (c) 2013 Google Inc. * * 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 com.google.api.client.auth.oauth2; import com.google.api.client.auth.oauth2.AuthorizationCodeFlow.CredentialCreatedListener; import com.google.api.client.http.BasicAuthentication; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.Joiner; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; /** * Tests {@link AuthorizationCodeFlow}. * * @author Yaniv Inbar */ public class AuthorizationCodeFlowTest extends AuthenticationTestBase { static class MyCredentialCreatedListener implements CredentialCreatedListener { boolean called = false; public void onCredentialCreated(Credential credential, TokenResponse tokenResponse) throws IOException { called = true; } } static class MyCredentialRefreshListener implements CredentialRefreshListener { boolean calledOnResponse = false; boolean calledOnError = false; public void onTokenResponse(Credential credential, TokenResponse tokenResponse) throws IOException { calledOnResponse = true; } public void onTokenErrorResponse(Credential credential, TokenErrorResponse tokenErrorResponse) throws IOException { calledOnError = true; } } public void testCredentialCreatedListener() throws IOException { MyCredentialCreatedListener listener = new MyCredentialCreatedListener(); AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.queryParameterAccessMethod(), new AccessTokenTransport(), new JacksonFactory(), TOKEN_SERVER_URL, new BasicAuthentication(CLIENT_ID, CLIENT_SECRET), CLIENT_ID, "authorizationServerEncodedUrl").setCredentialCreatedListener(listener).build(); assertFalse(listener.called); flow.createAndStoreCredential(new TokenResponse(), "userId"); assertTrue(listener.called); } public void testRefreshListeners() throws IOException { MyCredentialRefreshListener listener1 = new MyCredentialRefreshListener(); MyCredentialRefreshListener listener2 = new MyCredentialRefreshListener(); AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken .queryParameterAccessMethod(), new AccessTokenTransport(), new JacksonFactory(), TOKEN_SERVER_URL, new BasicAuthentication(CLIENT_ID, CLIENT_SECRET), CLIENT_ID, "authorizationServerEncodedUrl").addRefreshListener(listener1) .addRefreshListener(listener2).build(); TokenResponse tokenResponse = new TokenResponse(); tokenResponse.setAccessToken(ACCESS_TOKEN); tokenResponse.setRefreshToken(REFRESH_TOKEN); Credential cred = flow.createAndStoreCredential(tokenResponse, "userId"); assertFalse(listener1.calledOnResponse); assertFalse(listener2.calledOnResponse); assertFalse(listener1.calledOnError); assertFalse(listener2.calledOnError); assertTrue(cred.refreshToken()); assertTrue(listener1.calledOnResponse); assertTrue(listener2.calledOnResponse); assertFalse(listener1.calledOnError); assertFalse(listener2.calledOnError); } public void testNewAuthorizationUrl() { subsetTestNewAuthorizationUrl(Collections.<String>emptyList()); subsetTestNewAuthorizationUrl(Collections.singleton("a")); subsetTestNewAuthorizationUrl(Arrays.asList("a", "b", "c", "d")); } public void subsetTestNewAuthorizationUrl(Collection<String> scopes) { AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.queryParameterAccessMethod(), new AccessTokenTransport(), new JacksonFactory(), TOKEN_SERVER_URL, new BasicAuthentication(CLIENT_ID, CLIENT_SECRET), CLIENT_ID, "https://example.com").setScopes(scopes).build(); AuthorizationCodeRequestUrl url = flow.newAuthorizationUrl(); if (scopes.isEmpty()) { assertNull(url.getScopes()); } else { assertEquals(Joiner.on(' ').join(scopes), url.getScopes()); } } }
./CrossVul/dataset_final_sorted/CWE-862/java/bad_4619_2
crossvul-java_data_bad_4619_1
/* * Copyright (c) 2011 Google Inc. * * 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 com.google.api.client.auth.oauth2; import java.util.Collection; import java.util.Collections; /** * OAuth 2.0 URL builder for an authorization web page to allow the end user to authorize the * application to access their protected resources and that returns an authorization code, as * specified in <a href="http://tools.ietf.org/html/rfc6749#section-4.1">Authorization Code * Grant</a>. * * <p> * The default for {@link #getResponseTypes()} is {@code "code"}. Use * {@link AuthorizationCodeResponseUrl} to parse the redirect response after the end user * grants/denies the request. Using the authorization code in this response, use * {@link AuthorizationCodeTokenRequest} to request the access token. * </p> * * <p> * Sample usage for a web application: * </p> * * <pre> public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String url = new AuthorizationCodeRequestUrl("https://server.example.com/authorize", "s6BhdRkqt3") .setState("xyz").setRedirectUri("https://client.example.com/rd").build(); response.sendRedirect(url); } * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class AuthorizationCodeRequestUrl extends AuthorizationRequestUrl { /** * @param authorizationServerEncodedUrl authorization server encoded URL * @param clientId client identifier */ public AuthorizationCodeRequestUrl(String authorizationServerEncodedUrl, String clientId) { super(authorizationServerEncodedUrl, clientId, Collections.singleton("code")); } @Override public AuthorizationCodeRequestUrl setResponseTypes(Collection<String> responseTypes) { return (AuthorizationCodeRequestUrl) super.setResponseTypes(responseTypes); } @Override public AuthorizationCodeRequestUrl setRedirectUri(String redirectUri) { return (AuthorizationCodeRequestUrl) super.setRedirectUri(redirectUri); } @Override public AuthorizationCodeRequestUrl setScopes(Collection<String> scopes) { return (AuthorizationCodeRequestUrl) super.setScopes(scopes); } @Override public AuthorizationCodeRequestUrl setClientId(String clientId) { return (AuthorizationCodeRequestUrl) super.setClientId(clientId); } @Override public AuthorizationCodeRequestUrl setState(String state) { return (AuthorizationCodeRequestUrl) super.setState(state); } @Override public AuthorizationCodeRequestUrl set(String fieldName, Object value) { return (AuthorizationCodeRequestUrl) super.set(fieldName, value); } @Override public AuthorizationCodeRequestUrl clone() { return (AuthorizationCodeRequestUrl) super.clone(); } }
./CrossVul/dataset_final_sorted/CWE-862/java/bad_4619_1
crossvul-java_data_good_4619_1
/* * Copyright (c) 2011 Google Inc. * * 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 com.google.api.client.auth.oauth2; import com.google.api.client.util.Key; import java.util.Collection; import java.util.Collections; /** * OAuth 2.0 URL builder for an authorization web page to allow the end user to authorize the * application to access their protected resources and that returns an authorization code, as * specified in <a href="http://tools.ietf.org/html/rfc6749#section-4.1">Authorization Code * Grant</a>. * * <p> * The default for {@link #getResponseTypes()} is {@code "code"}. Use * {@link AuthorizationCodeResponseUrl} to parse the redirect response after the end user * grants/denies the request. Using the authorization code in this response, use * {@link AuthorizationCodeTokenRequest} to request the access token. * </p> * * <p> * Sample usage for a web application: * </p> * * <pre> public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String url = new AuthorizationCodeRequestUrl("https://server.example.com/authorize", "s6BhdRkqt3") .setState("xyz").setRedirectUri("https://client.example.com/rd").build(); response.sendRedirect(url); } * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class AuthorizationCodeRequestUrl extends AuthorizationRequestUrl { /** * The PKCE <a href="https://tools.ietf.org/html/rfc7636#section-4.3">Code Challenge</a>. * @since 1.31 */ @Key("code_challenge") String codeChallenge; /** * The PKCE <a href="https://tools.ietf.org/html/rfc7636#section-4.3">Code Challenge Method</a>. * @since 1.31 */ @Key("code_challenge_method") String codeChallengeMethod; /** * @param authorizationServerEncodedUrl authorization server encoded URL * @param clientId client identifier */ public AuthorizationCodeRequestUrl(String authorizationServerEncodedUrl, String clientId) { super(authorizationServerEncodedUrl, clientId, Collections.singleton("code")); } /** * Get the code challenge (<a href="https://tools.ietf.org/html/rfc7636#section-4.3">details</a>). * * @since 1.31 */ public String getCodeChallenge() { return codeChallenge; } /** * Get the code challenge method (<a href="https://tools.ietf.org/html/rfc7636#section-4.3">details</a>). * * @since 1.31 */ public String getCodeChallengeMethod() { return codeChallengeMethod; } /** * Set the code challenge (<a href="https://tools.ietf.org/html/rfc7636#section-4.3">details</a>). * @param codeChallenge the code challenge. * * @since 1.31 */ public void setCodeChallenge(String codeChallenge) { this.codeChallenge = codeChallenge; } /** * Set the code challenge method (<a href="https://tools.ietf.org/html/rfc7636#section-4.3">details</a>). * @param codeChallengeMethod the code challenge method. * * @since 1.31 */ public void setCodeChallengeMethod(String codeChallengeMethod) { this.codeChallengeMethod = codeChallengeMethod; } @Override public AuthorizationCodeRequestUrl setResponseTypes(Collection<String> responseTypes) { return (AuthorizationCodeRequestUrl) super.setResponseTypes(responseTypes); } @Override public AuthorizationCodeRequestUrl setRedirectUri(String redirectUri) { return (AuthorizationCodeRequestUrl) super.setRedirectUri(redirectUri); } @Override public AuthorizationCodeRequestUrl setScopes(Collection<String> scopes) { return (AuthorizationCodeRequestUrl) super.setScopes(scopes); } @Override public AuthorizationCodeRequestUrl setClientId(String clientId) { return (AuthorizationCodeRequestUrl) super.setClientId(clientId); } @Override public AuthorizationCodeRequestUrl setState(String state) { return (AuthorizationCodeRequestUrl) super.setState(state); } @Override public AuthorizationCodeRequestUrl set(String fieldName, Object value) { return (AuthorizationCodeRequestUrl) super.set(fieldName, value); } @Override public AuthorizationCodeRequestUrl clone() { return (AuthorizationCodeRequestUrl) super.clone(); } }
./CrossVul/dataset_final_sorted/CWE-862/java/good_4619_1
crossvul-java_data_good_1897_0
package io.onedev.server.model; import static io.onedev.server.model.User.PROP_EMAIL; import static io.onedev.server.model.User.PROP_FULL_NAME; import static io.onedev.server.model.User.PROP_NAME; import static io.onedev.server.model.User.PROP_ACCESS_TOKEN; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Stack; import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Lob; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.apache.commons.lang3.RandomStringUtils; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.SimplePrincipalCollection; import org.apache.shiro.subject.Subject; import org.eclipse.jgit.lib.PersonIdent; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonView; import com.google.common.base.MoreObjects; import io.onedev.server.OneDev; import io.onedev.server.entitymanager.SettingManager; import io.onedev.server.model.support.NamedProjectQuery; import io.onedev.server.model.support.QuerySetting; import io.onedev.server.model.support.SsoInfo; import io.onedev.server.model.support.administration.authenticator.Authenticator; import io.onedev.server.model.support.administration.sso.SsoConnector; import io.onedev.server.model.support.build.NamedBuildQuery; import io.onedev.server.model.support.issue.NamedIssueQuery; import io.onedev.server.model.support.pullrequest.NamedPullRequestQuery; import io.onedev.server.security.SecurityUtils; import io.onedev.server.util.jackson.DefaultView; import io.onedev.server.util.match.MatchScoreUtils; import io.onedev.server.util.validation.annotation.UserName; import io.onedev.server.util.watch.QuerySubscriptionSupport; import io.onedev.server.util.watch.QueryWatchSupport; import io.onedev.server.web.editable.annotation.Editable; import io.onedev.server.web.editable.annotation.Password; @Entity @Table( indexes={@Index(columnList=PROP_NAME), @Index(columnList=PROP_EMAIL), @Index(columnList=PROP_FULL_NAME), @Index(columnList=SsoInfo.COLUMN_CONNECTOR), @Index(columnList=SsoInfo.COLUMN_SUBJECT), @Index(columnList=PROP_ACCESS_TOKEN)}, uniqueConstraints={@UniqueConstraint(columnNames={SsoInfo.COLUMN_CONNECTOR, SsoInfo.COLUMN_SUBJECT})}) @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) @Editable public class User extends AbstractEntity implements AuthenticationInfo { private static final long serialVersionUID = 1L; public static final int ACCESS_TOKEN_LEN = 40; public static final Long SYSTEM_ID = -1L; public static final Long ROOT_ID = 1L; public static final String EXTERNAL_MANAGED = "external_managed"; public static final String PROP_NAME = "name"; public static final String PROP_EMAIL = "email"; public static final String PROP_PASSWORD = "password"; public static final String PROP_FULL_NAME = "fullName"; public static final String PROP_SSO_INFO = "ssoInfo"; public static final String PROP_ACCESS_TOKEN = "accessToken"; public static final String AUTH_SOURCE_BUILTIN_USER_STORE = "Builtin User Store"; public static final String AUTH_SOURCE_EXTERNAL_AUTHENTICATOR = "External Authenticator"; public static final String AUTH_SOURCE_SSO_PROVIDER = "SSO Provider: "; private static ThreadLocal<Stack<User>> stack = new ThreadLocal<Stack<User>>() { @Override protected Stack<User> initialValue() { return new Stack<User>(); } }; @Column(unique=true, nullable=false) private String name; @Column(length=1024, nullable=false) @JsonView(DefaultView.class) private String password; private String fullName; @JsonView(DefaultView.class) @Embedded private SsoInfo ssoInfo = new SsoInfo(); @Column(unique=true, nullable=false) private String email; @Column(unique=true, nullable=false) @JsonView(DefaultView.class) private String accessToken = RandomStringUtils.randomAlphanumeric(ACCESS_TOKEN_LEN); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) private Collection<UserAuthorization> authorizations = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) private Collection<Membership> memberships = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<PullRequestReview> pullRequestReviews = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<PullRequestAssignment> pullRequestAssignments = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<PullRequestWatch> pullRequestWatches = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<IssueWatch> issueWatches = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<IssueVote> issueVotes = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<IssueQuerySetting> projectIssueQuerySettings = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<BuildQuerySetting> projectBuildQuerySettings = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<PullRequestQuerySetting> projectPullRequestQuerySettings = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<CommitQuerySetting> projectCommitQuerySettings = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<CodeCommentQuerySetting> projectCodeCommentQuerySettings = new ArrayList<>(); @OneToMany(mappedBy="owner", cascade=CascadeType.REMOVE) @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) private Collection<SshKey> sshKeys = new ArrayList<>(); @Lob @Column(nullable=false, length=65535) private ArrayList<NamedProjectQuery> userProjectQueries = new ArrayList<>(); @Lob @Column(nullable=false, length=65535) private ArrayList<NamedIssueQuery> userIssueQueries = new ArrayList<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashMap<String, Boolean> userIssueQueryWatches = new LinkedHashMap<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashMap<String, Boolean> issueQueryWatches = new LinkedHashMap<>(); @Lob @Column(nullable=false, length=65535) private ArrayList<NamedPullRequestQuery> userPullRequestQueries = new ArrayList<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashMap<String, Boolean> userPullRequestQueryWatches = new LinkedHashMap<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashMap<String, Boolean> pullRequestQueryWatches = new LinkedHashMap<>(); @Lob @Column(nullable=false, length=65535) private ArrayList<NamedBuildQuery> userBuildQueries = new ArrayList<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashSet<String> userBuildQuerySubscriptions = new LinkedHashSet<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashSet<String> buildQuerySubscriptions = new LinkedHashSet<>(); private transient Collection<Group> groups; public QuerySetting<NamedProjectQuery> getProjectQuerySetting() { return new QuerySetting<NamedProjectQuery>() { @Override public Project getProject() { return null; } @Override public User getUser() { return User.this; } @Override public ArrayList<NamedProjectQuery> getUserQueries() { return userProjectQueries; } @Override public void setUserQueries(ArrayList<NamedProjectQuery> userQueries) { userProjectQueries = userQueries; } @Override public QueryWatchSupport<NamedProjectQuery> getQueryWatchSupport() { return null; } @Override public QuerySubscriptionSupport<NamedProjectQuery> getQuerySubscriptionSupport() { return null; } }; } public QuerySetting<NamedIssueQuery> getIssueQuerySetting() { return new QuerySetting<NamedIssueQuery>() { @Override public Project getProject() { return null; } @Override public User getUser() { return User.this; } @Override public ArrayList<NamedIssueQuery> getUserQueries() { return userIssueQueries; } @Override public void setUserQueries(ArrayList<NamedIssueQuery> userQueries) { userIssueQueries = userQueries; } @Override public QueryWatchSupport<NamedIssueQuery> getQueryWatchSupport() { return new QueryWatchSupport<NamedIssueQuery>() { @Override public LinkedHashMap<String, Boolean> getUserQueryWatches() { return userIssueQueryWatches; } @Override public LinkedHashMap<String, Boolean> getQueryWatches() { return issueQueryWatches; } }; } @Override public QuerySubscriptionSupport<NamedIssueQuery> getQuerySubscriptionSupport() { return null; } }; } public QuerySetting<NamedPullRequestQuery> getPullRequestQuerySetting() { return new QuerySetting<NamedPullRequestQuery>() { @Override public Project getProject() { return null; } @Override public User getUser() { return User.this; } @Override public ArrayList<NamedPullRequestQuery> getUserQueries() { return userPullRequestQueries; } @Override public void setUserQueries(ArrayList<NamedPullRequestQuery> userQueries) { userPullRequestQueries = userQueries; } @Override public QueryWatchSupport<NamedPullRequestQuery> getQueryWatchSupport() { return new QueryWatchSupport<NamedPullRequestQuery>() { @Override public LinkedHashMap<String, Boolean> getUserQueryWatches() { return userPullRequestQueryWatches; } @Override public LinkedHashMap<String, Boolean> getQueryWatches() { return pullRequestQueryWatches; } }; } @Override public QuerySubscriptionSupport<NamedPullRequestQuery> getQuerySubscriptionSupport() { return null; } }; } public QuerySetting<NamedBuildQuery> getBuildQuerySetting() { return new QuerySetting<NamedBuildQuery>() { @Override public Project getProject() { return null; } @Override public User getUser() { return User.this; } @Override public ArrayList<NamedBuildQuery> getUserQueries() { return userBuildQueries; } @Override public void setUserQueries(ArrayList<NamedBuildQuery> userQueries) { userBuildQueries = userQueries; } @Override public QueryWatchSupport<NamedBuildQuery> getQueryWatchSupport() { return null; } @Override public QuerySubscriptionSupport<NamedBuildQuery> getQuerySubscriptionSupport() { return new QuerySubscriptionSupport<NamedBuildQuery>() { @Override public LinkedHashSet<String> getUserQuerySubscriptions() { return userBuildQuerySubscriptions; } @Override public LinkedHashSet<String> getQuerySubscriptions() { return buildQuerySubscriptions; } }; } }; } @Override public PrincipalCollection getPrincipals() { return new SimplePrincipalCollection(getId(), ""); } @Override public Object getCredentials() { return password; } public Subject asSubject() { return SecurityUtils.asSubject(getId()); } @Editable(name="Login Name", order=100) @UserName @NotEmpty public String getName() { return name; } public void setName(String name) { this.name = name; } @Editable(order=150) @Password(confirmative=true, autoComplete="new-password") @NotEmpty public String getPassword() { return password; } /** * Set password of this user. * * @param password * password to set */ public void setPassword(String password) { this.password = password; } public boolean isExternalManaged() { return getPassword().equals(EXTERNAL_MANAGED); } @Editable(order=200) public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public SsoInfo getSsoInfo() { return ssoInfo; } public void setSsoInfo(SsoInfo ssoInfo) { this.ssoInfo = ssoInfo; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } @Editable(order=300) @NotEmpty @Email public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Collection<Membership> getMemberships() { return memberships; } public void setMemberships(Collection<Membership> memberships) { this.memberships = memberships; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", getName()) .toString(); } public PersonIdent asPerson() { if (isSystem()) return new PersonIdent(getDisplayName(), ""); else return new PersonIdent(getDisplayName(), getEmail()); } public String getDisplayName() { if (getFullName() != null) return getFullName(); else return getName(); } public boolean isRoot() { return ROOT_ID.equals(getId()); } public boolean isSystem() { return SYSTEM_ID.equals(getId()); } public Collection<UserAuthorization> getAuthorizations() { return authorizations; } public void setAuthorizations(Collection<UserAuthorization> authorizations) { this.authorizations = authorizations; } @Override public int compareTo(AbstractEntity entity) { User user = (User) entity; if (getDisplayName().equals(user.getDisplayName())) { return getId().compareTo(entity.getId()); } else { return getDisplayName().compareTo(user.getDisplayName()); } } public double getMatchScore(@Nullable String queryTerm) { double scoreOfName = MatchScoreUtils.getMatchScore(name, queryTerm); double scoreOfFullName = MatchScoreUtils.getMatchScore(fullName, queryTerm); return Math.max(scoreOfName, scoreOfFullName); } public Collection<Group> getGroups() { if (groups == null) groups = getMemberships().stream().map(it->it.getGroup()).collect(Collectors.toList()); return groups; } public static User from(@Nullable User user, @Nullable String displayName) { if (user == null) { user = new User(); if (displayName != null) user.setName(displayName); else user.setName("Unknown"); } return user; } public static void push(User user) { stack.get().push(user); } public static void pop() { stack.get().pop(); } @Nullable public static User get() { if (!stack.get().isEmpty()) return stack.get().peek(); else return SecurityUtils.getUser(); } public Collection<SshKey> getSshKeys() { return sshKeys; } public void setSshKeys(Collection<SshKey> sshKeys) { this.sshKeys = sshKeys; } public boolean isSshKeyExternalManaged() { if (isExternalManaged()) { if (getSsoInfo().getConnector() != null) { return false; } else { Authenticator authenticator = OneDev.getInstance(SettingManager.class).getAuthenticator(); return authenticator != null && authenticator.isManagingSshKeys(); } } else { return false; } } public boolean isMembershipExternalManaged() { if (isExternalManaged()) { SettingManager settingManager = OneDev.getInstance(SettingManager.class); if (getSsoInfo().getConnector() != null) { SsoConnector ssoConnector = settingManager.getSsoConnectors().stream() .filter(it->it.getName().equals(getSsoInfo().getConnector())) .findFirst().orElse(null); return ssoConnector != null && ssoConnector.isManagingMemberships(); } else { Authenticator authenticator = settingManager.getAuthenticator(); return authenticator != null && authenticator.isManagingMemberships(); } } else { return false; } } public String getAuthSource() { if (isExternalManaged()) { if (getSsoInfo().getConnector() != null) return AUTH_SOURCE_SSO_PROVIDER + getSsoInfo().getConnector(); else return AUTH_SOURCE_EXTERNAL_AUTHENTICATOR; } else { return AUTH_SOURCE_BUILTIN_USER_STORE; } } }
./CrossVul/dataset_final_sorted/CWE-862/java/good_1897_0
crossvul-java_data_good_4619_2
/* * Copyright (c) 2013 Google Inc. * * 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 com.google.api.client.auth.oauth2; import com.google.api.client.auth.oauth2.AuthorizationCodeFlow.CredentialCreatedListener; import com.google.api.client.http.BasicAuthentication; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.Joiner; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * Tests {@link AuthorizationCodeFlow}. * * @author Yaniv Inbar */ public class AuthorizationCodeFlowTest extends AuthenticationTestBase { static class MyCredentialCreatedListener implements CredentialCreatedListener { boolean called = false; public void onCredentialCreated(Credential credential, TokenResponse tokenResponse) throws IOException { called = true; } } static class MyCredentialRefreshListener implements CredentialRefreshListener { boolean calledOnResponse = false; boolean calledOnError = false; public void onTokenResponse(Credential credential, TokenResponse tokenResponse) throws IOException { calledOnResponse = true; } public void onTokenErrorResponse(Credential credential, TokenErrorResponse tokenErrorResponse) throws IOException { calledOnError = true; } } public void testCredentialCreatedListener() throws IOException { MyCredentialCreatedListener listener = new MyCredentialCreatedListener(); AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.queryParameterAccessMethod(), new AccessTokenTransport(), new JacksonFactory(), TOKEN_SERVER_URL, new BasicAuthentication(CLIENT_ID, CLIENT_SECRET), CLIENT_ID, "authorizationServerEncodedUrl").setCredentialCreatedListener(listener).build(); assertFalse(listener.called); flow.createAndStoreCredential(new TokenResponse(), "userId"); assertTrue(listener.called); } public void testRefreshListeners() throws IOException { MyCredentialRefreshListener listener1 = new MyCredentialRefreshListener(); MyCredentialRefreshListener listener2 = new MyCredentialRefreshListener(); AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken .queryParameterAccessMethod(), new AccessTokenTransport(), new JacksonFactory(), TOKEN_SERVER_URL, new BasicAuthentication(CLIENT_ID, CLIENT_SECRET), CLIENT_ID, "authorizationServerEncodedUrl").addRefreshListener(listener1) .addRefreshListener(listener2).build(); TokenResponse tokenResponse = new TokenResponse(); tokenResponse.setAccessToken(ACCESS_TOKEN); tokenResponse.setRefreshToken(REFRESH_TOKEN); Credential cred = flow.createAndStoreCredential(tokenResponse, "userId"); assertFalse(listener1.calledOnResponse); assertFalse(listener2.calledOnResponse); assertFalse(listener1.calledOnError); assertFalse(listener2.calledOnError); assertTrue(cred.refreshToken()); assertTrue(listener1.calledOnResponse); assertTrue(listener2.calledOnResponse); assertFalse(listener1.calledOnError); assertFalse(listener2.calledOnError); } public void testNewAuthorizationUrl() { subsetTestNewAuthorizationUrl(Collections.<String>emptyList()); subsetTestNewAuthorizationUrl(Collections.singleton("a")); subsetTestNewAuthorizationUrl(Arrays.asList("a", "b", "c", "d")); } public void subsetTestNewAuthorizationUrl(Collection<String> scopes) { AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.queryParameterAccessMethod(), new AccessTokenTransport(), new JacksonFactory(), TOKEN_SERVER_URL, new BasicAuthentication(CLIENT_ID, CLIENT_SECRET), CLIENT_ID, "https://example.com").setScopes(scopes).build(); AuthorizationCodeRequestUrl url = flow.newAuthorizationUrl(); if (scopes.isEmpty()) { assertNull(url.getScopes()); } else { assertEquals(Joiner.on(' ').join(scopes), url.getScopes()); } } public void testPKCE() { AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.queryParameterAccessMethod(), new AccessTokenTransport(), new JacksonFactory(), TOKEN_SERVER_URL, new BasicAuthentication(CLIENT_ID, CLIENT_SECRET), CLIENT_ID, "https://example.com") .enablePKCE() .build(); AuthorizationCodeRequestUrl url = flow.newAuthorizationUrl(); assertNotNull(url.getCodeChallenge()); assertNotNull(url.getCodeChallengeMethod()); Set<String> methods = new HashSet<>(Arrays.asList("plain", "s256")); assertTrue(methods.contains(url.getCodeChallengeMethod().toLowerCase())); assertTrue(url.getCodeChallenge().length() > 0); } }
./CrossVul/dataset_final_sorted/CWE-862/java/good_4619_2
crossvul-java_data_good_4619_0
/* * Copyright (c) 2012 Google Inc. * * 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 com.google.api.client.auth.oauth2; import com.google.api.client.auth.oauth2.Credential.AccessMethod; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.UrlEncodedContent; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Base64; import com.google.api.client.util.Beta; import com.google.api.client.util.Data; import com.google.api.client.util.Clock; import com.google.api.client.util.Joiner; import com.google.api.client.util.Lists; import com.google.api.client.util.Preconditions; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Collection; import java.util.Collections; import java.util.Map; import static com.google.api.client.util.Strings.isNullOrEmpty; /** * Thread-safe OAuth 2.0 authorization code flow that manages and persists end-user credentials. * * <p> * This is designed to simplify the flow in which an end-user authorizes the application to access * their protected data, and then the application has access to their data based on an access token * and a refresh token to refresh that access token when it expires. * </p> * * <p> * The first step is to call {@link #loadCredential(String)} based on the known user ID to check if * the end-user's credentials are already known. If not, call {@link #newAuthorizationUrl()} and * direct the end-user's browser to an authorization page. The web browser will then redirect to the * redirect URL with a {@code "code"} query parameter which can then be used to request an access * token using {@link #newTokenRequest(String)}. Finally, use * {@link #createAndStoreCredential(TokenResponse, String)} to store and obtain a credential for * accessing protected resources. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class AuthorizationCodeFlow { /** * Method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}). */ private final AccessMethod method; /** HTTP transport. */ private final HttpTransport transport; /** JSON factory. */ private final JsonFactory jsonFactory; /** Token server encoded URL. */ private final String tokenServerEncodedUrl; /** * Client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). */ private final HttpExecuteInterceptor clientAuthentication; /** Client identifier. */ private final String clientId; /** Authorization server encoded URL. */ private final String authorizationServerEncodedUrl; /** The Proof Key for Code Exchange (PKCE) or {@code null} if this flow should not use PKCE. */ private final PKCE pkce; /** Credential persistence store or {@code null} for none. */ @Beta @Deprecated private final CredentialStore credentialStore; /** Stored credential data store or {@code null} for none. */ @Beta private final DataStore<StoredCredential> credentialDataStore; /** HTTP request initializer or {@code null} for none. */ private final HttpRequestInitializer requestInitializer; /** Clock passed along to Credential. */ private final Clock clock; /** Collection of scopes. */ private final Collection<String> scopes; /** Credential created listener or {@code null} for none. */ private final CredentialCreatedListener credentialCreatedListener; /** Refresh listeners provided by the client. */ private final Collection<CredentialRefreshListener> refreshListeners; /** * @param method method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}) * @param transport HTTP transport * @param jsonFactory JSON factory * @param tokenServerUrl token server URL * @param clientAuthentication client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}) * @param clientId client identifier * @param authorizationServerEncodedUrl authorization server encoded URL * * @since 1.14 */ public AuthorizationCodeFlow(AccessMethod method, HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl, HttpExecuteInterceptor clientAuthentication, String clientId, String authorizationServerEncodedUrl) { this(new Builder(method, transport, jsonFactory, tokenServerUrl, clientAuthentication, clientId, authorizationServerEncodedUrl)); } /** * @param builder authorization code flow builder * * @since 1.14 */ protected AuthorizationCodeFlow(Builder builder) { method = Preconditions.checkNotNull(builder.method); transport = Preconditions.checkNotNull(builder.transport); jsonFactory = Preconditions.checkNotNull(builder.jsonFactory); tokenServerEncodedUrl = Preconditions.checkNotNull(builder.tokenServerUrl).build(); clientAuthentication = builder.clientAuthentication; clientId = Preconditions.checkNotNull(builder.clientId); authorizationServerEncodedUrl = Preconditions.checkNotNull(builder.authorizationServerEncodedUrl); requestInitializer = builder.requestInitializer; credentialStore = builder.credentialStore; credentialDataStore = builder.credentialDataStore; scopes = Collections.unmodifiableCollection(builder.scopes); clock = Preconditions.checkNotNull(builder.clock); credentialCreatedListener = builder.credentialCreatedListener; refreshListeners = Collections.unmodifiableCollection(builder.refreshListeners); pkce = builder.pkce; } /** * Returns a new instance of an authorization code request URL. * * <p> * This is a builder for an authorization web page to allow the end user to authorize the * application to access their protected resources and that returns an authorization code. It uses * the {@link #getAuthorizationServerEncodedUrl()}, {@link #getClientId()}, and * {@link #getScopes()}. Sample usage: * </p> * * <pre> private AuthorizationCodeFlow flow; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String url = flow.newAuthorizationUrl().setState("xyz") .setRedirectUri("https://client.example.com/rd").build(); response.sendRedirect(url); } * </pre> */ public AuthorizationCodeRequestUrl newAuthorizationUrl() { AuthorizationCodeRequestUrl url = new AuthorizationCodeRequestUrl(authorizationServerEncodedUrl, clientId); url.setScopes(scopes); if (pkce != null) { url.setCodeChallenge(pkce.getChallenge()); url.setCodeChallengeMethod(pkce.getChallengeMethod()); } return url; } /** * Returns a new instance of an authorization code token request based on the given authorization * code. * * <p> * This is used to make a request for an access token using the authorization code. It uses * {@link #getTransport()}, {@link #getJsonFactory()}, {@link #getTokenServerEncodedUrl()}, * {@link #getClientAuthentication()}, {@link #getRequestInitializer()}, and {@link #getScopes()}. * </p> * * <pre> static TokenResponse requestAccessToken(AuthorizationCodeFlow flow, String code) throws IOException, TokenResponseException { return flow.newTokenRequest(code).setRedirectUri("https://client.example.com/rd").execute(); } * </pre> * * @param authorizationCode authorization code. */ public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) { HttpExecuteInterceptor pkceClientAuthenticationWrapper = new HttpExecuteInterceptor() { @Override public void intercept(HttpRequest request) throws IOException { clientAuthentication.intercept(request); if (pkce != null) { Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData()); data.put("code_verifier", pkce.getVerifier()); } } }; return new AuthorizationCodeTokenRequest(transport, jsonFactory, new GenericUrl(tokenServerEncodedUrl), authorizationCode).setClientAuthentication( pkceClientAuthenticationWrapper).setRequestInitializer(requestInitializer).setScopes(scopes); } /** * Creates a new credential for the given user ID based on the given token response * and stores it in the credential store. * * @param response token response * @param userId user ID or {@code null} if not using a persisted credential store * @return newly created credential */ @SuppressWarnings("deprecation") public Credential createAndStoreCredential(TokenResponse response, String userId) throws IOException { Credential credential = newCredential(userId).setFromTokenResponse(response); if (credentialStore != null) { credentialStore.store(userId, credential); } if (credentialDataStore != null) { credentialDataStore.set(userId, new StoredCredential(credential)); } if (credentialCreatedListener != null) { credentialCreatedListener.onCredentialCreated(credential, response); } return credential; } /** * Loads the credential of the given user ID from the credential store. * * @param userId user ID or {@code null} if not using a persisted credential store * @return credential found in the credential store of the given user ID or {@code null} for none * found */ @SuppressWarnings("deprecation") public Credential loadCredential(String userId) throws IOException { // No requests need to be performed when userId is not specified. if (isNullOrEmpty(userId)) { return null; } if (credentialDataStore == null && credentialStore == null) { return null; } Credential credential = newCredential(userId); if (credentialDataStore != null) { StoredCredential stored = credentialDataStore.get(userId); if (stored == null) { return null; } credential.setAccessToken(stored.getAccessToken()); credential.setRefreshToken(stored.getRefreshToken()); credential.setExpirationTimeMilliseconds(stored.getExpirationTimeMilliseconds()); } else if (!credentialStore.load(userId, credential)) { return null; } return credential; } /** * Returns a new credential instance based on the given user ID. * * @param userId user ID or {@code null} if not using a persisted credential store */ @SuppressWarnings("deprecation") private Credential newCredential(String userId) { Credential.Builder builder = new Credential.Builder(method).setTransport(transport) .setJsonFactory(jsonFactory) .setTokenServerEncodedUrl(tokenServerEncodedUrl) .setClientAuthentication(clientAuthentication) .setRequestInitializer(requestInitializer) .setClock(clock); if (credentialDataStore != null) { builder.addRefreshListener( new DataStoreCredentialRefreshListener(userId, credentialDataStore)); } else if (credentialStore != null) { builder.addRefreshListener(new CredentialStoreRefreshListener(userId, credentialStore)); } builder.getRefreshListeners().addAll(refreshListeners); return builder.build(); } /** * Returns the method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}). */ public final AccessMethod getMethod() { return method; } /** Returns the HTTP transport. */ public final HttpTransport getTransport() { return transport; } /** Returns the JSON factory. */ public final JsonFactory getJsonFactory() { return jsonFactory; } /** Returns the token server encoded URL. */ public final String getTokenServerEncodedUrl() { return tokenServerEncodedUrl; } /** * Returns the client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). */ public final HttpExecuteInterceptor getClientAuthentication() { return clientAuthentication; } /** Returns the client identifier. */ public final String getClientId() { return clientId; } /** Returns the authorization server encoded URL. */ public final String getAuthorizationServerEncodedUrl() { return authorizationServerEncodedUrl; } /** * {@link Beta} <br/> * Returns the credential persistence store or {@code null} for none. * @deprecated (to be removed in the future) Use {@link #getCredentialDataStore()} instead. */ @Beta @Deprecated public final CredentialStore getCredentialStore() { return credentialStore; } /** * {@link Beta} <br/> * Returns the stored credential data store or {@code null} for none. * * @since 1.16 */ @Beta public final DataStore<StoredCredential> getCredentialDataStore() { return credentialDataStore; } /** Returns the HTTP request initializer or {@code null} for none. */ public final HttpRequestInitializer getRequestInitializer() { return requestInitializer; } /** * Returns the space-separated list of scopes. * * @since 1.15 */ public final String getScopesAsString() { return Joiner.on(' ').join(scopes); } /** Returns the a collection of scopes. */ public final Collection<String> getScopes() { return scopes; } /** * Returns the clock which will be passed along to the Credential. * @since 1.9 */ public final Clock getClock() { return clock; } /** * Returns the unmodifiable list of listeners for refresh token results. * * @since 1.15 */ public final Collection<CredentialRefreshListener> getRefreshListeners() { return refreshListeners; } /** * Listener for a created credential after a successful token response in * {@link #createAndStoreCredential}. * * @since 1.14 */ public interface CredentialCreatedListener { /** * Notifies of a created credential after a successful token response in * {@link #createAndStoreCredential}. * * <p> * Typical use is to parse additional fields from the credential created, such as an ID token. * </p> * * @param credential created credential * @param tokenResponse successful token response */ void onCredentialCreated(Credential credential, TokenResponse tokenResponse) throws IOException; } /** * An implementation of <a href="https://tools.ietf.org/html/rfc7636">Proof Key for Code Exchange</a> * which, according to the <a href="https://tools.ietf.org/html/rfc8252#section-6">OAuth 2.0 for Native Apps RFC</a>, * is mandatory for public native apps. */ private static class PKCE { private final String verifier; private String challenge; private String challengeMethod; public PKCE() { verifier = generateVerifier(); generateChallenge(verifier); } private static String generateVerifier() { SecureRandom sr = new SecureRandom(); byte[] code = new byte[32]; sr.nextBytes(code); return Base64.encodeBase64URLSafeString(code); } /** * Create the PKCE code verifier. It uses the S256 method but * falls back to using the 'plain' method in the unlikely case * that the SHA-256 MessageDigest algorithm implementation can't be * loaded. */ private void generateChallenge(String verifier) { try { byte[] bytes = verifier.getBytes(); MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(bytes, 0, bytes.length); byte[] digest = md.digest(); challenge = Base64.encodeBase64URLSafeString(digest); challengeMethod = "S256"; } catch (NoSuchAlgorithmException e) { challenge = verifier; challengeMethod = "plain"; } } public String getVerifier() { return verifier; } public String getChallenge() { return challenge; } public String getChallengeMethod() { return challengeMethod; } } /** * Authorization code flow builder. * * <p> * Implementation is not thread-safe. * </p> */ public static class Builder { /** * Method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}). */ AccessMethod method; /** HTTP transport. */ HttpTransport transport; /** JSON factory. */ JsonFactory jsonFactory; /** Token server URL. */ GenericUrl tokenServerUrl; /** * Client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). */ HttpExecuteInterceptor clientAuthentication; /** Client identifier. */ String clientId; /** Authorization server encoded URL. */ String authorizationServerEncodedUrl; PKCE pkce; /** Credential persistence store or {@code null} for none. */ @Deprecated @Beta CredentialStore credentialStore; /** Stored credential data store or {@code null} for none. */ @Beta DataStore<StoredCredential> credentialDataStore; /** HTTP request initializer or {@code null} for none. */ HttpRequestInitializer requestInitializer; /** Collection of scopes. */ Collection<String> scopes = Lists.newArrayList(); /** Clock passed along to the Credential. */ Clock clock = Clock.SYSTEM; /** Credential created listener or {@code null} for none. */ CredentialCreatedListener credentialCreatedListener; /** Refresh listeners provided by the client. */ Collection<CredentialRefreshListener> refreshListeners = Lists.newArrayList(); /** * @param method method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}) * @param transport HTTP transport * @param jsonFactory JSON factory * @param tokenServerUrl token server URL * @param clientAuthentication client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}) * @param clientId client identifier * @param authorizationServerEncodedUrl authorization server encoded URL */ public Builder(AccessMethod method, HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl, HttpExecuteInterceptor clientAuthentication, String clientId, String authorizationServerEncodedUrl) { setMethod(method); setTransport(transport); setJsonFactory(jsonFactory); setTokenServerUrl(tokenServerUrl); setClientAuthentication(clientAuthentication); setClientId(clientId); setAuthorizationServerEncodedUrl(authorizationServerEncodedUrl); } /** Returns a new instance of an authorization code flow based on this builder. */ public AuthorizationCodeFlow build() { return new AuthorizationCodeFlow(this); } /** * Returns the method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}). */ public final AccessMethod getMethod() { return method; } /** * Sets the method of presenting the access token to the resource server (for example * {@link BearerToken#authorizationHeaderAccessMethod}). * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setMethod(AccessMethod method) { this.method = Preconditions.checkNotNull(method); return this; } /** Returns the HTTP transport. */ public final HttpTransport getTransport() { return transport; } /** * Sets the HTTP transport. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setTransport(HttpTransport transport) { this.transport = Preconditions.checkNotNull(transport); return this; } /** Returns the JSON factory. */ public final JsonFactory getJsonFactory() { return jsonFactory; } /** * Sets the JSON factory. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setJsonFactory(JsonFactory jsonFactory) { this.jsonFactory = Preconditions.checkNotNull(jsonFactory); return this; } /** Returns the token server URL. */ public final GenericUrl getTokenServerUrl() { return tokenServerUrl; } /** * Sets the token server URL. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setTokenServerUrl(GenericUrl tokenServerUrl) { this.tokenServerUrl = Preconditions.checkNotNull(tokenServerUrl); return this; } /** * Returns the client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). */ public final HttpExecuteInterceptor getClientAuthentication() { return clientAuthentication; } /** * Sets the client authentication or {@code null} for none (see * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { this.clientAuthentication = clientAuthentication; return this; } /** Returns the client identifier. */ public final String getClientId() { return clientId; } /** * Sets the client identifier. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setClientId(String clientId) { this.clientId = Preconditions.checkNotNull(clientId); return this; } /** Returns the authorization server encoded URL. */ public final String getAuthorizationServerEncodedUrl() { return authorizationServerEncodedUrl; } /** * Sets the authorization server encoded URL. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.11 */ public Builder setAuthorizationServerEncodedUrl(String authorizationServerEncodedUrl) { this.authorizationServerEncodedUrl = Preconditions.checkNotNull(authorizationServerEncodedUrl); return this; } /** * {@link Beta} <br/> * Returns the credential persistence store or {@code null} for none. * @deprecated (to be removed in the future) Use {@link #getCredentialDataStore()} instead. */ @Beta @Deprecated public final CredentialStore getCredentialStore() { return credentialStore; } /** * {@link Beta} <br/> * Returns the stored credential data store or {@code null} for none. * * @since 1.16 */ @Beta public final DataStore<StoredCredential> getCredentialDataStore() { return credentialDataStore; } /** * Returns the clock passed along to the Credential or {@link Clock#SYSTEM} when system default * is used. * @since 1.9 */ public final Clock getClock() { return clock; } /** * Sets the clock to pass to the Credential. * * <p> * The default value for this parameter is {@link Clock#SYSTEM} * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * @since 1.9 */ public Builder setClock(Clock clock) { this.clock = Preconditions.checkNotNull(clock); return this; } /** * {@link Beta} <br/> * Sets the credential persistence store or {@code null} for none. * * <p> * Warning: not compatible with {@link #setDataStoreFactory} or {@link #setCredentialDataStore}, * and if either of those is called before this method is called, this method will throw an * {@link IllegalArgumentException}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @deprecated (to be removed in the future) Use * {@link #setDataStoreFactory(DataStoreFactory)} or * {@link #setCredentialDataStore(DataStore)} instead. */ @Beta @Deprecated public Builder setCredentialStore(CredentialStore credentialStore) { Preconditions.checkArgument(credentialDataStore == null); this.credentialStore = credentialStore; return this; } /** * {@link Beta} <br/> * Sets the data store factory or {@code null} for none. * * <p> * Warning: not compatible with {@link #setCredentialStore}, and if it is called before this * method is called, this method will throw an {@link IllegalArgumentException}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.16 */ @Beta public Builder setDataStoreFactory(DataStoreFactory dataStoreFactory) throws IOException { return setCredentialDataStore(StoredCredential.getDefaultDataStore(dataStoreFactory)); } /** * {@link Beta} <br/> * Sets the stored credential data store or {@code null} for none. * * <p> * Warning: not compatible with {@link #setCredentialStore}, and if it is called before this * method is called, this method will throw an {@link IllegalArgumentException}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.16 */ @Beta public Builder setCredentialDataStore(DataStore<StoredCredential> credentialDataStore) { Preconditions.checkArgument(credentialStore == null); this.credentialDataStore = credentialDataStore; return this; } /** Returns the HTTP request initializer or {@code null} for none. */ public final HttpRequestInitializer getRequestInitializer() { return requestInitializer; } /** * Sets the HTTP request initializer or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) { this.requestInitializer = requestInitializer; return this; } /** * Enables Proof Key for Code Exchange (PKCE) for this Athorization Code Flow. * @since 1.31 */ @Beta public Builder enablePKCE() { this.pkce = new PKCE(); return this; } /** * Sets the collection of scopes. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param scopes collection of scopes * @since 1.15 */ public Builder setScopes(Collection<String> scopes) { this.scopes = Preconditions.checkNotNull(scopes); return this; } /** Returns a collection of scopes. */ public final Collection<String> getScopes() { return scopes; } /** * Sets the credential created listener or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.14 */ public Builder setCredentialCreatedListener( CredentialCreatedListener credentialCreatedListener) { this.credentialCreatedListener = credentialCreatedListener; return this; } /** * Adds a listener for refresh token results. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param refreshListener refresh listener * @since 1.15 */ public Builder addRefreshListener(CredentialRefreshListener refreshListener) { refreshListeners.add(Preconditions.checkNotNull(refreshListener)); return this; } /** * Returns the listeners for refresh token results. * * @since 1.15 */ public final Collection<CredentialRefreshListener> getRefreshListeners() { return refreshListeners; } /** * Sets the listeners for refresh token results. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.15 */ public Builder setRefreshListeners(Collection<CredentialRefreshListener> refreshListeners) { this.refreshListeners = Preconditions.checkNotNull(refreshListeners); return this; } /** * Returns the credential created listener or {@code null} for none. * * @since 1.14 */ public final CredentialCreatedListener getCredentialCreatedListener() { return credentialCreatedListener; } } }
./CrossVul/dataset_final_sorted/CWE-862/java/good_4619_0
crossvul-java_data_bad_1897_1
package io.onedev.server.rest; import java.util.Collection; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.shiro.authz.UnauthorizedException; import org.hibernate.criterion.Restrictions; import org.hibernate.validator.constraints.Email; import io.onedev.server.entitymanager.UserManager; import io.onedev.server.model.User; import io.onedev.server.persistence.dao.EntityCriteria; import io.onedev.server.rest.jersey.ValidQueryParams; import io.onedev.server.security.SecurityUtils; @Path("/users") @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Singleton public class UserResource { private final UserManager userManager; @Inject public UserResource(UserManager userManager) { this.userManager = userManager; } @ValidQueryParams @GET public Response query(@QueryParam("name") String name, @Email @QueryParam("email") String email, @QueryParam("offset") Integer offset, @QueryParam("count") Integer count, @Context UriInfo uriInfo) { if (!SecurityUtils.isAdministrator()) throw new UnauthorizedException("Unauthorized access to user profiles"); EntityCriteria<User> criteria = EntityCriteria.of(User.class); if (name != null) criteria.add(Restrictions.eq("name", name)); if (email != null) criteria.add(Restrictions.eq("email", email)); if (offset == null) offset = 0; if (count == null || count > RestConstants.PAGE_SIZE) count = RestConstants.PAGE_SIZE; Collection<User> users = userManager.query(criteria, offset, count); return Response.ok(users, RestConstants.JSON_UTF8).build(); } @GET @Path("/{userId}") public User get(@PathParam("userId") Long userId) { return userManager.load(userId); } }
./CrossVul/dataset_final_sorted/CWE-862/java/bad_1897_1
crossvul-java_data_bad_1897_0
package io.onedev.server.model; import static io.onedev.server.model.User.PROP_EMAIL; import static io.onedev.server.model.User.PROP_FULL_NAME; import static io.onedev.server.model.User.PROP_NAME; import static io.onedev.server.model.User.PROP_ACCESS_TOKEN; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Stack; import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Lob; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.apache.commons.lang3.RandomStringUtils; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.SimplePrincipalCollection; import org.apache.shiro.subject.Subject; import org.eclipse.jgit.lib.PersonIdent; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonView; import com.google.common.base.MoreObjects; import io.onedev.server.OneDev; import io.onedev.server.entitymanager.SettingManager; import io.onedev.server.model.support.NamedProjectQuery; import io.onedev.server.model.support.QuerySetting; import io.onedev.server.model.support.SsoInfo; import io.onedev.server.model.support.administration.authenticator.Authenticator; import io.onedev.server.model.support.administration.sso.SsoConnector; import io.onedev.server.model.support.build.NamedBuildQuery; import io.onedev.server.model.support.issue.NamedIssueQuery; import io.onedev.server.model.support.pullrequest.NamedPullRequestQuery; import io.onedev.server.security.SecurityUtils; import io.onedev.server.util.jackson.DefaultView; import io.onedev.server.util.match.MatchScoreUtils; import io.onedev.server.util.validation.annotation.UserName; import io.onedev.server.util.watch.QuerySubscriptionSupport; import io.onedev.server.util.watch.QueryWatchSupport; import io.onedev.server.web.editable.annotation.Editable; import io.onedev.server.web.editable.annotation.Password; @Entity @Table( indexes={@Index(columnList=PROP_NAME), @Index(columnList=PROP_EMAIL), @Index(columnList=PROP_FULL_NAME), @Index(columnList=SsoInfo.COLUMN_CONNECTOR), @Index(columnList=SsoInfo.COLUMN_SUBJECT), @Index(columnList=PROP_ACCESS_TOKEN)}, uniqueConstraints={@UniqueConstraint(columnNames={SsoInfo.COLUMN_CONNECTOR, SsoInfo.COLUMN_SUBJECT})}) @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) @Editable public class User extends AbstractEntity implements AuthenticationInfo { private static final long serialVersionUID = 1L; public static final int ACCESS_TOKEN_LEN = 40; public static final Long SYSTEM_ID = -1L; public static final Long ROOT_ID = 1L; public static final String EXTERNAL_MANAGED = "external_managed"; public static final String PROP_NAME = "name"; public static final String PROP_EMAIL = "email"; public static final String PROP_PASSWORD = "password"; public static final String PROP_FULL_NAME = "fullName"; public static final String PROP_SSO_INFO = "ssoInfo"; public static final String PROP_ACCESS_TOKEN = "accessToken"; public static final String AUTH_SOURCE_BUILTIN_USER_STORE = "Builtin User Store"; public static final String AUTH_SOURCE_EXTERNAL_AUTHENTICATOR = "External Authenticator"; public static final String AUTH_SOURCE_SSO_PROVIDER = "SSO Provider: "; private static ThreadLocal<Stack<User>> stack = new ThreadLocal<Stack<User>>() { @Override protected Stack<User> initialValue() { return new Stack<User>(); } }; @Column(unique=true, nullable=false) private String name; @Column(length=1024, nullable=false) @JsonView(DefaultView.class) private String password; private String fullName; @Embedded private SsoInfo ssoInfo = new SsoInfo(); @Column(unique=true, nullable=false) private String email; @Column(unique=true, nullable=false) private String accessToken = RandomStringUtils.randomAlphanumeric(ACCESS_TOKEN_LEN); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) private Collection<UserAuthorization> authorizations = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) private Collection<Membership> memberships = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<PullRequestReview> pullRequestReviews = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<PullRequestAssignment> pullRequestAssignments = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<PullRequestWatch> pullRequestWatches = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<IssueWatch> issueWatches = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<IssueVote> issueVotes = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<IssueQuerySetting> projectIssueQuerySettings = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<BuildQuerySetting> projectBuildQuerySettings = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<PullRequestQuerySetting> projectPullRequestQuerySettings = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<CommitQuerySetting> projectCommitQuerySettings = new ArrayList<>(); @OneToMany(mappedBy="user", cascade=CascadeType.REMOVE) private Collection<CodeCommentQuerySetting> projectCodeCommentQuerySettings = new ArrayList<>(); @OneToMany(mappedBy="owner", cascade=CascadeType.REMOVE) @Cache(usage=CacheConcurrencyStrategy.READ_WRITE) private Collection<SshKey> sshKeys = new ArrayList<>(); @Lob @Column(nullable=false, length=65535) private ArrayList<NamedProjectQuery> userProjectQueries = new ArrayList<>(); @Lob @Column(nullable=false, length=65535) private ArrayList<NamedIssueQuery> userIssueQueries = new ArrayList<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashMap<String, Boolean> userIssueQueryWatches = new LinkedHashMap<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashMap<String, Boolean> issueQueryWatches = new LinkedHashMap<>(); @Lob @Column(nullable=false, length=65535) private ArrayList<NamedPullRequestQuery> userPullRequestQueries = new ArrayList<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashMap<String, Boolean> userPullRequestQueryWatches = new LinkedHashMap<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashMap<String, Boolean> pullRequestQueryWatches = new LinkedHashMap<>(); @Lob @Column(nullable=false, length=65535) private ArrayList<NamedBuildQuery> userBuildQueries = new ArrayList<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashSet<String> userBuildQuerySubscriptions = new LinkedHashSet<>(); @Lob @Column(nullable=false, length=65535) private LinkedHashSet<String> buildQuerySubscriptions = new LinkedHashSet<>(); private transient Collection<Group> groups; public QuerySetting<NamedProjectQuery> getProjectQuerySetting() { return new QuerySetting<NamedProjectQuery>() { @Override public Project getProject() { return null; } @Override public User getUser() { return User.this; } @Override public ArrayList<NamedProjectQuery> getUserQueries() { return userProjectQueries; } @Override public void setUserQueries(ArrayList<NamedProjectQuery> userQueries) { userProjectQueries = userQueries; } @Override public QueryWatchSupport<NamedProjectQuery> getQueryWatchSupport() { return null; } @Override public QuerySubscriptionSupport<NamedProjectQuery> getQuerySubscriptionSupport() { return null; } }; } public QuerySetting<NamedIssueQuery> getIssueQuerySetting() { return new QuerySetting<NamedIssueQuery>() { @Override public Project getProject() { return null; } @Override public User getUser() { return User.this; } @Override public ArrayList<NamedIssueQuery> getUserQueries() { return userIssueQueries; } @Override public void setUserQueries(ArrayList<NamedIssueQuery> userQueries) { userIssueQueries = userQueries; } @Override public QueryWatchSupport<NamedIssueQuery> getQueryWatchSupport() { return new QueryWatchSupport<NamedIssueQuery>() { @Override public LinkedHashMap<String, Boolean> getUserQueryWatches() { return userIssueQueryWatches; } @Override public LinkedHashMap<String, Boolean> getQueryWatches() { return issueQueryWatches; } }; } @Override public QuerySubscriptionSupport<NamedIssueQuery> getQuerySubscriptionSupport() { return null; } }; } public QuerySetting<NamedPullRequestQuery> getPullRequestQuerySetting() { return new QuerySetting<NamedPullRequestQuery>() { @Override public Project getProject() { return null; } @Override public User getUser() { return User.this; } @Override public ArrayList<NamedPullRequestQuery> getUserQueries() { return userPullRequestQueries; } @Override public void setUserQueries(ArrayList<NamedPullRequestQuery> userQueries) { userPullRequestQueries = userQueries; } @Override public QueryWatchSupport<NamedPullRequestQuery> getQueryWatchSupport() { return new QueryWatchSupport<NamedPullRequestQuery>() { @Override public LinkedHashMap<String, Boolean> getUserQueryWatches() { return userPullRequestQueryWatches; } @Override public LinkedHashMap<String, Boolean> getQueryWatches() { return pullRequestQueryWatches; } }; } @Override public QuerySubscriptionSupport<NamedPullRequestQuery> getQuerySubscriptionSupport() { return null; } }; } public QuerySetting<NamedBuildQuery> getBuildQuerySetting() { return new QuerySetting<NamedBuildQuery>() { @Override public Project getProject() { return null; } @Override public User getUser() { return User.this; } @Override public ArrayList<NamedBuildQuery> getUserQueries() { return userBuildQueries; } @Override public void setUserQueries(ArrayList<NamedBuildQuery> userQueries) { userBuildQueries = userQueries; } @Override public QueryWatchSupport<NamedBuildQuery> getQueryWatchSupport() { return null; } @Override public QuerySubscriptionSupport<NamedBuildQuery> getQuerySubscriptionSupport() { return new QuerySubscriptionSupport<NamedBuildQuery>() { @Override public LinkedHashSet<String> getUserQuerySubscriptions() { return userBuildQuerySubscriptions; } @Override public LinkedHashSet<String> getQuerySubscriptions() { return buildQuerySubscriptions; } }; } }; } @Override public PrincipalCollection getPrincipals() { return new SimplePrincipalCollection(getId(), ""); } @Override public Object getCredentials() { return password; } public Subject asSubject() { return SecurityUtils.asSubject(getId()); } @Editable(name="Login Name", order=100) @UserName @NotEmpty public String getName() { return name; } public void setName(String name) { this.name = name; } @Editable(order=150) @Password(confirmative=true, autoComplete="new-password") @NotEmpty public String getPassword() { return password; } /** * Set password of this user. * * @param password * password to set */ public void setPassword(String password) { this.password = password; } public boolean isExternalManaged() { return getPassword().equals(EXTERNAL_MANAGED); } @Editable(order=200) public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public SsoInfo getSsoInfo() { return ssoInfo; } public void setSsoInfo(SsoInfo ssoInfo) { this.ssoInfo = ssoInfo; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } @Editable(order=300) @NotEmpty @Email public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Collection<Membership> getMemberships() { return memberships; } public void setMemberships(Collection<Membership> memberships) { this.memberships = memberships; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", getName()) .toString(); } public PersonIdent asPerson() { if (isSystem()) return new PersonIdent(getDisplayName(), ""); else return new PersonIdent(getDisplayName(), getEmail()); } public String getDisplayName() { if (getFullName() != null) return getFullName(); else return getName(); } public boolean isRoot() { return ROOT_ID.equals(getId()); } public boolean isSystem() { return SYSTEM_ID.equals(getId()); } public Collection<UserAuthorization> getAuthorizations() { return authorizations; } public void setAuthorizations(Collection<UserAuthorization> authorizations) { this.authorizations = authorizations; } @Override public int compareTo(AbstractEntity entity) { User user = (User) entity; if (getDisplayName().equals(user.getDisplayName())) { return getId().compareTo(entity.getId()); } else { return getDisplayName().compareTo(user.getDisplayName()); } } public double getMatchScore(@Nullable String queryTerm) { double scoreOfName = MatchScoreUtils.getMatchScore(name, queryTerm); double scoreOfFullName = MatchScoreUtils.getMatchScore(fullName, queryTerm); return Math.max(scoreOfName, scoreOfFullName); } public Collection<Group> getGroups() { if (groups == null) groups = getMemberships().stream().map(it->it.getGroup()).collect(Collectors.toList()); return groups; } public static User from(@Nullable User user, @Nullable String displayName) { if (user == null) { user = new User(); if (displayName != null) user.setName(displayName); else user.setName("Unknown"); } return user; } public static void push(User user) { stack.get().push(user); } public static void pop() { stack.get().pop(); } @Nullable public static User get() { if (!stack.get().isEmpty()) return stack.get().peek(); else return SecurityUtils.getUser(); } public Collection<SshKey> getSshKeys() { return sshKeys; } public void setSshKeys(Collection<SshKey> sshKeys) { this.sshKeys = sshKeys; } public boolean isSshKeyExternalManaged() { if (isExternalManaged()) { if (getSsoInfo().getConnector() != null) { return false; } else { Authenticator authenticator = OneDev.getInstance(SettingManager.class).getAuthenticator(); return authenticator != null && authenticator.isManagingSshKeys(); } } else { return false; } } public boolean isMembershipExternalManaged() { if (isExternalManaged()) { SettingManager settingManager = OneDev.getInstance(SettingManager.class); if (getSsoInfo().getConnector() != null) { SsoConnector ssoConnector = settingManager.getSsoConnectors().stream() .filter(it->it.getName().equals(getSsoInfo().getConnector())) .findFirst().orElse(null); return ssoConnector != null && ssoConnector.isManagingMemberships(); } else { Authenticator authenticator = settingManager.getAuthenticator(); return authenticator != null && authenticator.isManagingMemberships(); } } else { return false; } } public String getAuthSource() { if (isExternalManaged()) { if (getSsoInfo().getConnector() != null) return AUTH_SOURCE_SSO_PROVIDER + getSsoInfo().getConnector(); else return AUTH_SOURCE_EXTERNAL_AUTHENTICATOR; } else { return AUTH_SOURCE_BUILTIN_USER_STORE; } } }
./CrossVul/dataset_final_sorted/CWE-862/java/bad_1897_0
crossvul-java_data_good_3889_0
package com.eebbk.greenbrowser.util; import android.content.Intent; import android.net.Uri; import android.webkit.WebView; import android.webkit.WebViewClient; @SuppressWarnings("unused") class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url); if (uri.getHost() != null && uri.getHost().endsWith(".example.com")) { return false; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); view.getContext().startActivity(intent); return true; } }
./CrossVul/dataset_final_sorted/CWE-862/java/good_3889_0
crossvul-java_data_good_1897_1
package io.onedev.server.rest; import java.util.Collection; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.shiro.authz.UnauthorizedException; import org.hibernate.criterion.Restrictions; import org.hibernate.validator.constraints.Email; import io.onedev.server.entitymanager.UserManager; import io.onedev.server.model.User; import io.onedev.server.persistence.dao.EntityCriteria; import io.onedev.server.rest.jersey.ValidQueryParams; import io.onedev.server.security.SecurityUtils; @Path("/users") @Consumes(MediaType.WILDCARD) @Produces(MediaType.APPLICATION_JSON) @Singleton public class UserResource { private final UserManager userManager; @Inject public UserResource(UserManager userManager) { this.userManager = userManager; } @ValidQueryParams @GET public Response query(@QueryParam("name") String name, @Email @QueryParam("email") String email, @QueryParam("offset") Integer offset, @QueryParam("count") Integer count, @Context UriInfo uriInfo) { if (!SecurityUtils.isAdministrator()) throw new UnauthorizedException("Unauthorized access to user profiles"); EntityCriteria<User> criteria = EntityCriteria.of(User.class); if (name != null) criteria.add(Restrictions.eq("name", name)); if (email != null) criteria.add(Restrictions.eq("email", email)); if (offset == null) offset = 0; if (count == null || count > RestConstants.PAGE_SIZE) count = RestConstants.PAGE_SIZE; Collection<User> users = userManager.query(criteria, offset, count); return Response.ok(users, RestConstants.JSON_UTF8).build(); } @GET @Path("/{userId}") public User get(@PathParam("userId") Long userId) { return userManager.load(userId); } }
./CrossVul/dataset_final_sorted/CWE-862/java/good_1897_1
crossvul-java_data_good_3133_0
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * 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 net.java.sip.communicator.impl.protocol.jabber; import java.util.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.carbon.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.mailnotification.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.messagecorrection.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.Message; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.service.protocol.jabberconstants.*; import net.java.sip.communicator.util.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.filter.*; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.provider.*; import org.jivesoftware.smack.util.*; import org.jivesoftware.smackx.*; import org.jivesoftware.smackx.packet.*; /** * A straightforward implementation of the basic instant messaging operation * set. * * @author Damian Minkov * @author Matthieu Helleringer * @author Alain Knaebel * @author Emil Ivov * @author Hristo Terezov */ public class OperationSetBasicInstantMessagingJabberImpl extends AbstractOperationSetBasicInstantMessaging implements OperationSetMessageCorrection { /** * Our class logger */ private static final Logger logger = Logger.getLogger(OperationSetBasicInstantMessagingJabberImpl.class); /** * The maximum number of unread threads that we'd be notifying the user of. */ private static final String PNAME_MAX_GMAIL_THREADS_PER_NOTIFICATION = "net.java.sip.communicator.impl.protocol.jabber." +"MAX_GMAIL_THREADS_PER_NOTIFICATION"; /** * A table mapping contact addresses to full jids that can be used to * target a specific resource (rather than sending a message to all logged * instances of a user). */ private Map<String, StoredThreadID> jids = new Hashtable<String, StoredThreadID>(); /** * The most recent full JID used for the contact address. */ private Map<String, String> recentJIDForAddress = new Hashtable<String, String>(); /** * The smackMessageListener instance listens for incoming messages. * Keep a reference of it so if anything goes wrong we don't add * two different instances. */ private SmackMessageListener smackMessageListener = null; /** * Contains the complete jid of a specific user and the time that it was * last used so that we could remove it after a certain point. */ public static class StoredThreadID { /** The time that we last sent or received a message from this jid */ long lastUpdatedTime; /** The last chat used, this way we will reuse the thread-id */ String threadID; } /** * A prefix helps to make sure that thread ID's are unique across mutliple * instances. */ private static String prefix = StringUtils.randomString(5); /** * Keeps track of the current increment, which is appended to the prefix to * forum a unique thread ID. */ private static long id = 0; /** * The number of milliseconds that we preserve threads with no traffic * before considering them dead. */ private static final long JID_INACTIVITY_TIMEOUT = 10*60*1000;//10 min. /** * Indicates the time of the last Mailbox report that we received from * Google (if this is a Google server we are talking to). Should be included * in all following mailbox queries */ private long lastReceivedMailboxResultTime = -1; /** * The provider that created us. */ private final ProtocolProviderServiceJabberImpl jabberProvider; /** * A reference to the persistent presence operation set that we use * to match incoming messages to <tt>Contact</tt>s and vice versa. */ private OperationSetPersistentPresenceJabberImpl opSetPersPresence = null; /** * The opening BODY HTML TAG: &ltbody&gt */ private static final String OPEN_BODY_TAG = "<body>"; /** * The closing BODY HTML TAG: &ltbody&gt */ private static final String CLOSE_BODY_TAG = "</body>"; /** * The html namespace used as feature * XHTMLManager.namespace */ private final static String HTML_NAMESPACE = "http://jabber.org/protocol/xhtml-im"; /** * List of filters to be used to filter which messages to handle * current Operation Set. */ private List<PacketFilter> packetFilters = new ArrayList<PacketFilter>(); /** * Whether carbon is enabled or not. */ private boolean isCarbonEnabled = false; /** * Creates an instance of this operation set. * @param provider a reference to the <tt>ProtocolProviderServiceImpl</tt> * that created us and that we'll use for retrieving the underlying aim * connection. */ OperationSetBasicInstantMessagingJabberImpl( ProtocolProviderServiceJabberImpl provider) { this.jabberProvider = provider; packetFilters.add(new GroupMessagePacketFilter()); packetFilters.add( new PacketTypeFilter(org.jivesoftware.smack.packet.Message.class)); provider.addRegistrationStateChangeListener( new RegistrationStateListener()); ProviderManager man = ProviderManager.getInstance(); MessageCorrectionExtensionProvider extProvider = new MessageCorrectionExtensionProvider(); man.addExtensionProvider(MessageCorrectionExtension.ELEMENT_NAME, MessageCorrectionExtension.NAMESPACE, extProvider); } /** * Create a Message instance with the specified UID, content type * and a default encoding. * This method can be useful when message correction is required. One can * construct the corrected message to have the same UID as the message * before correction. * * @param messageText the string content of the message. * @param contentType the MIME-type for <tt>content</tt> * @param messageUID the unique identifier of this message. * @return Message the newly created message */ public Message createMessageWithUID( String messageText, String contentType, String messageUID) { return new MessageJabberImpl(messageText, contentType, DEFAULT_MIME_ENCODING, null, messageUID); } /** * Create a Message instance for sending arbitrary MIME-encoding content. * * @param content content value * @param contentType the MIME-type for <tt>content</tt> * @return the newly created message. */ public Message createMessage(String content, String contentType) { return createMessage(content, contentType, DEFAULT_MIME_ENCODING, null); } /** * Create a Message instance for sending arbitrary MIME-encoding content. * * @param content content value * @param contentType the MIME-type for <tt>content</tt> * @param subject the Subject of the message that we'd like to create. * @param encoding the enconding of the message that we will be sending. * * @return the newly created message. */ @Override public Message createMessage(String content, String contentType, String encoding, String subject) { return new MessageJabberImpl(content, contentType, encoding, subject); } Message createMessage(String content, String contentType, String messageUID) { return new MessageJabberImpl(content, contentType, DEFAULT_MIME_ENCODING, null, messageUID); } /** * Determines wheter the protocol provider (or the protocol itself) support * sending and receiving offline messages. Most often this method would * return true for protocols that support offline messages and false for * those that don't. It is however possible for a protocol to support these * messages and yet have a particular account that does not (i.e. feature * not enabled on the protocol server). In cases like this it is possible * for this method to return true even when offline messaging is not * supported, and then have the sendMessage method throw an * OperationFailedException with code - OFFLINE_MESSAGES_NOT_SUPPORTED. * * @return <tt>true</tt> if the protocol supports offline messages and * <tt>false</tt> otherwise. */ public boolean isOfflineMessagingSupported() { return true; } /** * Determines wheter the protocol supports the supplied content type * * @param contentType the type we want to check * @return <tt>true</tt> if the protocol supports it and * <tt>false</tt> otherwise. */ public boolean isContentTypeSupported(String contentType) { return (contentType.equals(DEFAULT_MIME_TYPE) || contentType.equals(HTML_MIME_TYPE)); } /** * Determines whether the protocol supports the supplied content type * for the given contact. * * @param contentType the type we want to check * @param contact contact which is checked for supported contentType * @return <tt>true</tt> if the contact supports it and * <tt>false</tt> otherwise. */ @Override public boolean isContentTypeSupported(String contentType, Contact contact) { // by default we support default mime type, for other mimetypes // method must be overriden if(contentType.equals(DEFAULT_MIME_TYPE)) return true; else if(contentType.equals(HTML_MIME_TYPE)) { String toJID = recentJIDForAddress.get(contact.getAddress()); if (toJID == null) toJID = contact.getAddress(); return jabberProvider.isFeatureListSupported( toJID, HTML_NAMESPACE); } return false; } /** * Remove from our <tt>jids</tt> map all entries that have not seen any * activity (i.e. neither outgoing nor incoming messags) for more than * JID_INACTIVITY_TIMEOUT. Note that this method is not synchronous and that * it is only meant for use by the {@link #getThreadIDForAddress(String)} and * {@link #putJidForAddress(String, String)} */ private void purgeOldJids() { long currentTime = System.currentTimeMillis(); Iterator<Map.Entry<String, StoredThreadID>> entries = jids.entrySet().iterator(); while( entries.hasNext() ) { Map.Entry<String, StoredThreadID> entry = entries.next(); StoredThreadID target = entry.getValue(); if (currentTime - target.lastUpdatedTime > JID_INACTIVITY_TIMEOUT) entries.remove(); } } /** * Returns the last jid that the party with the specified <tt>address</tt> * contacted us from or <tt>null</tt>(or bare jid) if we don't have a jid * for the specified <tt>address</tt> yet. The method would also purge all * entries that haven't seen any activity (i.e. no one has tried to get or * remap it) for a delay longer than <tt>JID_INACTIVITY_TIMEOUT</tt>. * * @param jid the <tt>jid</tt> that we'd like to obtain a threadID for. * * @return the last jid that the party with the specified <tt>address</tt> * contacted us from or <tt>null</tt> if we don't have a jid for the * specified <tt>address</tt> yet. */ String getThreadIDForAddress(String jid) { synchronized(jids) { purgeOldJids(); StoredThreadID ta = jids.get(jid); if (ta == null) return null; ta.lastUpdatedTime = System.currentTimeMillis(); return ta.threadID; } } /** * Maps the specified <tt>address</tt> to <tt>jid</tt>. The point of this * method is to allow us to send all messages destined to the contact with * the specified <tt>address</tt> to the <tt>jid</tt> that they last * contacted us from. * * @param threadID the threadID of conversation. * @param jid the jid (i.e. address/resource) that the contact with the * specified <tt>address</tt> last contacted us from. */ private void putJidForAddress(String jid, String threadID) { synchronized(jids) { purgeOldJids(); StoredThreadID ta = jids.get(jid); if (ta == null) { ta = new StoredThreadID(); jids.put(jid, ta); } recentJIDForAddress.put(StringUtils.parseBareAddress(jid), jid); ta.lastUpdatedTime = System.currentTimeMillis(); ta.threadID = threadID; } } /** * Helper function used to send a message to a contact, with the given * extensions attached. * * @param to The contact to send the message to. * @param toResource The resource to send the message to or null if no * resource has been specified * @param message The message to send. * @param extensions The XMPP extensions that should be attached to the * message before sending. * @return The MessageDeliveryEvent that resulted after attempting to * send this message, so the calling function can modify it if needed. */ private MessageDeliveredEvent sendMessage( Contact to, ContactResource toResource, Message message, PacketExtension[] extensions) { if( !(to instanceof ContactJabberImpl) ) throw new IllegalArgumentException( "The specified contact is not a Jabber contact." + to); assertConnected(); org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message(); String toJID = null; if (toResource != null) { if(toResource.equals(ContactResource.BASE_RESOURCE)) { toJID = to.getAddress(); } else toJID = ((ContactResourceJabberImpl) toResource).getFullJid(); } if (toJID == null) { toJID = to.getAddress(); } msg.setPacketID(message.getMessageUID()); msg.setTo(toJID); for (PacketExtension ext : extensions) { msg.addExtension(ext); } if (logger.isTraceEnabled()) logger.trace("Will send a message to:" + toJID + " chat.jid=" + toJID); MessageDeliveredEvent msgDeliveryPendingEvt = new MessageDeliveredEvent(message, to, toResource); MessageDeliveredEvent[] transformedEvents = messageDeliveryPendingTransform(msgDeliveryPendingEvt); if (transformedEvents == null || transformedEvents.length == 0) return null; for (MessageDeliveredEvent event : transformedEvents) { String content = event.getSourceMessage().getContent(); if (message.getContentType().equals(HTML_MIME_TYPE)) { msg.setBody(Html2Text.extractText(content)); // Check if the other user supports XHTML messages // make sure we use our discovery manager as it caches calls if (jabberProvider .isFeatureListSupported(toJID, HTML_NAMESPACE)) { // Add the XHTML text to the message XHTMLManager.addBody(msg, OPEN_BODY_TAG + content + CLOSE_BODY_TAG); } } else { // this is plain text so keep it as it is. msg.setBody(content); } // msg.addExtension(new Version()); if (event.isMessageEncrypted() && isCarbonEnabled) { msg.addExtension(new CarbonPacketExtension.PrivateExtension()); } MessageEventManager.addNotificationsRequests(msg, true, false, false, true); String threadID = getThreadIDForAddress(toJID); if (threadID == null) threadID = nextThreadID(); msg.setThread(threadID); msg.setType(org.jivesoftware.smack.packet.Message.Type.chat); msg.setFrom(jabberProvider.getConnection().getUser()); jabberProvider.getConnection().sendPacket(msg); putJidForAddress(toJID, threadID); } return new MessageDeliveredEvent(message, to, toResource); } /** * Sends the <tt>message</tt> to the destination indicated by the * <tt>to</tt> contact. * * @param to the <tt>Contact</tt> to send <tt>message</tt> to * @param message the <tt>Message</tt> to send. * @throws java.lang.IllegalStateException if the underlying stack is * not registered and initialized. * @throws java.lang.IllegalArgumentException if <tt>to</tt> is not an * instance of ContactImpl. */ public void sendInstantMessage(Contact to, Message message) throws IllegalStateException, IllegalArgumentException { sendInstantMessage(to, null, message); } /** * Sends the <tt>message</tt> to the destination indicated by the * <tt>to</tt>. Provides a default implementation of this method. * * @param to the <tt>Contact</tt> to send <tt>message</tt> to * @param toResource the resource to which the message should be send * @param message the <tt>Message</tt> to send. * @throws java.lang.IllegalStateException if the underlying ICQ stack is * not registered and initialized. * @throws java.lang.IllegalArgumentException if <tt>to</tt> is not an * instance belonging to the underlying implementation. */ @Override public void sendInstantMessage( Contact to, ContactResource toResource, Message message) throws IllegalStateException, IllegalArgumentException { MessageDeliveredEvent msgDelivered = sendMessage(to, toResource, message, new PacketExtension[0]); fireMessageEvent(msgDelivered); } /** * Replaces the message with ID <tt>correctedMessageUID</tt> sent to * the contact <tt>to</tt> with the message <tt>message</tt> * * @param to The contact to send the message to. * @param message The new message. * @param correctedMessageUID The ID of the message being replaced. */ public void correctMessage( Contact to, ContactResource resource, Message message, String correctedMessageUID) { PacketExtension[] exts = new PacketExtension[1]; exts[0] = new MessageCorrectionExtension(correctedMessageUID); MessageDeliveredEvent msgDelivered = sendMessage(to, resource, message, exts); msgDelivered.setCorrectedMessageUID(correctedMessageUID); fireMessageEvent(msgDelivered); } /** * Utility method throwing an exception if the stack is not properly * initialized. * * @throws java.lang.IllegalStateException if the underlying stack is * not registered and initialized. */ private void assertConnected() throws IllegalStateException { if (opSetPersPresence == null) { throw new IllegalStateException( "The provider must be signed on the service before" + " being able to communicate."); } else opSetPersPresence.assertConnected(); } /** * Our listener that will tell us when we're registered to */ private class RegistrationStateListener implements RegistrationStateChangeListener { /** * The method is called by a ProtocolProvider implementation whenever * a change in the registration state of the corresponding provider had * occurred. * @param evt ProviderStatusChangeEvent the event describing the status * change. */ public void registrationStateChanged(RegistrationStateChangeEvent evt) { if (logger.isDebugEnabled()) logger.debug("The provider changed state from: " + evt.getOldState() + " to: " + evt.getNewState()); if (evt.getNewState() == RegistrationState.REGISTERING) { opSetPersPresence = (OperationSetPersistentPresenceJabberImpl) jabberProvider.getOperationSet( OperationSetPersistentPresence.class); if(smackMessageListener == null) { smackMessageListener = new SmackMessageListener(); } else { // make sure this listener is not already installed in this // connection jabberProvider.getConnection() .removePacketListener(smackMessageListener); } jabberProvider.getConnection().addPacketListener( smackMessageListener, new AndFilter( packetFilters.toArray( new PacketFilter[packetFilters.size()]))); } else if (evt.getNewState() == RegistrationState.REGISTERED) { new Thread(new Runnable() { @Override public void run() { initAdditionalServices(); } }).start(); } else if(evt.getNewState() == RegistrationState.UNREGISTERED || evt.getNewState() == RegistrationState.CONNECTION_FAILED || evt.getNewState() == RegistrationState.AUTHENTICATION_FAILED) { if(jabberProvider.getConnection() != null) { if(smackMessageListener != null) jabberProvider.getConnection().removePacketListener( smackMessageListener); } smackMessageListener = null; } } } /** * Initialize additional services, like gmail notifications and message * carbons. */ private void initAdditionalServices() { //subscribe for Google (Gmail or Google Apps) notifications //for new mail messages. boolean enableGmailNotifications = jabberProvider .getAccountID() .getAccountPropertyBoolean( "GMAIL_NOTIFICATIONS_ENABLED", false); if (enableGmailNotifications) subscribeForGmailNotifications(); boolean enableCarbon = isCarbonSupported() && !jabberProvider.getAccountID() .getAccountPropertyBoolean( ProtocolProviderFactory.IS_CARBON_DISABLED, false); if(enableCarbon) { enableDisableCarbon(true); } else { isCarbonEnabled = false; } } /** * Sends enable or disable carbon packet to the server. * @param enable if <tt>true</tt> sends enable packet otherwise sends * disable packet. */ private void enableDisableCarbon(final boolean enable) { IQ iq = new IQ(){ @Override public String getChildElementXML() { return "<" + (enable? "enable" : "disable") + " xmlns='urn:xmpp:carbons:2' />"; } }; Packet response = null; try { PacketCollector packetCollector = jabberProvider.getConnection().createPacketCollector( new PacketIDFilter(iq.getPacketID())); iq.setFrom(jabberProvider.getOurJID()); iq.setType(IQ.Type.SET); jabberProvider.getConnection().sendPacket(iq); response = packetCollector.nextResult( SmackConfiguration.getPacketReplyTimeout()); packetCollector.cancel(); } catch(Exception e) { logger.error("Failed to enable carbon.", e); } isCarbonEnabled = false; if (response == null) { logger.error( "Failed to enable carbon. No response is received."); } else if (response.getError() != null) { logger.error( "Failed to enable carbon: " + response.getError()); } else if (!(response instanceof IQ) || !((IQ) response).getType().equals(IQ.Type.RESULT)) { logger.error( "Failed to enable carbon. The response is not correct."); } else { isCarbonEnabled = true; } } /** * Checks whether the carbon is supported by the server or not. * @return <tt>true</tt> if carbon is supported by the server and * <tt>false</tt> if not. */ private boolean isCarbonSupported() { try { return jabberProvider.getDiscoveryManager().discoverInfo( jabberProvider.getAccountID().getService()) .containsFeature(CarbonPacketExtension.NAMESPACE); } catch (XMPPException e) { logger.warn("Failed to retrieve carbon support." + e.getMessage()); } return false; } /** * The listener that we use in order to handle incoming messages. */ @SuppressWarnings("unchecked") private class SmackMessageListener implements PacketListener { /** * Handles incoming messages and dispatches whatever events are * necessary. * @param packet the packet that we need to handle (if it is a message). */ public void processPacket(Packet packet) { if(!(packet instanceof org.jivesoftware.smack.packet.Message)) return; org.jivesoftware.smack.packet.Message msg = (org.jivesoftware.smack.packet.Message)packet; boolean isForwardedSentMessage = false; if(msg.getBody() == null) { CarbonPacketExtension carbonExt = (CarbonPacketExtension) msg.getExtension( CarbonPacketExtension.NAMESPACE); if(carbonExt == null) return; isForwardedSentMessage = (carbonExt.getElementName() == CarbonPacketExtension.SENT_ELEMENT_NAME); List<ForwardedPacketExtension> extensions = carbonExt.getChildExtensionsOfType( ForwardedPacketExtension.class); if(extensions.isEmpty()) return; // according to xep-0280 all carbons should come from // our bare jid if (!msg.getFrom().equals( StringUtils.parseBareAddress( jabberProvider.getOurJID()))) { logger.info("Received a carbon copy with wrong from!"); return; } ForwardedPacketExtension forwardedExt = extensions.get(0); msg = forwardedExt.getMessage(); if(msg == null || msg.getBody() == null) return; } Object multiChatExtension = msg.getExtension("x", "http://jabber.org/protocol/muc#user"); // its not for us if(multiChatExtension != null) return; String userFullId = isForwardedSentMessage? msg.getTo() : msg.getFrom(); String userBareID = StringUtils.parseBareAddress(userFullId); boolean isPrivateMessaging = false; ChatRoom privateContactRoom = null; OperationSetMultiUserChatJabberImpl mucOpSet = (OperationSetMultiUserChatJabberImpl)jabberProvider .getOperationSet(OperationSetMultiUserChat.class); if(mucOpSet != null) privateContactRoom = mucOpSet.getChatRoom(userBareID); if(privateContactRoom != null) { isPrivateMessaging = true; } if(logger.isDebugEnabled()) { if (logger.isDebugEnabled()) logger.debug("Received from " + userBareID + " the message " + msg.toXML()); } Message newMessage = createMessage(msg.getBody(), DEFAULT_MIME_TYPE, msg.getPacketID()); //check if the message is available in xhtml PacketExtension ext = msg.getExtension( "http://jabber.org/protocol/xhtml-im"); if(ext != null) { XHTMLExtension xhtmlExt = (XHTMLExtension)ext; //parse all bodies Iterator<String> bodies = xhtmlExt.getBodies(); StringBuffer messageBuff = new StringBuffer(); while (bodies.hasNext()) { String body = bodies.next(); messageBuff.append(body); } if (messageBuff.length() > 0) { // we remove body tags around message cause their // end body tag is breaking // the visualization as html in the UI String receivedMessage = messageBuff.toString() // removes body start tag .replaceAll("\\<[bB][oO][dD][yY].*?>","") // removes body end tag .replaceAll("\\</[bB][oO][dD][yY].*?>",""); // for some reason &apos; is not rendered correctly // from our ui, lets use its equivalent. Other // similar chars(< > & ") seem ok. receivedMessage = receivedMessage.replaceAll("&apos;", "&#39;"); newMessage = createMessage(receivedMessage, HTML_MIME_TYPE, msg.getPacketID()); } } PacketExtension correctionExtension = msg.getExtension(MessageCorrectionExtension.NAMESPACE); String correctedMessageUID = null; if (correctionExtension != null) { correctedMessageUID = ((MessageCorrectionExtension) correctionExtension).getCorrectedMessageUID(); } Contact sourceContact = opSetPersPresence.findContactByID( (isPrivateMessaging? userFullId : userBareID)); if(msg.getType() == org.jivesoftware.smack.packet.Message.Type.error) { // error which is multichat and we don't know about the contact // is a muc message error which is missing muc extension // and is coming from the room, when we try to send message to // room which was deleted or offline on the server if(isPrivateMessaging && sourceContact == null) { if(privateContactRoom != null) { XMPPError error = packet.getError(); int errorResultCode = ChatRoomMessageDeliveryFailedEvent.UNKNOWN_ERROR; if(error != null && error.getCode() == 403) { errorResultCode = ChatRoomMessageDeliveryFailedEvent.FORBIDDEN; } String errorReason = error.getMessage(); ChatRoomMessageDeliveryFailedEvent evt = new ChatRoomMessageDeliveryFailedEvent( privateContactRoom, null, errorResultCode, errorReason, new Date(), newMessage); ((ChatRoomJabberImpl)privateContactRoom) .fireMessageEvent(evt); } return; } if (logger.isInfoEnabled()) logger.info("Message error received from " + userBareID); int errorResultCode = MessageDeliveryFailedEvent.UNKNOWN_ERROR; if (packet.getError() != null) { int errorCode = packet.getError().getCode(); if(errorCode == 503) { org.jivesoftware.smackx.packet.MessageEvent msgEvent = (org.jivesoftware.smackx.packet.MessageEvent) packet.getExtension("x", "jabber:x:event"); if(msgEvent != null && msgEvent.isOffline()) { errorResultCode = MessageDeliveryFailedEvent .OFFLINE_MESSAGES_NOT_SUPPORTED; } } } if (sourceContact == null) { sourceContact = opSetPersPresence.createVolatileContact( userFullId, isPrivateMessaging); } MessageDeliveryFailedEvent ev = new MessageDeliveryFailedEvent(newMessage, sourceContact, correctedMessageUID, errorResultCode); // ev = messageDeliveryFailedTransform(ev); if (ev != null) fireMessageEvent(ev); return; } putJidForAddress(userFullId, msg.getThread()); // In the second condition we filter all group chat messages, // because they are managed by the multi user chat operation set. if(sourceContact == null) { if (logger.isDebugEnabled()) logger.debug("received a message from an unknown contact: " + userBareID); //create the volatile contact sourceContact = opSetPersPresence .createVolatileContact( userFullId, isPrivateMessaging); } Date timestamp = new Date(); //Check for XEP-0091 timestamp (deprecated) PacketExtension delay = msg.getExtension("x", "jabber:x:delay"); if(delay != null && delay instanceof DelayInformation) { timestamp = ((DelayInformation)delay).getStamp(); } //check for XEP-0203 timestamp delay = msg.getExtension("delay", "urn:xmpp:delay"); if(delay != null && delay instanceof DelayInfo) { timestamp = ((DelayInfo)delay).getStamp(); } ContactResource resource = ((ContactJabberImpl) sourceContact) .getResourceFromJid(userFullId); EventObject msgEvt = null; if(!isForwardedSentMessage) msgEvt = new MessageReceivedEvent( newMessage, sourceContact, resource, timestamp, correctedMessageUID, isPrivateMessaging, privateContactRoom); else msgEvt = new MessageDeliveredEvent(newMessage, sourceContact, timestamp); // msgReceivedEvt = messageReceivedTransform(msgReceivedEvt); if (msgEvt != null) fireMessageEvent(msgEvt); } } /** * A filter that prevents this operation set from handling multi user chat * messages. */ private static class GroupMessagePacketFilter implements PacketFilter { /** * Returns <tt>true</tt> if <tt>packet</tt> is a <tt>Message</tt> and * false otherwise. * * @param packet the packet that we need to check. * * @return <tt>true</tt> if <tt>packet</tt> is a <tt>Message</tt> and * false otherwise. */ public boolean accept(Packet packet) { if(!(packet instanceof org.jivesoftware.smack.packet.Message)) return false; org.jivesoftware.smack.packet.Message msg = (org.jivesoftware.smack.packet.Message) packet; return !msg.getType().equals( org.jivesoftware.smack.packet.Message.Type.groupchat); } } /** * Subscribes this provider as interested in receiving notifications for * new mail messages from Google mail services such as Gmail or Google Apps. */ private void subscribeForGmailNotifications() { // first check support for the notification service String accountIDService = jabberProvider.getAccountID().getService(); boolean notificationsAreSupported = jabberProvider.isFeatureSupported( accountIDService, NewMailNotificationIQ.NAMESPACE); if (!notificationsAreSupported) { if (logger.isDebugEnabled()) logger.debug(accountIDService +" does not seem to provide a Gmail notification " +" service so we won't be trying to subscribe for it"); return; } if (logger.isDebugEnabled()) logger.debug(accountIDService +" seems to provide a Gmail notification " +" service so we will try to subscribe for it"); ProviderManager providerManager = ProviderManager.getInstance(); providerManager.addIQProvider( MailboxIQ.ELEMENT_NAME, MailboxIQ.NAMESPACE, new MailboxIQProvider()); providerManager.addIQProvider( NewMailNotificationIQ.ELEMENT_NAME, NewMailNotificationIQ.NAMESPACE, new NewMailNotificationProvider()); Connection connection = jabberProvider.getConnection(); connection.addPacketListener( new MailboxIQListener(), new PacketTypeFilter(MailboxIQ.class)); connection.addPacketListener( new NewMailNotificationListener(), new PacketTypeFilter(NewMailNotificationIQ.class)); if(opSetPersPresence.getCurrentStatusMessage().equals( JabberStatusEnum.OFFLINE)) return; //create a query with -1 values for newer-than-tid and //newer-than-time attributes MailboxQueryIQ mailboxQuery = new MailboxQueryIQ(); if (logger.isTraceEnabled()) logger.trace("sending mailNotification for acc: " + jabberProvider.getAccountID().getAccountUniqueID()); jabberProvider.getConnection().sendPacket(mailboxQuery); } /** * Creates an html description of the specified mailbox. * * @param mailboxIQ the mailboxIQ that we are to describe. * * @return an html description of <tt>mailboxIQ</tt> */ private String createMailboxDescription(MailboxIQ mailboxIQ) { int threadCount = mailboxIQ.getThreadCount(); String resourceHeaderKey = threadCount > 1 ? "service.gui.NEW_GMAIL_MANY_HEADER" : "service.gui.NEW_GMAIL_HEADER"; String resourceFooterKey = threadCount > 1 ? "service.gui.NEW_GMAIL_MANY_FOOTER" : "service.gui.NEW_GMAIL_FOOTER"; // FIXME Escape HTML! String newMailHeader = JabberActivator.getResources().getI18NString( resourceHeaderKey, new String[] { jabberProvider.getAccountID() .getService(), //{0} - service name mailboxIQ.getUrl(), //{1} - inbox URI Integer.toString( threadCount )//{2} - thread count }); StringBuilder message = new StringBuilder(newMailHeader); //we now start an html table for the threads. message.append("<table width=100% cellpadding=2 cellspacing=0 "); message.append("border=0 bgcolor=#e8eef7>"); Iterator<MailThreadInfo> threads = mailboxIQ.threads(); String maxThreadsStr = (String)JabberActivator.getConfigurationService() .getProperty(PNAME_MAX_GMAIL_THREADS_PER_NOTIFICATION); int maxThreads = 5; try { if(maxThreadsStr != null) maxThreads = Integer.parseInt(maxThreadsStr); } catch (NumberFormatException e) { if (logger.isDebugEnabled()) logger.debug("Failed to parse max threads count: "+maxThreads +". Going for default."); } //print a maximum of MAX_THREADS for (int i = 0; i < maxThreads && threads.hasNext(); i++) { message.append(threads.next().createHtmlDescription()); } message.append("</table><br/>"); if(threadCount > maxThreads) { String messageFooter = JabberActivator.getResources().getI18NString( resourceFooterKey, new String[] { mailboxIQ.getUrl(), //{0} - inbox URI Integer.toString( threadCount - maxThreads )//{1} - thread count }); message.append(messageFooter); } return message.toString(); } public String getRecentJIDForAddress(String address) { return recentJIDForAddress.get(address); } /** * Receives incoming MailNotification Packets */ private class MailboxIQListener implements PacketListener { /** * Handles incoming <tt>MailboxIQ</tt> packets. * * @param packet the IQ that we need to handle in case it is a * <tt>MailboxIQ</tt>. */ public void processPacket(Packet packet) { if(packet != null && !(packet instanceof MailboxIQ)) return; MailboxIQ mailboxIQ = (MailboxIQ) packet; if(mailboxIQ.getTotalMatched() < 1) return; //Get a reference to a dummy volatile contact Contact sourceContact = opSetPersPresence .findContactByID(jabberProvider.getAccountID().getService()); if(sourceContact == null) sourceContact = opSetPersPresence.createVolatileContact( jabberProvider.getAccountID().getService()); lastReceivedMailboxResultTime = mailboxIQ.getResultTime(); String newMail = createMailboxDescription(mailboxIQ); Message newMailMessage = new MessageJabberImpl( newMail, HTML_MIME_TYPE, DEFAULT_MIME_ENCODING, null); MessageReceivedEvent msgReceivedEvt = new MessageReceivedEvent( newMailMessage, sourceContact, new Date(), MessageReceivedEvent.SYSTEM_MESSAGE_RECEIVED); fireMessageEvent(msgReceivedEvt); } } /** * Receives incoming NewMailNotification Packets. */ private class NewMailNotificationListener implements PacketListener { /** * Handles incoming <tt>NewMailNotificationIQ</tt> packets. * * @param packet the IQ that we need to handle in case it is a * <tt>NewMailNotificationIQ</tt>. */ public void processPacket(Packet packet) { if(packet != null && !(packet instanceof NewMailNotificationIQ)) return; //check whether we are still enabled. boolean enableGmailNotifications = jabberProvider .getAccountID() .getAccountPropertyBoolean( "GMAIL_NOTIFICATIONS_ENABLED", false); if (!enableGmailNotifications) return; if(opSetPersPresence.getCurrentStatusMessage() .equals(JabberStatusEnum.OFFLINE)) return; MailboxQueryIQ mailboxQueryIQ = new MailboxQueryIQ(); if(lastReceivedMailboxResultTime != -1) mailboxQueryIQ.setNewerThanTime( lastReceivedMailboxResultTime); if (logger.isTraceEnabled()) logger.trace( "send mailNotification for acc: " + jabberProvider.getAccountID().getAccountUniqueID()); jabberProvider.getConnection().sendPacket(mailboxQueryIQ); } } /** * Returns the inactivity timeout in milliseconds. * * @return The inactivity timeout in milliseconds. Or -1 if undefined */ public long getInactivityTimeout() { return JID_INACTIVITY_TIMEOUT; } /** * Adds additional filters for incoming messages. To be able to skip some * messages. * @param filter to add */ public void addMessageFilters(PacketFilter filter) { this.packetFilters.add(filter); } /** * Returns the next unique thread id. Each thread id made up of a short * alphanumeric prefix along with a unique numeric value. * * @return the next thread id. */ public static synchronized String nextThreadID() { return prefix + Long.toString(id++); } }
./CrossVul/dataset_final_sorted/CWE-346/java/good_3133_0
crossvul-java_data_bad_4353_0
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.kernel.http.impl; import org.opencastproject.kernel.http.api.HttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** Implementation of HttpClient that makes http requests. */ public class HttpClientImpl implements HttpClient { /** The logging facility */ private static final Logger logger = LoggerFactory.getLogger(HttpClientImpl.class); /** client used for all http requests. */ private DefaultHttpClient defaultHttpClient = makeHttpClient(); /** See org.opencastproject.kernel.http.api.HttpClient */ @Override public HttpParams getParams() { return defaultHttpClient.getParams(); } /** See org.opencastproject.kernel.http.api.HttpClient */ @Override public CredentialsProvider getCredentialsProvider() { return defaultHttpClient.getCredentialsProvider(); } /** See org.opencastproject.kernel.http.api.HttpClient */ @Override public HttpResponse execute(HttpUriRequest httpUriRequest) throws IOException { return defaultHttpClient.execute(httpUriRequest); } /** See org.opencastproject.kernel.http.api.HttpClient */ @Override public ClientConnectionManager getConnectionManager() { return defaultHttpClient.getConnectionManager(); } /** * Creates a new client that can deal with all kinds of oddities with regards to http/https connections. * * @return the client */ private DefaultHttpClient makeHttpClient() { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); try { logger.debug("Installing forgiving hostname verifier and trust managers"); X509TrustManager trustManager = createTrustManager(); X509HostnameVerifier hostNameVerifier = createHostNameVerifier(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom()); SSLSocketFactory ssf = new SSLSocketFactory(sslContext, hostNameVerifier); ClientConnectionManager ccm = defaultHttpClient.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); } catch (NoSuchAlgorithmException e) { logger.error("Error creating context to handle TLS connections: {}", e.getMessage()); } catch (KeyManagementException e) { logger.error("Error creating context to handle TLS connections: {}", e.getMessage()); } return defaultHttpClient; } /** * Returns a new trust manager which will be in charge of checking the SSL certificates that are being presented by * SSL enabled hosts. * * @return the trust manager */ private X509TrustManager createTrustManager() { X509TrustManager trustManager = new X509TrustManager() { /** * {@InheritDoc} * * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[], java.lang.String) */ public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { logger.trace("Skipping trust check on client certificate {}", string); } /** * {@InheritDoc} * * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[], java.lang.String) */ public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { logger.trace("Skipping trust check on server certificate {}", string); } /** * {@InheritDoc} * * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() */ public X509Certificate[] getAcceptedIssuers() { logger.trace("Returning empty list of accepted issuers"); return null; } }; return trustManager; } /** * Creates a host name verifier that will make sure the SSL host's name matches the name in the SSL certificate. * * @return the host name verifier */ private X509HostnameVerifier createHostNameVerifier() { X509HostnameVerifier verifier = new X509HostnameVerifier() { /** * {@InheritDoc} * * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSocket) */ public void verify(String host, SSLSocket ssl) throws IOException { logger.trace("Skipping SSL host name check on {}", host); } /** * {@InheritDoc} * * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.security.cert.X509Certificate) */ public void verify(String host, X509Certificate xc) throws SSLException { logger.trace("Skipping X509 certificate host name check on {}", host); } /** * {@InheritDoc} * * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.lang.String[], * java.lang.String[]) */ public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { logger.trace("Skipping DNS host name check on {}", host); } /** * {@InheritDoc} * * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String, javax.net.ssl.SSLSession) */ public boolean verify(String host, SSLSession ssl) { logger.trace("Skipping SSL session host name check on {}", host); return true; } }; return verifier; } }
./CrossVul/dataset_final_sorted/CWE-346/java/bad_4353_0
crossvul-java_data_good_4353_0
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.kernel.http.impl; import org.opencastproject.kernel.http.api.HttpClient; import org.apache.http.HttpResponse; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** Implementation of HttpClient that makes http requests. */ public class HttpClientImpl implements HttpClient { /** The logging facility */ private static final Logger logger = LoggerFactory.getLogger(HttpClientImpl.class); /** client used for all http requests. */ private DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); /** See org.opencastproject.kernel.http.api.HttpClient */ @Override public HttpParams getParams() { return defaultHttpClient.getParams(); } /** See org.opencastproject.kernel.http.api.HttpClient */ @Override public CredentialsProvider getCredentialsProvider() { return defaultHttpClient.getCredentialsProvider(); } /** See org.opencastproject.kernel.http.api.HttpClient */ @Override public HttpResponse execute(HttpUriRequest httpUriRequest) throws IOException { return defaultHttpClient.execute(httpUriRequest); } /** See org.opencastproject.kernel.http.api.HttpClient */ @Override public ClientConnectionManager getConnectionManager() { return defaultHttpClient.getConnectionManager(); } }
./CrossVul/dataset_final_sorted/CWE-346/java/good_4353_0
crossvul-java_data_bad_3124_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-346/java/bad_3124_0
crossvul-java_data_good_3124_0
package org.yaxim.androidclient.service; import java.io.File; import java.text.Collator; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Map; import javax.net.ssl.SSLContext; import javax.net.ssl.X509TrustManager; import de.duenndns.ssl.MemorizingTrustManager; import org.jivesoftware.smack.AccountManager; import org.jivesoftware.smack.Connection; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.RosterGroup; import org.jivesoftware.smack.RosterListener; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ.Type; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.Presence.Mode; import org.jivesoftware.smack.packet.RosterPacket; import org.jivesoftware.smack.provider.ProviderManager; import org.jivesoftware.smack.util.DNSUtil; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smack.util.dns.DNSJavaResolver; import org.jivesoftware.smackx.entitycaps.EntityCapsManager; import org.jivesoftware.smackx.entitycaps.cache.SimpleDirectoryPersistentCache; import org.jivesoftware.smackx.Form; import org.jivesoftware.smackx.FormField; import org.jivesoftware.smackx.GroupChatInvitation; import org.jivesoftware.smackx.ServiceDiscoveryManager; import org.jivesoftware.smackx.muc.DiscussionHistory; import org.jivesoftware.smackx.muc.InvitationListener; import org.jivesoftware.smackx.muc.MultiUserChat; import org.jivesoftware.smackx.muc.Occupant; import org.jivesoftware.smackx.muc.RoomInfo; import org.jivesoftware.smackx.carbons.Carbon; import org.jivesoftware.smackx.carbons.CarbonManager; import org.jivesoftware.smackx.entitycaps.provider.CapsExtensionProvider; import org.jivesoftware.smackx.forward.Forwarded; import org.jivesoftware.smackx.muc.MultiUserChat; import org.jivesoftware.smackx.provider.DataFormProvider; import org.jivesoftware.smackx.provider.DelayInfoProvider; import org.jivesoftware.smackx.provider.DiscoverInfoProvider; import org.jivesoftware.smackx.provider.DiscoverItemsProvider; import org.jivesoftware.smackx.provider.MUCAdminProvider; import org.jivesoftware.smackx.provider.MUCOwnerProvider; import org.jivesoftware.smackx.provider.MUCUserProvider; import org.jivesoftware.smackx.packet.DelayInformation; import org.jivesoftware.smackx.packet.DelayInfo; import org.jivesoftware.smackx.packet.DiscoverInfo; import org.jivesoftware.smackx.packet.MUCUser; import org.jivesoftware.smackx.packet.Version; import org.jivesoftware.smackx.ping.PingManager; import org.jivesoftware.smackx.ping.packet.*; import org.jivesoftware.smackx.ping.provider.PingProvider; import org.jivesoftware.smackx.receipts.DeliveryReceipt; import org.jivesoftware.smackx.receipts.DeliveryReceiptManager; import org.jivesoftware.smackx.receipts.DeliveryReceiptRequest; import org.jivesoftware.smackx.receipts.ReceiptReceivedListener; import org.yaxim.androidclient.YaximApplication; import org.yaxim.androidclient.data.ChatHelper; import org.yaxim.androidclient.data.ChatProvider; import org.yaxim.androidclient.data.ChatRoomHelper; import org.yaxim.androidclient.data.RosterProvider; import org.yaxim.androidclient.data.YaximConfiguration; import org.yaxim.androidclient.data.ChatProvider.ChatConstants; import org.yaxim.androidclient.data.RosterProvider.RosterConstants; import org.yaxim.androidclient.exceptions.YaximXMPPException; import org.yaxim.androidclient.packet.PreAuth; import org.yaxim.androidclient.packet.Replace; import org.yaxim.androidclient.util.ConnectionState; import org.yaxim.androidclient.util.LogConstants; import org.yaxim.androidclient.util.PreferenceConstants; import org.yaxim.androidclient.util.StatusMode; import org.yaxim.androidclient.R; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.net.Uri; import android.telephony.gsm.SmsMessage.MessageClass; import android.text.TextUtils; import android.util.Log; public class SmackableImp implements Smackable { final static private String TAG = "yaxim.SmackableImp"; final static private int PACKET_TIMEOUT = 30000; final static private String[] SEND_OFFLINE_PROJECTION = new String[] { ChatConstants._ID, ChatConstants.JID, ChatConstants.MESSAGE, ChatConstants.DATE, ChatConstants.PACKET_ID }; final static private String SEND_OFFLINE_SELECTION = ChatConstants.DIRECTION + " = " + ChatConstants.OUTGOING + " AND " + ChatConstants.DELIVERY_STATUS + " = " + ChatConstants.DS_NEW; static final DiscoverInfo.Identity YAXIM_IDENTITY = new DiscoverInfo.Identity("client", YaximApplication.XMPP_IDENTITY_NAME, YaximApplication.XMPP_IDENTITY_TYPE); static File capsCacheDir = null; ///< this is used to cache if we already initialized EntityCapsCache static { registerSmackProviders(); DNSUtil.setDNSResolver(DNSJavaResolver.getInstance()); // initialize smack defaults before any connections are created SmackConfiguration.setPacketReplyTimeout(PACKET_TIMEOUT); SmackConfiguration.setDefaultPingInterval(0); } static void registerSmackProviders() { ProviderManager pm = ProviderManager.getInstance(); // add IQ handling pm.addIQProvider("query","http://jabber.org/protocol/disco#info", new DiscoverInfoProvider()); pm.addIQProvider("query","http://jabber.org/protocol/disco#items", new DiscoverItemsProvider()); // add delayed delivery notifications pm.addExtensionProvider("delay","urn:xmpp:delay", new DelayInfoProvider()); pm.addExtensionProvider("x","jabber:x:delay", new DelayInfoProvider()); // add XEP-0092 Software Version pm.addIQProvider("query", Version.NAMESPACE, new Version.Provider()); // data forms pm.addExtensionProvider("x","jabber:x:data", new DataFormProvider()); // add carbons and forwarding pm.addExtensionProvider("forwarded", Forwarded.NAMESPACE, new Forwarded.Provider()); pm.addExtensionProvider("sent", Carbon.NAMESPACE, new Carbon.Provider()); pm.addExtensionProvider("received", Carbon.NAMESPACE, new Carbon.Provider()); // add delivery receipts pm.addExtensionProvider(DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider()); pm.addExtensionProvider(DeliveryReceiptRequest.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceiptRequest.Provider()); // add XMPP Ping (XEP-0199) pm.addIQProvider("ping","urn:xmpp:ping", new PingProvider()); ServiceDiscoveryManager.setDefaultIdentity(YAXIM_IDENTITY); // XEP-0115 Entity Capabilities pm.addExtensionProvider("c", "http://jabber.org/protocol/caps", new CapsExtensionProvider()); // XEP-0308 Last Message Correction pm.addExtensionProvider("replace", Replace.NAMESPACE, new Replace.Provider()); // XEP-XXXX Pre-Authenticated Roster Subscription pm.addExtensionProvider("preauth", PreAuth.NAMESPACE, new PreAuth.Provider()); // MUC User pm.addExtensionProvider("x","http://jabber.org/protocol/muc#user", new MUCUserProvider()); // MUC direct invitation pm.addExtensionProvider("x","jabber:x:conference", new GroupChatInvitation.Provider()); // MUC Admin pm.addIQProvider("query","http://jabber.org/protocol/muc#admin", new MUCAdminProvider()); // MUC Owner pm.addIQProvider("query","http://jabber.org/protocol/muc#owner", new MUCOwnerProvider()); XmppStreamHandler.addExtensionProviders(); } private final YaximConfiguration mConfig; private ConnectionConfiguration mXMPPConfig; private XmppStreamHandler.ExtXMPPConnection mXMPPConnection; private XmppStreamHandler mStreamHandler; private Thread mConnectingThread; private Object mConnectingThreadMutex = new Object(); private ConnectionState mRequestedState = ConnectionState.OFFLINE; private ConnectionState mState = ConnectionState.OFFLINE; private String mLastError; private long mLastOnline = 0; //< timestamp of last successful full login (XEP-0198 does not count) private long mLastOffline = 0; //< timestamp of the end of last successful login private XMPPServiceCallback mServiceCallBack; private Roster mRoster; private RosterListener mRosterListener; private PacketListener mPacketListener; private PacketListener mPresenceListener; private ConnectionListener mConnectionListener; private final ContentResolver mContentResolver; private AlarmManager mAlarmManager; private PacketListener mPongListener; private String mPingID; private long mPingTimestamp; private PendingIntent mPingAlarmPendIntent; private PendingIntent mPongTimeoutAlarmPendIntent; private static final String PING_ALARM = "org.yaxim.androidclient.PING_ALARM"; private static final String PONG_TIMEOUT_ALARM = "org.yaxim.androidclient.PONG_TIMEOUT_ALARM"; private Intent mPingAlarmIntent = new Intent(PING_ALARM); private Intent mPongTimeoutAlarmIntent = new Intent(PONG_TIMEOUT_ALARM); private Service mService; private PongTimeoutAlarmReceiver mPongTimeoutAlarmReceiver = new PongTimeoutAlarmReceiver(); private BroadcastReceiver mPingAlarmReceiver = new PingAlarmReceiver(); private final HashSet<String> mucJIDs = new HashSet<String>(); //< all configured MUCs, joined or not private Map<String, MultiUserChat> multiUserChats; private long mucLastPing = 0; private Map<String, Long> mucLastPong = new HashMap<String, Long>(); //< per-MUC timestamp of last incoming ping result private Map<String, Presence> subscriptionRequests = new HashMap<String, Presence>(); public SmackableImp(YaximConfiguration config, ContentResolver contentResolver, Service service) { this.mConfig = config; this.mContentResolver = contentResolver; this.mService = service; this.mAlarmManager = (AlarmManager)mService.getSystemService(Context.ALARM_SERVICE); mLastOnline = mLastOffline = System.currentTimeMillis(); } // this code runs a DNS resolver, might be blocking private synchronized void initXMPPConnection() { // allow custom server / custom port to override SRV record if (mConfig.customServer.length() > 0) mXMPPConfig = new ConnectionConfiguration(mConfig.customServer, mConfig.port, mConfig.server); else mXMPPConfig = new ConnectionConfiguration(mConfig.server); // use SRV mXMPPConfig.setReconnectionAllowed(false); mXMPPConfig.setSendPresence(false); mXMPPConfig.setCompressionEnabled(false); // disable for now mXMPPConfig.setDebuggerEnabled(mConfig.smackdebug); if (mConfig.require_ssl) this.mXMPPConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.required); // register MemorizingTrustManager for HTTPS try { SSLContext sc = SSLContext.getInstance("TLS"); MemorizingTrustManager mtm = YaximApplication.getApp(mService).mMTM; sc.init(null, new X509TrustManager[] { mtm }, new java.security.SecureRandom()); this.mXMPPConfig.setCustomSSLContext(sc); this.mXMPPConfig.setHostnameVerifier(mtm.wrapHostnameVerifier( new org.apache.http.conn.ssl.StrictHostnameVerifier())); } catch (java.security.GeneralSecurityException e) { debugLog("initialize MemorizingTrustManager: " + e); } this.mXMPPConnection = new XmppStreamHandler.ExtXMPPConnection(mXMPPConfig); this.mStreamHandler = new XmppStreamHandler(mXMPPConnection, mConfig.smackdebug); mStreamHandler.addAckReceivedListener(new XmppStreamHandler.AckReceivedListener() { public void ackReceived(long handled, long total) { gotServerPong("" + handled); } }); mConfig.reconnect_required = false; multiUserChats = new HashMap<String, MultiUserChat>(); initServiceDiscovery(); } // blocking, run from a thread! public boolean doConnect(boolean create_account) throws YaximXMPPException { mRequestedState = ConnectionState.ONLINE; updateConnectionState(ConnectionState.CONNECTING); if (mXMPPConnection == null || mConfig.reconnect_required) initXMPPConnection(); tryToConnect(create_account); // actually, authenticated must be true now, or an exception must have // been thrown. if (isAuthenticated()) { updateConnectionState(ConnectionState.LOADING); registerMessageListener(); registerPresenceListener(); registerPongListener(); syncDbRooms(); sendOfflineMessages(); sendUserWatching(); // we need to "ping" the service to let it know we are actually // connected, even when no roster entries will come in updateConnectionState(ConnectionState.ONLINE); } else throw new YaximXMPPException("SMACK connected, but authentication failed"); return true; } // BLOCKING, call on a new Thread! private void updateConnectingThread(Thread new_thread) { synchronized(mConnectingThreadMutex) { if (mConnectingThread == null) { mConnectingThread = new_thread; } else try { Log.d(TAG, "updateConnectingThread: old thread is still running, killing it."); mConnectingThread.interrupt(); mConnectingThread.join(50); } catch (InterruptedException e) { Log.d(TAG, "updateConnectingThread: failed to join(): " + e); } finally { mConnectingThread = new_thread; } } } private void finishConnectingThread() { synchronized(mConnectingThreadMutex) { mConnectingThread = null; } } /** Non-blocking, synchronized function to connect/disconnect XMPP. * This code is called from outside and returns immediately. The actual work * is done on a background thread, and notified via callback. * @param new_state The state to transition into. Possible values: * OFFLINE to properly close the connection * ONLINE to connect * DISCONNECTED when network goes down * @param create_account When going online, try to register an account. */ @Override public synchronized void requestConnectionState(ConnectionState new_state, final boolean create_account) { Log.d(TAG, "requestConnState: " + mState + " -> " + new_state + (create_account ? " create_account!" : "")); mRequestedState = new_state; if (new_state == mState) return; switch (new_state) { case ONLINE: switch (mState) { case RECONNECT_DELAYED: // TODO: cancel timer case RECONNECT_NETWORK: case DISCONNECTED: case OFFLINE: // update state before starting thread to prevent race conditions updateConnectionState(ConnectionState.CONNECTING); // register ping (connection) timeout handler: 2*PACKET_TIMEOUT(30s) + 3s registerPongTimeout(2*PACKET_TIMEOUT + 3000, "connection"); new Thread() { @Override public void run() { updateConnectingThread(this); try { doConnect(create_account); } catch (IllegalArgumentException e) { // this might happen when DNS resolution in ConnectionConfiguration fails onDisconnected(e); } catch (IllegalStateException e) {//TODO: work around old smack onDisconnected(e); } catch (YaximXMPPException e) { onDisconnected(e); } finally { mAlarmManager.cancel(mPongTimeoutAlarmPendIntent); finishConnectingThread(); } } }.start(); break; case CONNECTING: case LOADING: case DISCONNECTING: // ignore all other cases break; } break; case DISCONNECTED: // spawn thread to do disconnect if (mState == ConnectionState.ONLINE) { // update state before starting thread to prevent race conditions updateConnectionState(ConnectionState.DISCONNECTING); // register ping (connection) timeout handler: PACKET_TIMEOUT(30s) registerPongTimeout(PACKET_TIMEOUT, "forced disconnect"); new Thread() { public void run() { updateConnectingThread(this); mStreamHandler.quickShutdown(); onDisconnected("forced disconnect completed"); finishConnectingThread(); //updateConnectionState(ConnectionState.OFFLINE); } }.start(); } break; case OFFLINE: switch (mState) { case CONNECTING: case LOADING: case ONLINE: // update state before starting thread to prevent race conditions updateConnectionState(ConnectionState.DISCONNECTING); // register ping (connection) timeout handler: PACKET_TIMEOUT(30s) registerPongTimeout(PACKET_TIMEOUT, "manual disconnect"); // spawn thread to do disconnect new Thread() { public void run() { updateConnectingThread(this); mXMPPConnection.shutdown(); mStreamHandler.close(); mAlarmManager.cancel(mPongTimeoutAlarmPendIntent); // we should reset XMPPConnection the next time mConfig.reconnect_required = true; finishConnectingThread(); // reconnect if it was requested in the meantime if (mRequestedState == ConnectionState.ONLINE) requestConnectionState(ConnectionState.ONLINE); } }.start(); break; case DISCONNECTING: break; case DISCONNECTED: case RECONNECT_DELAYED: // TODO: clear timer case RECONNECT_NETWORK: updateConnectionState(ConnectionState.OFFLINE); } break; case RECONNECT_NETWORK: case RECONNECT_DELAYED: switch (mState) { case DISCONNECTED: case RECONNECT_NETWORK: case RECONNECT_DELAYED: updateConnectionState(new_state); break; default: throw new IllegalArgumentException("Can not go from " + mState + " to " + new_state); } } } @Override public void requestConnectionState(ConnectionState new_state) { requestConnectionState(new_state, false); } @Override public ConnectionState getConnectionState() { return mState; } @Override public long getConnectionStateTimestamp() { return (mState == ConnectionState.ONLINE) ? mLastOnline : mLastOffline; } // called at the end of a state transition private synchronized void updateConnectionState(ConnectionState new_state) { if (new_state == ConnectionState.ONLINE || new_state == ConnectionState.LOADING) mLastError = null; Log.d(TAG, "updateConnectionState: " + mState + " -> " + new_state + " (" + mLastError + ")"); if (new_state == mState) return; if (mState == ConnectionState.ONLINE) mLastOffline = System.currentTimeMillis(); mState = new_state; if (mServiceCallBack != null) mServiceCallBack.connectionStateChanged(); } private void initServiceDiscovery() { // register connection features ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(mXMPPConnection); // init Entity Caps manager with storage in app's cache dir try { if (capsCacheDir == null) { capsCacheDir = new File(mService.getCacheDir(), "entity-caps-cache"); capsCacheDir.mkdirs(); EntityCapsManager.setPersistentCache(new SimpleDirectoryPersistentCache(capsCacheDir)); } } catch (java.io.IOException e) { Log.e(TAG, "Could not init Entity Caps cache: " + e.getLocalizedMessage()); } // reference PingManager, set ping flood protection to 10s PingManager.getInstanceFor(mXMPPConnection).disablePingFloodProtection(); // set Version for replies String app_name = mService.getString(R.string.app_name); String build_revision = mService.getString(R.string.build_revision); Version.Manager.getInstanceFor(mXMPPConnection).setVersion( new Version(app_name, build_revision, "Android")); // reference DeliveryReceiptManager, add listener DeliveryReceiptManager dm = DeliveryReceiptManager.getInstanceFor(mXMPPConnection); dm.addReceiptReceivedListener(new ReceiptReceivedListener() { // DOES NOT WORK IN CARBONS public void onReceiptReceived(String fromJid, String toJid, String receiptId) { Log.d(TAG, "got delivery receipt for " + receiptId); changeMessageDeliveryStatus(receiptId, ChatConstants.DS_ACKED); }}); } public void addRosterItem(String user, String alias, String group, String token) throws YaximXMPPException { subscriptionRequests.remove(user); mConfig.whitelistInvitationJID(user); tryToAddRosterEntry(user, alias, group, token); } public void removeRosterItem(String user) throws YaximXMPPException { debugLog("removeRosterItem(" + user + ")"); subscriptionRequests.remove(user); tryToRemoveRosterEntry(user); } public void renameRosterItem(String user, String newName) throws YaximXMPPException { RosterEntry rosterEntry = mRoster.getEntry(user); if (!(newName.length() > 0) || (rosterEntry == null)) { throw new YaximXMPPException("JabberID to rename is invalid!"); } rosterEntry.setName(newName); } public void addRosterGroup(String group) { mRoster.createGroup(group); } public void renameRosterGroup(String group, String newGroup) { RosterGroup groupToRename = mRoster.getGroup(group); groupToRename.setName(newGroup); } public void moveRosterItemToGroup(String user, String group) throws YaximXMPPException { tryToMoveRosterEntryToGroup(user, group); } public void sendPresenceRequest(String user, String type) { // HACK: remove the fake roster entry added by handleIncomingSubscribe() subscriptionRequests.remove(user); if ("unsubscribed".equals(type)) deleteRosterEntryFromDB(user); Presence response = new Presence(Presence.Type.valueOf(type)); response.setTo(user); mXMPPConnection.sendPacket(response); } @Override public String changePassword(String newPassword) { try { new AccountManager(mXMPPConnection).changePassword(newPassword); return "OK"; //HACK: hard coded string to differentiate from failure modes } catch (XMPPException e) { if (e.getXMPPError() != null) return e.getXMPPError().toString(); else return e.getLocalizedMessage(); } } private void onDisconnected(String reason) { unregisterPongListener(); mLastError = reason; updateConnectionState(ConnectionState.DISCONNECTED); } private void onDisconnected(Throwable reason) { Log.e(TAG, "onDisconnected: " + reason); reason.printStackTrace(); // iterate through to the deepest exception while (reason.getCause() != null && !(reason.getCause().getClass().getSimpleName().equals("GaiException"))) reason = reason.getCause(); onDisconnected(reason.getLocalizedMessage()); } private void tryToConnect(boolean create_account) throws YaximXMPPException { try { if (mXMPPConnection.isConnected()) { try { mStreamHandler.quickShutdown(); // blocking shutdown prior to re-connection } catch (Exception e) { debugLog("conn.shutdown() failed: " + e); } } registerRosterListener(); boolean need_bind = !mStreamHandler.isResumePossible(); if (mConnectionListener != null) mXMPPConnection.removeConnectionListener(mConnectionListener); mConnectionListener = new ConnectionListener() { public void connectionClosedOnError(Exception e) { // XXX: this is the only callback we get from errors, so // we need to check for non-resumability and work around // here: if (!mStreamHandler.isResumePossible()) { multiUserChats.clear(); mucLastPong.clear(); mucLastPing = 0; } onDisconnected(e); } public void connectionClosed() { // TODO: fix reconnect when we got kicked by the server or SM failed! //onDisconnected(null); multiUserChats.clear(); mucLastPong.clear(); mucLastPing = 0; updateConnectionState(ConnectionState.OFFLINE); } public void reconnectingIn(int seconds) { } public void reconnectionFailed(Exception e) { } public void reconnectionSuccessful() { } }; mXMPPConnection.addConnectionListener(mConnectionListener); mXMPPConnection.connect(need_bind); // SMACK auto-logins if we were authenticated before if (!mXMPPConnection.isAuthenticated()) { if (create_account) { Log.d(TAG, "creating new server account..."); AccountManager am = new AccountManager(mXMPPConnection); am.createAccount(mConfig.userName, mConfig.password); } mXMPPConnection.login(mConfig.userName, mConfig.password, mConfig.ressource); } Log.d(TAG, "SM: can resume = " + mStreamHandler.isResumePossible() + " needbind=" + need_bind); if (need_bind) { mStreamHandler.notifyInitialLogin(); cleanupMUCs(true); setStatusFromConfig(); mLastOnline = System.currentTimeMillis(); } } catch (Exception e) { // actually we just care for IllegalState or NullPointer or XMPPEx. throw new YaximXMPPException("tryToConnect failed", e); } } private void tryToMoveRosterEntryToGroup(String userName, String groupName) throws YaximXMPPException { RosterGroup rosterGroup = getRosterGroup(groupName); RosterEntry rosterEntry = mRoster.getEntry(userName); removeRosterEntryFromGroups(rosterEntry); if (groupName.length() == 0) return; else { try { rosterGroup.addEntry(rosterEntry); } catch (XMPPException e) { throw new YaximXMPPException("tryToMoveRosterEntryToGroup", e); } } } private RosterGroup getRosterGroup(String groupName) { RosterGroup rosterGroup = mRoster.getGroup(groupName); // create group if unknown if ((groupName.length() > 0) && rosterGroup == null) { rosterGroup = mRoster.createGroup(groupName); } return rosterGroup; } private void removeRosterEntryFromGroups(RosterEntry rosterEntry) throws YaximXMPPException { Collection<RosterGroup> oldGroups = rosterEntry.getGroups(); for (RosterGroup group : oldGroups) { tryToRemoveUserFromGroup(group, rosterEntry); } } private void tryToRemoveUserFromGroup(RosterGroup group, RosterEntry rosterEntry) throws YaximXMPPException { try { group.removeEntry(rosterEntry); } catch (XMPPException e) { throw new YaximXMPPException("tryToRemoveUserFromGroup", e); } } private void tryToRemoveRosterEntry(String user) throws YaximXMPPException { try { RosterEntry rosterEntry = mRoster.getEntry(user); if (rosterEntry != null) { // first, unsubscribe the user Presence unsub = new Presence(Presence.Type.unsubscribed); unsub.setTo(rosterEntry.getUser()); mXMPPConnection.sendPacket(unsub); // then, remove from roster mRoster.removeEntry(rosterEntry); } } catch (XMPPException e) { throw new YaximXMPPException("tryToRemoveRosterEntry", e); } } private void tryToAddRosterEntry(String user, String alias, String group, String token) throws YaximXMPPException { try { // send a presence subscription request with token (must be before roster action!) if (token != null && token.length() > 0) { Presence preauth = new Presence(Presence.Type.subscribe); preauth.setTo(user); preauth.addExtension(new PreAuth(token)); mXMPPConnection.sendPacket(preauth); } // add to roster, triggers another sub request by Smack (sigh) mRoster.createEntry(user, alias, new String[] { group }); // send a pre-approval Presence pre_approval = new Presence(Presence.Type.subscribed); pre_approval.setTo(user); mXMPPConnection.sendPacket(pre_approval); mConfig.whitelistInvitationJID(user); } catch (XMPPException e) { throw new YaximXMPPException("tryToAddRosterEntry", e); } } private void removeOldRosterEntries() { Log.d(TAG, "removeOldRosterEntries()"); Collection<RosterEntry> rosterEntries = mRoster.getEntries(); StringBuilder exclusion = new StringBuilder(RosterConstants.JID + " NOT IN ("); boolean first = true; for (RosterEntry rosterEntry : rosterEntries) { if (first) first = false; else exclusion.append(","); exclusion.append("'").append(rosterEntry.getUser()).append("'"); } exclusion.append(") AND "+RosterConstants.GROUP+" NOT IN ('" + RosterProvider.RosterConstants.MUCS + "');"); int count = mContentResolver.delete(RosterProvider.CONTENT_URI, exclusion.toString(), null); Log.d(TAG, "deleted " + count + " old roster entries"); } // HACK: add an incoming subscription request as a fake roster entry private void handleIncomingSubscribe(Presence request) { // perform Pre-Authenticated Roster Subscription, fallback to manual try { String jid = request.getFrom(); PreAuth preauth = (PreAuth)request.getExtension(PreAuth.ELEMENT, PreAuth.NAMESPACE); String jid_or_token = jid; if (preauth != null) { jid_or_token = preauth.getToken(); Log.d(TAG, "PARS: found token " + jid_or_token); } if (mConfig.redeemInvitationCode(jid_or_token)) { Log.d(TAG, "PARS: approving request from " + jid); if (mRoster.getEntry(request.getFrom()) != null) { // already in roster, only send approval Presence response = new Presence(Presence.Type.subscribed); response.setTo(jid); mXMPPConnection.sendPacket(response); } else { tryToAddRosterEntry(jid, null, "", null); } return; } } catch (YaximXMPPException e) { Log.d(TAG, "PARS: failed to send response: " + e); } subscriptionRequests.put(request.getFrom(), request); final ContentValues values = new ContentValues(); values.put(RosterConstants.JID, request.getFrom()); values.put(RosterConstants.STATUS_MODE, getStatusInt(request)); values.put(RosterConstants.STATUS_MESSAGE, request.getStatus()); if (!mRoster.contains(request.getFrom())) { // reset alias and group for new entries values.put(RosterConstants.ALIAS, request.getFrom()); values.put(RosterConstants.GROUP, ""); }; upsertRoster(values, request.getFrom()); } public void setStatusFromConfig() { // TODO: only call this when carbons changed, not on every presence change CarbonManager.getInstanceFor(mXMPPConnection).sendCarbonsEnabled(mConfig.messageCarbons); Presence presence = new Presence(Presence.Type.available); Mode mode = Mode.valueOf(mConfig.getPresenceMode().toString()); presence.setMode(mode); presence.setStatus(mConfig.statusMessage); presence.setPriority(mConfig.priority); mXMPPConnection.sendPacket(presence); mConfig.presence_required = false; } public void sendOfflineMessages() { Cursor cursor = mContentResolver.query(ChatProvider.CONTENT_URI, SEND_OFFLINE_PROJECTION, SEND_OFFLINE_SELECTION, null, null); final int _ID_COL = cursor.getColumnIndexOrThrow(ChatConstants._ID); final int JID_COL = cursor.getColumnIndexOrThrow(ChatConstants.JID); final int MSG_COL = cursor.getColumnIndexOrThrow(ChatConstants.MESSAGE); final int TS_COL = cursor.getColumnIndexOrThrow(ChatConstants.DATE); final int PACKETID_COL = cursor.getColumnIndexOrThrow(ChatConstants.PACKET_ID); ContentValues mark_sent = new ContentValues(); mark_sent.put(ChatConstants.DELIVERY_STATUS, ChatConstants.DS_SENT_OR_READ); while (cursor.moveToNext()) { int _id = cursor.getInt(_ID_COL); String toJID = cursor.getString(JID_COL); String message = cursor.getString(MSG_COL); String packetID = cursor.getString(PACKETID_COL); long ts = cursor.getLong(TS_COL); Log.d(TAG, "sendOfflineMessages: " + toJID + " > " + message); final Message newMessage = new Message(toJID, Message.Type.chat); newMessage.setBody(message); DelayInformation delay = new DelayInformation(new Date(ts)); newMessage.addExtension(delay); newMessage.addExtension(new DelayInfo(delay)); if (mucJIDs.contains(toJID)) newMessage.setType(Message.Type.groupchat); else newMessage.addExtension(new DeliveryReceiptRequest()); if ((packetID != null) && (packetID.length() > 0)) { newMessage.setPacketID(packetID); } else { packetID = newMessage.getPacketID(); } mark_sent.put(ChatConstants.PACKET_ID, packetID); Uri rowuri = Uri.parse("content://" + ChatProvider.AUTHORITY + "/" + ChatProvider.TABLE_NAME + "/" + _id); mContentResolver.update(rowuri, mark_sent, null, null); mXMPPConnection.sendPacket(newMessage); // must be after marking delivered, otherwise it may override the SendFailListener } cursor.close(); } public static void sendOfflineMessage(ContentResolver cr, String toJID, String message) { ContentValues values = new ContentValues(); values.put(ChatConstants.DIRECTION, ChatConstants.OUTGOING); values.put(ChatConstants.JID, toJID); values.put(ChatConstants.MESSAGE, message); values.put(ChatConstants.DELIVERY_STATUS, ChatConstants.DS_NEW); values.put(ChatConstants.DATE, System.currentTimeMillis()); values.put(ChatConstants.PACKET_ID, Packet.nextID()); cr.insert(ChatProvider.CONTENT_URI, values); } public void sendReceiptIfRequested(Packet packet) { DeliveryReceiptRequest drr = (DeliveryReceiptRequest)packet.getExtension( DeliveryReceiptRequest.ELEMENT, DeliveryReceipt.NAMESPACE); if (drr != null) { Message ack = new Message(packet.getFrom(), Message.Type.normal); ack.addExtension(new DeliveryReceipt(packet.getPacketID())); mXMPPConnection.sendPacket(ack); } } public void sendMessage(String toJID, String message) { final Message newMessage = new Message(toJID, Message.Type.chat); newMessage.setBody(message); newMessage.addExtension(new DeliveryReceiptRequest()); if (isAuthenticated()) { if(mucJIDs.contains(toJID)) { sendMucMessage(toJID, message); } else { addChatMessageToDB(ChatConstants.OUTGOING, toJID, message, ChatConstants.DS_SENT_OR_READ, System.currentTimeMillis(), newMessage.getPacketID()); mXMPPConnection.sendPacket(newMessage); } } else { // send offline -> store to DB addChatMessageToDB(ChatConstants.OUTGOING, toJID, message, ChatConstants.DS_NEW, System.currentTimeMillis(), newMessage.getPacketID()); } } public boolean isAuthenticated() { if (mXMPPConnection != null) { return (mXMPPConnection.isConnected() && mXMPPConnection .isAuthenticated()); } return false; } public void registerCallback(XMPPServiceCallback callBack) { this.mServiceCallBack = callBack; mService.registerReceiver(mPingAlarmReceiver, new IntentFilter(PING_ALARM)); mService.registerReceiver(mPongTimeoutAlarmReceiver, new IntentFilter(PONG_TIMEOUT_ALARM)); } public void unRegisterCallback() { debugLog("unRegisterCallback()"); // remove callbacks _before_ tossing old connection try { mXMPPConnection.getRoster().removeRosterListener(mRosterListener); mXMPPConnection.removePacketListener(mPacketListener); mXMPPConnection.removePacketListener(mPresenceListener); mXMPPConnection.removePacketListener(mPongListener); unregisterPongListener(); } catch (Exception e) { // ignore it! e.printStackTrace(); } requestConnectionState(ConnectionState.OFFLINE); setStatusOffline(); mService.unregisterReceiver(mPingAlarmReceiver); mService.unregisterReceiver(mPongTimeoutAlarmReceiver); // multiUserChats.clear(); // TODO: right place this.mServiceCallBack = null; } public String getNameForJID(String jid) { if (jid.contains("/")) { // MUC-PM String[] jid_parts = jid.split("/", 2); return String.format("%s (%s)", jid_parts[1], ChatRoomHelper.getRoomName(mService, jid_parts[0])); } RosterEntry re = mRoster.getEntry(jid); if (null != re && null != re.getName() && re.getName().length() > 0) { return re.getName(); } else if (mucJIDs.contains(jid)) { return ChatRoomHelper.getRoomName(mService, jid); } else { return jid; } } public long getRowIdForMessage(String jid, String resource, int direction, String packet_id) { // query the DB for the RowID, return -1 if packet_id does not match Cursor c = mContentResolver.query(ChatProvider.CONTENT_URI, new String[] { ChatConstants._ID, ChatConstants.PACKET_ID }, "jid = ? AND resource = ? AND from_me = ?", new String[] { jid, resource, "" + direction }, "_id DESC"); long result = -1; if (c.moveToFirst() && c.getString(1).equals(packet_id)) result = c.getLong(0); c.close(); return result; } private void setStatusOffline() { ContentValues values = new ContentValues(); values.put(RosterConstants.STATUS_MODE, StatusMode.offline.ordinal()); mContentResolver.update(RosterProvider.CONTENT_URI, values, null, null); } private void registerRosterListener() { // flush roster on connecting. mRoster = mXMPPConnection.getRoster(); mRoster.setSubscriptionMode(Roster.SubscriptionMode.manual); if (mRosterListener != null) mRoster.removeRosterListener(mRosterListener); mRosterListener = new RosterListener() { private boolean first_roster = true; public void entriesAdded(Collection<String> entries) { debugLog("entriesAdded(" + entries + ")"); ContentValues[] cvs = new ContentValues[entries.size()]; int i = 0; for (String entry : entries) { RosterEntry rosterEntry = mRoster.getEntry(entry); cvs[i++] = getContentValuesForRosterEntry(rosterEntry); } mContentResolver.bulkInsert(RosterProvider.CONTENT_URI, cvs); // when getting the roster in the beginning, remove remains of old one if (first_roster) { removeOldRosterEntries(); first_roster = false; } debugLog("entriesAdded() done"); } public void entriesDeleted(Collection<String> entries) { debugLog("entriesDeleted(" + entries + ")"); for (String entry : entries) { deleteRosterEntryFromDB(entry); } } public void entriesUpdated(Collection<String> entries) { debugLog("entriesUpdated(" + entries + ")"); for (String entry : entries) { RosterEntry rosterEntry = mRoster.getEntry(entry); updateRosterEntryInDB(rosterEntry); } } public void presenceChanged(Presence presence) { debugLog("presenceChanged(" + presence.getFrom() + "): " + presence); String jabberID = getBareJID(presence.getFrom()); RosterEntry rosterEntry = mRoster.getEntry(jabberID); if (rosterEntry != null) upsertRoster(getContentValuesForRosterEntry(rosterEntry, presence), rosterEntry.getUser()); } }; mRoster.addRosterListener(mRosterListener); } private String getBareJID(String from) { String[] res = from.split("/", 2); return res[0].toLowerCase(); } private String[] getJabberID(String from) { if(from.contains("/")) { String[] res = from.split("/", 2); return new String[] { res[0], res[1] }; } else { return new String[] {from, ""}; } } public boolean changeMessageDeliveryStatus(String packetID, int new_status) { ContentValues cv = new ContentValues(); cv.put(ChatConstants.DELIVERY_STATUS, new_status); Uri rowuri = Uri.parse("content://" + ChatProvider.AUTHORITY + "/" + ChatProvider.TABLE_NAME); return mContentResolver.update(rowuri, cv, ChatConstants.PACKET_ID + " = ? AND " + ChatConstants.DELIVERY_STATUS + " != " + ChatConstants.DS_ACKED + " AND " + ChatConstants.DIRECTION + " = " + ChatConstants.OUTGOING, new String[] { packetID }) > 0; } protected boolean is_user_watching = false; public void setUserWatching(boolean user_watching) { if (is_user_watching == user_watching) return; is_user_watching = user_watching; if (mXMPPConnection != null && mXMPPConnection.isAuthenticated()) sendUserWatching(); } protected void sendUserWatching() { IQ toggle_google_queue = new IQ() { public String getChildElementXML() { // enable g:q = start queueing packets = do it when the user is gone return "<query xmlns='google:queue'><" + (is_user_watching ? "disable" : "enable") + "/></query>"; } }; toggle_google_queue.setType(IQ.Type.SET); mXMPPConnection.sendPacket(toggle_google_queue); } /** Check the server connection, reconnect if needed. * * This function will try to ping the server if we are connected, and try * to reestablish a connection otherwise. */ public void sendServerPing() { if (mXMPPConnection == null || !mXMPPConnection.isAuthenticated()) { debugLog("Ping: requested, but not connected to server."); requestConnectionState(ConnectionState.ONLINE, false); return; } if (mPingID != null) { debugLog("Ping: requested, but still waiting for " + mPingID); return; // a ping is still on its way } if (mStreamHandler.isSmEnabled()) { debugLog("Ping: sending SM request"); mPingID = "" + mStreamHandler.requestAck(); } else { Ping ping = new Ping(); ping.setType(Type.GET); ping.setTo(mConfig.server); mPingID = ping.getPacketID(); debugLog("Ping: sending ping " + mPingID); mXMPPConnection.sendPacket(ping); } // register ping timeout handler: PACKET_TIMEOUT(30s) + 3s registerPongTimeout(PACKET_TIMEOUT + 3000, mPingID); } private void gotServerPong(String pongID) { long latency = System.currentTimeMillis() - mPingTimestamp; if (pongID != null && pongID.equals(mPingID)) Log.i(TAG, String.format("Ping: server latency %1.3fs", latency/1000.)); else Log.i(TAG, String.format("Ping: server latency %1.3fs (estimated)", latency/1000.)); mPingID = null; mAlarmManager.cancel(mPongTimeoutAlarmPendIntent); } /** Register a "pong" timeout on the connection. */ private void registerPongTimeout(long wait_time, String id) { mPingID = id; mPingTimestamp = System.currentTimeMillis(); debugLog(String.format("Ping: registering timeout for %s: %1.3fs", id, wait_time/1000.)); mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + wait_time, mPongTimeoutAlarmPendIntent); } /** * BroadcastReceiver to trigger reconnect on pong timeout. */ private class PongTimeoutAlarmReceiver extends BroadcastReceiver { public void onReceive(Context ctx, Intent i) { debugLog("Ping: timeout for " + mPingID); onDisconnected(mService.getString(R.string.conn_ping_timeout)); } } /** * BroadcastReceiver to trigger sending pings to the server */ private class PingAlarmReceiver extends BroadcastReceiver { public void onReceive(Context ctx, Intent i) { sendServerPing(); // ping all MUCs. if no ping was received since last attempt, /cycle Iterator<MultiUserChat> muc_it = multiUserChats.values().iterator(); long ts = System.currentTimeMillis(); ContentValues cvR = new ContentValues(); cvR.put(RosterProvider.RosterConstants.STATUS_MESSAGE, mService.getString(R.string.conn_ping_timeout)); cvR.put(RosterProvider.RosterConstants.STATUS_MODE, StatusMode.offline.ordinal()); cvR.put(RosterProvider.RosterConstants.GROUP, RosterProvider.RosterConstants.MUCS); while (muc_it.hasNext()) { MultiUserChat muc = muc_it.next(); if (!muc.isJoined()) continue; Long lastPong = mucLastPong.get(muc.getRoom()); if (mucLastPing > 0 && (lastPong == null || lastPong < mucLastPing)) { debugLog("Ping timeout from " + muc.getRoom()); muc.leave(); upsertRoster(cvR, muc.getRoom()); } else { Ping ping = new Ping(); ping.setType(Type.GET); String jid = muc.getRoom() + "/" + muc.getNickname(); ping.setTo(jid); mPingID = ping.getPacketID(); debugLog("Ping: sending ping to " + jid); mXMPPConnection.sendPacket(ping); } } syncDbRooms(); mucLastPing = ts; } } /** * Registers a smack packet listener for IQ packets, intended to recognize "pongs" with * a packet id matching the last "ping" sent to the server. * * Also sets up the AlarmManager Timer plus necessary intents. */ private void registerPongListener() { // reset ping expectation on new connection mPingID = null; if (mPongListener != null) mXMPPConnection.removePacketListener(mPongListener); mPongListener = new PacketListener() { @Override public void processPacket(Packet packet) { if (packet == null) return; if (packet instanceof IQ && packet.getFrom() != null) { IQ ping = (IQ)packet; String from_bare = getBareJID(ping.getFrom()); // check for ping error or RESULT if (ping.getType() == Type.RESULT && mucJIDs.contains(from_bare)) { Log.d(TAG, "Ping: got response from MUC " + from_bare); mucLastPong.put(from_bare, System.currentTimeMillis()); } } if (mPingID != null && mPingID.equals(packet.getPacketID())) gotServerPong(packet.getPacketID()); } }; mXMPPConnection.addPacketListener(mPongListener, new PacketTypeFilter(IQ.class)); mPingAlarmPendIntent = PendingIntent.getBroadcast(mService.getApplicationContext(), 0, mPingAlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); mPongTimeoutAlarmPendIntent = PendingIntent.getBroadcast(mService.getApplicationContext(), 0, mPongTimeoutAlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + AlarmManager.INTERVAL_FIFTEEN_MINUTES, AlarmManager.INTERVAL_FIFTEEN_MINUTES, mPingAlarmPendIntent); } private void unregisterPongListener() { mAlarmManager.cancel(mPingAlarmPendIntent); mAlarmManager.cancel(mPongTimeoutAlarmPendIntent); } private void registerMessageListener() { // do not register multiple packet listeners if (mPacketListener != null) mXMPPConnection.removePacketListener(mPacketListener); PacketTypeFilter filter = new PacketTypeFilter(Message.class); mPacketListener = new PacketListener() { public void processPacket(Packet packet) { try { if (packet instanceof Message) { Message msg = (Message) packet; String[] fromJID = getJabberID(msg.getFrom()); int direction = ChatConstants.INCOMING; Carbon cc = CarbonManager.getCarbon(msg); if (cc != null && !msg.getFrom().equalsIgnoreCase(mConfig.jabberID)) { Log.w(TAG, "Received illegal carbon from " + msg.getFrom() + ": " + cc.toXML()); cc = null; } // extract timestamp long ts; DelayInfo timestamp = (DelayInfo)msg.getExtension("delay", "urn:xmpp:delay"); if (timestamp == null) timestamp = (DelayInfo)msg.getExtension("x", "jabber:x:delay"); if (cc != null) // Carbon timestamp overrides packet timestamp timestamp = cc.getForwarded().getDelayInfo(); if (timestamp != null) ts = timestamp.getStamp().getTime(); else ts = System.currentTimeMillis(); // try to extract a carbon if (cc != null) { Log.d(TAG, "carbon: " + cc.toXML()); msg = (Message)cc.getForwarded().getForwardedPacket(); // outgoing carbon: fromJID is actually chat peer's JID if (cc.getDirection() == Carbon.Direction.sent) { fromJID = getJabberID(msg.getTo()); direction = ChatConstants.OUTGOING; } else { fromJID = getJabberID(msg.getFrom()); // hook off carbonated delivery receipts DeliveryReceipt dr = (DeliveryReceipt)msg.getExtension( DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE); if (dr != null) { Log.d(TAG, "got CC'ed delivery receipt for " + dr.getId()); changeMessageDeliveryStatus(dr.getId(), ChatConstants.DS_ACKED); } } // ignore carbon copies of OTR messages sent by broken clients if (msg.getBody() != null && msg.getBody().startsWith("?OTR")) { Log.i(TAG, "Ignoring OTR carbon from " + msg.getFrom() + " to " + msg.getTo()); return; } } // check for jabber MUC invitation if(direction == ChatConstants.INCOMING && handleMucInvitation(msg)) { sendReceiptIfRequested(packet); return; } String chatMessage = msg.getBody(); // display error inline if (msg.getType() == Message.Type.error) { if (changeMessageDeliveryStatus(msg.getPacketID(), ChatConstants.DS_FAILED)) mServiceCallBack.notifyMessage(fromJID, msg.getError().toString(), (cc != null), Message.Type.error); else if (mucJIDs.contains(msg.getFrom())) { handleKickedFromMUC(msg.getFrom(), false, null, msg.getError().toString()); } return; // we do not want to add errors as "incoming messages" } // ignore empty messages if (chatMessage == null) { if (msg.getSubject() != null && msg.getType() == Message.Type.groupchat && mucJIDs.contains(fromJID[0])) { // this is a MUC subject, update our DB ContentValues cvR = new ContentValues(); cvR.put(RosterProvider.RosterConstants.STATUS_MESSAGE, msg.getSubject()); cvR.put(RosterProvider.RosterConstants.STATUS_MODE, StatusMode.available.ordinal()); Log.d(TAG, "MUC subject for " + fromJID[0] + " set to: " + msg.getSubject()); upsertRoster(cvR, fromJID[0]); return; } Log.d(TAG, "empty message."); return; } // obtain Last Message Correction, if present Replace replace = (Replace)msg.getExtension(Replace.NAMESPACE); String replace_id = (replace != null) ? replace.getId() : null; // carbons are old. all others are new int is_new = (cc == null) ? ChatConstants.DS_NEW : ChatConstants.DS_SENT_OR_READ; if (msg.getType() == Message.Type.error) is_new = ChatConstants.DS_FAILED; boolean is_muc = (msg.getType() == Message.Type.groupchat); boolean is_from_me = (direction == ChatConstants.OUTGOING) || (is_muc && fromJID[1].equals(getMyMucNick(fromJID[0]))); // handle MUC-PMs: messages from a nick from a known MUC or with // an <x> element MUCUser muc_x = (MUCUser)msg.getExtension("x", "http://jabber.org/protocol/muc#user"); boolean is_muc_pm = !is_muc && !TextUtils.isEmpty(fromJID[1]) && (muc_x != null || mucJIDs.contains(fromJID[0])); // TODO: ignoring 'received' MUC-PM carbons, until XSF sorts out shit: // - if yaxim is in the MUC, it will receive a non-carbonated copy of // incoming messages, but not of outgoing ones // - if yaxim isn't in the MUC, it can't respond anyway if (is_muc_pm && !is_from_me && cc != null) return; if (is_muc_pm) { // store MUC-PMs under the participant's full JID, not bare //is_from_me = fromJID[1].equals(getMyMucNick(fromJID[0])); fromJID[0] = fromJID[0] + "/" + fromJID[1]; fromJID[1] = null; Log.d(TAG, "MUC-PM: " + fromJID[0] + " d=" + direction + " fromme=" + is_from_me); } // Carbons and MUC history are 'silent' by default boolean is_silent = (cc != null) || (is_muc && timestamp != null); if (!is_muc || checkAddMucMessage(msg, msg.getPacketID(), fromJID, timestamp)) { addChatMessageToDB(direction, fromJID, chatMessage, is_new, ts, msg.getPacketID(), replace_id); // only notify on private messages or when MUC notification requested boolean need_notify = !is_muc || mConfig.needMucNotification(getMyMucNick(fromJID[0]), chatMessage); // outgoing carbon -> clear notification by signalling 'null' message if (is_from_me) { mServiceCallBack.notifyMessage(fromJID, null, true, msg.getType()); // TODO: MUC PMs ChatHelper.markAsRead(mService, fromJID[0]); } else if (direction == ChatConstants.INCOMING && need_notify) mServiceCallBack.notifyMessage(fromJID, chatMessage, is_silent, msg.getType()); } sendReceiptIfRequested(packet); } } catch (Exception e) { // SMACK silently discards exceptions dropped from processPacket :( Log.e(TAG, "failed to process packet:"); e.printStackTrace(); } } }; mXMPPConnection.addPacketListener(mPacketListener, filter); } private boolean checkAddMucMessage(Message msg, String packet_id, String[] fromJid, DelayInfo timestamp) { String muc = fromJid[0]; String nick = fromJid[1]; // HACK: remove last outgoing message instead of upserting if (nick.equals(getMyMucNick(muc))) mContentResolver.delete(ChatProvider.CONTENT_URI, "jid = ? AND from_me = 1 AND (pid = ? OR message = ?) AND " + "_id >= (SELECT MIN(_id) FROM chats WHERE jid = ? ORDER BY _id DESC LIMIT 50)", new String[] { muc, packet_id, msg.getBody(), muc }); // messages with no timestamp are always new if (timestamp == null) return true; long ts = timestamp.getStamp().getTime(); final String[] projection = new String[] { ChatConstants._ID, ChatConstants.MESSAGE, ChatConstants.JID, ChatConstants.RESOURCE, ChatConstants.PACKET_ID }; if (packet_id == null) packet_id = ""; final String selection = "resource = ? AND (pid = ? OR date = ? OR message = ?) AND _id >= (SELECT MIN(_id) FROM chats WHERE jid = ? ORDER BY _id DESC LIMIT 50)"; final String[] selectionArgs = new String[] { nick, packet_id, ""+ts, msg.getBody(), muc }; try { Cursor cursor = mContentResolver.query(ChatProvider.CONTENT_URI, projection, selection, selectionArgs, null); Log.d(TAG, "message from " + nick + " matched " + cursor.getCount() + " items."); boolean result = (cursor.getCount() == 0); cursor.close(); return result; } catch (Exception e) { e.printStackTrace(); } // just return true... return true; } private void handleKickedFromMUC(String room, boolean banned, String actor, String reason) { mucLastPong.remove(room); ContentValues cvR = new ContentValues(); String message; if (actor != null && actor.length() > 0) message = mService.getString(banned ? R.string.muc_banned_by : R.string.muc_kicked_by, actor, reason); else message = mService.getString(banned ? R.string.muc_banned : R.string.muc_kicked, reason); cvR.put(RosterProvider.RosterConstants.STATUS_MESSAGE, message); cvR.put(RosterProvider.RosterConstants.STATUS_MODE, StatusMode.offline.ordinal()); upsertRoster(cvR, room); } @Override public String getMyMucNick(String jid) { MultiUserChat muc = multiUserChats.get(jid); if (muc != null && muc.getNickname() != null) return muc.getNickname(); if (mucJIDs.contains(jid)) { ChatRoomHelper.RoomInfo ri = ChatRoomHelper.getRoomInfo(mService, jid); if (ri != null) return ri.nickname; } return null; } private void registerPresenceListener() { // do not register multiple packet listeners if (mPresenceListener != null) mXMPPConnection.removePacketListener(mPresenceListener); mPresenceListener = new PacketListener() { public void processPacket(Packet packet) { try { Presence p = (Presence) packet; switch (p.getType()) { case subscribe: handleIncomingSubscribe(p); break; case subscribed: case unsubscribe: case unsubscribed: subscriptionRequests.remove(p.getFrom()); break; } } catch (Exception e) { // SMACK silently discards exceptions dropped from processPacket :( Log.e(TAG, "failed to process presence:"); e.printStackTrace(); } } }; mXMPPConnection.addPacketListener(mPresenceListener, new PacketTypeFilter(Presence.class)); } private void addChatMessageToDB(int direction, String[] tJID, String message, int delivery_status, long ts, String packetID, String replaceID) { ContentValues values = new ContentValues(); values.put(ChatConstants.DIRECTION, direction); values.put(ChatConstants.JID, tJID[0]); values.put(ChatConstants.RESOURCE, tJID[1]); values.put(ChatConstants.MESSAGE, message); values.put(ChatConstants.DELIVERY_STATUS, delivery_status); values.put(ChatConstants.DATE, ts); values.put(ChatConstants.PACKET_ID, packetID); if (replaceID != null) { // obtain row id for last message with that full JID, or -1 long _id = getRowIdForMessage(tJID[0], tJID[1], direction, replaceID); Log.d(TAG, "Replacing last message from " + tJID[0] + "/" + tJID[1] + ": " + replaceID + " -> " + packetID); Uri row = Uri.withAppendedPath(ChatProvider.CONTENT_URI, "" + _id); if (_id >= 0 && mContentResolver.update(row, values, null, null) == 1) return; } mContentResolver.insert(ChatProvider.CONTENT_URI, values); } private void addChatMessageToDB(int direction, String JID, String message, int delivery_status, long ts, String packetID) { String[] tJID = {JID, ""}; addChatMessageToDB(direction, tJID, message, delivery_status, ts, packetID, null); } private ContentValues getContentValuesForRosterEntry(final RosterEntry entry) { Presence presence = mRoster.getPresence(entry.getUser()); return getContentValuesForRosterEntry(entry, presence); } private ContentValues getContentValuesForRosterEntry(final RosterEntry entry, Presence presence) { final ContentValues values = new ContentValues(); values.put(RosterConstants.JID, entry.getUser()); values.put(RosterConstants.ALIAS, getName(entry)); // handle subscription requests and errors with higher priority Presence sub = subscriptionRequests.get(entry.getUser()); if (presence.getType() == Presence.Type.error) { String error = presence.getError().getMessage(); if (error == null || error.length() == 0) error = presence.getError().toString(); values.put(RosterConstants.STATUS_MESSAGE, error); } else if (sub != null) { presence = sub; values.put(RosterConstants.STATUS_MESSAGE, presence.getStatus()); } else switch (entry.getType()) { case to: case both: // override received presence from roster, using highest-prio entry presence = mRoster.getPresence(entry.getUser()); values.put(RosterConstants.STATUS_MESSAGE, presence.getStatus()); break; case from: values.put(RosterConstants.STATUS_MESSAGE, mService.getString(R.string.subscription_status_from)); presence = null; break; case none: values.put(RosterConstants.STATUS_MESSAGE, ""); presence = null; } values.put(RosterConstants.STATUS_MODE, getStatusInt(presence)); values.put(RosterConstants.GROUP, getGroup(entry.getGroups())); return values; } private void deleteRosterEntryFromDB(final String jabberID) { int count = mContentResolver.delete(RosterProvider.CONTENT_URI, RosterConstants.JID + " = ?", new String[] { jabberID }); debugLog("deleteRosterEntryFromDB: Deleted " + count + " entries"); } private void updateRosterEntryInDB(final RosterEntry entry) { upsertRoster(getContentValuesForRosterEntry(entry), entry.getUser()); } private void upsertRoster(final ContentValues values, String jid) { if (mContentResolver.update(RosterProvider.CONTENT_URI, values, RosterConstants.JID + " = ?", new String[] { jid }) == 0) { mContentResolver.insert(RosterProvider.CONTENT_URI, values); } } private String getGroup(Collection<RosterGroup> groups) { for (RosterGroup group : groups) { return group.getName(); } return ""; } private String getName(RosterEntry rosterEntry) { String name = rosterEntry.getName(); if (name != null && name.length() > 0) { return name; } return rosterEntry.getUser(); } private StatusMode getStatus(Presence presence) { if (presence == null) return StatusMode.unknown; if (presence.getType() == Presence.Type.subscribe) return StatusMode.subscribe; if (presence.getType() == Presence.Type.available) { if (presence.getMode() != null) { return StatusMode.valueOf(presence.getMode().name()); } return StatusMode.available; } return StatusMode.offline; } private int getStatusInt(final Presence presence) { return getStatus(presence).ordinal(); } private void debugLog(String data) { if (LogConstants.LOG_DEBUG) { Log.d(TAG, data); } } @Override public String getLastError() { return mLastError; } private synchronized void cleanupMUCs(boolean set_offline) { // get a fresh MUC list Cursor cursor = mContentResolver.query(RosterProvider.MUCS_URI, new String[] { RosterProvider.RosterConstants.JID }, null, null, null); mucJIDs.clear(); while(cursor.moveToNext()) { mucJIDs.add(cursor.getString(0)); } cursor.close(); // delete removed MUCs StringBuilder exclusion = new StringBuilder(RosterProvider.RosterConstants.GROUP + " = ? AND " + RosterConstants.JID + " NOT IN ('"); exclusion.append(TextUtils.join("', '", mucJIDs)); exclusion.append("');"); mContentResolver.delete(RosterProvider.CONTENT_URI, exclusion.toString(), new String[] { RosterProvider.RosterConstants.MUCS }); if (set_offline) { // update all other MUCs as offline ContentValues values = new ContentValues(); values.put(RosterConstants.STATUS_MODE, StatusMode.offline.ordinal()); mContentResolver.update(RosterProvider.CONTENT_URI, values, RosterProvider.RosterConstants.GROUP + " = ?", new String[] { RosterProvider.RosterConstants.MUCS }); } } public synchronized void syncDbRooms() { if (!isAuthenticated()) { debugLog("syncDbRooms: aborting, not yet authenticated"); } java.util.Set<String> joinedRooms = multiUserChats.keySet(); Cursor cursor = mContentResolver.query(RosterProvider.MUCS_URI, new String[] {RosterProvider.RosterConstants._ID, RosterProvider.RosterConstants.JID, RosterProvider.RosterConstants.PASSWORD, RosterProvider.RosterConstants.NICKNAME}, null, null, null); final int ID = cursor.getColumnIndexOrThrow(RosterProvider.RosterConstants._ID); final int JID_ID = cursor.getColumnIndexOrThrow(RosterProvider.RosterConstants.JID); final int PASSWORD_ID = cursor.getColumnIndexOrThrow(RosterProvider.RosterConstants.PASSWORD); final int NICKNAME_ID = cursor.getColumnIndexOrThrow(RosterProvider.RosterConstants.NICKNAME); mucJIDs.clear(); while(cursor.moveToNext()) { int id = cursor.getInt(ID); String jid = cursor.getString(JID_ID); String password = cursor.getString(PASSWORD_ID); String nickname = cursor.getString(NICKNAME_ID); mucJIDs.add(jid); //debugLog("Found MUC Room: "+jid+" with nick "+nickname+" and pw "+password); if(!joinedRooms.contains(jid) || !multiUserChats.get(jid).isJoined()) { debugLog("room " + jid + " isn't joined yet, i wanna join..."); joinRoomAsync(jid, nickname, password); // TODO: make historyLen configurable } else { MultiUserChat muc = multiUserChats.get(jid); if (!muc.getNickname().equals(nickname)) { debugLog("room " + jid + ": changing nickname to " + nickname); try { muc.changeNickname(nickname); } catch (XMPPException e) { Log.e(TAG, "Changing nickname failed."); e.printStackTrace(); } } } //debugLog("found data in contentprovider: "+jid+" "+password+" "+nickname); } cursor.close(); for(String room : new HashSet<String>(joinedRooms)) { if(!mucJIDs.contains(room)) { quitRoom(room); } } cleanupMUCs(false); } protected boolean handleMucInvitation(Message msg) { String room; String inviter = null; String reason = null; String password = null; MUCUser mucuser = (MUCUser)msg.getExtension("x", "http://jabber.org/protocol/muc#user"); GroupChatInvitation direct = (GroupChatInvitation)msg.getExtension(GroupChatInvitation.ELEMENT_NAME, GroupChatInvitation.NAMESPACE); if (mucuser != null && mucuser.getInvite() != null) { // first try official XEP-0045 mediated invitation MUCUser.Invite invite = mucuser.getInvite(); room = msg.getFrom(); inviter = invite.getFrom(); reason = invite.getReason(); password = mucuser.getPassword(); } else if (direct != null) { // fall back to XEP-0249 direct invitation room = direct.getRoomAddress(); inviter = msg.getFrom(); // TODO: get reason from direct invitation, not supported in smack3 } else return false; // not a MUC invitation if (mucJIDs.contains(room)) { Log.i(TAG, "Ignoring invitation to known MUC " + room); return true; } Log.d(TAG, "MUC invitation from " + inviter + " to " + room); asyncProcessMucInvitation(room, inviter, reason, password); return true; } protected void asyncProcessMucInvitation(final String room, final String inviter, final String reason, final String password) { new Thread() { public void run() { processMucInvitation(room, inviter, reason, password); } }.start(); } protected void processMucInvitation(final String room, final String inviter, final String reason, final String password) { String roomname = room; String inviter_name = null; if (getBareJID(inviter).equalsIgnoreCase(room)) { // from == participant JID, display as "user (MUC)" inviter_name = getNameForJID(inviter); } else { // from == user bare or full JID inviter_name = getNameForJID(getBareJID(inviter)); } String description = null; String inv_from = mService.getString(R.string.muc_invitation_from, inviter_name); // query room for info try { Log.d(TAG, "Requesting disco#info from " + room); RoomInfo ri = MultiUserChat.getRoomInfo(mXMPPConnection, room); String rn = ri.getRoomName(); if (rn != null && rn.length() > 0) roomname = String.format("%s (%s)", rn, roomname); description = ri.getSubject(); if (!TextUtils.isEmpty(description)) description = ri.getDescription(); description = mService.getString(R.string.muc_invitation_occupants, description, ri.getOccupantsCount()); Log.d(TAG, "MUC name after disco: " + roomname); } catch (XMPPException e) { // ignore a failed room info request Log.d(TAG, "MUC room IQ failed: " + room); e.printStackTrace(); } mServiceCallBack.mucInvitationReceived( roomname, room, password, inv_from, description); } private Map<String,Runnable> ongoingMucJoins = new java.util.concurrent.ConcurrentHashMap<String, Runnable>(); private synchronized void joinRoomAsync(final String room, final String nickname, final String password) { if (ongoingMucJoins.containsKey(room)) return; Thread joiner = new Thread() { @Override public void run() { Log.d(TAG, "async joining " + room); boolean result = joinRoom(room, nickname, password); Log.d(TAG, "async joining " + room + " done: " + result); ongoingMucJoins.remove(room); } }; ongoingMucJoins.put(room, joiner); joiner.start(); } private boolean joinRoom(final String room, String nickname, String password) { // work around smack3 bug: can't rejoin with "used" MultiUserChat instance MultiUserChat muc = new MultiUserChat(mXMPPConnection, room); Log.d(TAG, "created new MUC instance: " + room + " " + muc); muc.addUserStatusListener(new org.jivesoftware.smackx.muc.DefaultUserStatusListener() { @Override public void kicked(String actor, String reason) { debugLog("Kicked from " + room + " by " + actor + ": " + reason); handleKickedFromMUC(room, false, actor, reason); } @Override public void banned(String actor, String reason) { debugLog("Banned from " + room + " by " + actor + ": " + reason); handleKickedFromMUC(room, true, actor, reason); } }); DiscussionHistory history = new DiscussionHistory(); final String[] projection = new String[] { ChatConstants._ID, ChatConstants.DATE }; Cursor cursor = mContentResolver.query(ChatProvider.CONTENT_URI, projection, ChatConstants.JID + " = ? AND " + ChatConstants.DELIVERY_STATUS + " = " + ChatConstants.DS_SENT_OR_READ, new String[] { room }, "_id DESC LIMIT 1"); if(cursor.getCount()>0) { cursor.moveToFirst(); Date lastDate = new Date(cursor.getLong(1)); Log.d(TAG, "Getting room history for " + room + " starting at " + lastDate); history.setSince(lastDate); } else Log.d(TAG, "No last message for " + room); cursor.close(); ContentValues cvR = new ContentValues(); cvR.put(RosterProvider.RosterConstants.JID, room); cvR.put(RosterProvider.RosterConstants.ALIAS, room); cvR.put(RosterProvider.RosterConstants.STATUS_MESSAGE, mService.getString(R.string.muc_synchronizing)); cvR.put(RosterProvider.RosterConstants.STATUS_MODE, StatusMode.dnd.ordinal()); cvR.put(RosterProvider.RosterConstants.GROUP, RosterProvider.RosterConstants.MUCS); upsertRoster(cvR, room); cvR.clear(); try { Presence force_resync = new Presence(Presence.Type.unavailable); force_resync.setTo(room + "/" + nickname); mXMPPConnection.sendPacket(force_resync); muc.join(nickname, password, history, 10*PACKET_TIMEOUT); } catch (Exception e) { Log.e(TAG, "Could not join MUC-room "+room); e.printStackTrace(); cvR.put(RosterProvider.RosterConstants.STATUS_MESSAGE, mService.getString(R.string.conn_error, e.getLocalizedMessage())); cvR.put(RosterProvider.RosterConstants.STATUS_MODE, StatusMode.offline.ordinal()); upsertRoster(cvR, room); return false; } if(muc.isJoined()) { synchronized(this) { multiUserChats.put(room, muc); } String roomname = room.split("@")[0]; try { RoomInfo ri = MultiUserChat.getRoomInfo(mXMPPConnection, room); String rn = ri.getRoomName(); if (rn != null && rn.length() > 0) roomname = rn; Log.d(TAG, "MUC name after disco: " + roomname); } catch (XMPPException e) { // ignore a failed room info request Log.d(TAG, "MUC room IQ failed: " + room); e.printStackTrace(); } // delay requesting subject until room info IQ returned/failed String subject = muc.getSubject(); cvR.put(RosterProvider.RosterConstants.ALIAS, roomname); cvR.put(RosterProvider.RosterConstants.STATUS_MESSAGE, subject); cvR.put(RosterProvider.RosterConstants.STATUS_MODE, StatusMode.available.ordinal()); Log.d(TAG, "upserting MUC as online: " + roomname); upsertRoster(cvR, room); return true; } return false; } @Override public void sendMucMessage(String room, String message) { Message newMessage = new Message(room, Message.Type.groupchat); newMessage.setBody(message); addChatMessageToDB(ChatConstants.OUTGOING, room, message, ChatConstants.DS_NEW, System.currentTimeMillis(), newMessage.getPacketID()); mXMPPConnection.sendPacket(newMessage); } private void quitRoom(String room) { Log.d(TAG, "Leaving MUC " + room); MultiUserChat muc = multiUserChats.get(room); muc.leave(); multiUserChats.remove(room); mucLastPong.remove(room); mContentResolver.delete(RosterProvider.CONTENT_URI, "jid = ?", new String[] {room}); } @Override public boolean inviteToRoom(String contactJid, String roomJid) { MultiUserChat muc = multiUserChats.get(roomJid); if(contactJid.contains("/")) { contactJid = contactJid.split("/")[0]; } Log.d(TAG, "invitng contact: "+contactJid+" to room: "+muc); muc.invite(contactJid, "User "+contactJid+" has invited you to a chat!"); return false; } @Override public List<ParcelablePresence> getUserList(String jid) { MultiUserChat muc = multiUserChats.get(jid); if (muc == null) { return null; } Log.d(TAG, "MUC instance: " + jid + " " + muc); Iterator<String> occIter = muc.getOccupants(); ArrayList<ParcelablePresence> tmpList = new ArrayList<ParcelablePresence>(); while(occIter.hasNext()) tmpList.add(new ParcelablePresence(muc.getOccupantPresence(occIter.next()))); Collections.sort(tmpList, new Comparator<ParcelablePresence>() { @Override public int compare(ParcelablePresence lhs, ParcelablePresence rhs) { return java.text.Collator.getInstance().compare(lhs.resource, rhs.resource); } }); Log.d(TAG, "getUserList(" + jid + "): " + tmpList.size()); return tmpList; } }
./CrossVul/dataset_final_sorted/CWE-346/java/good_3124_0
crossvul-java_data_bad_3133_0
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * 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 net.java.sip.communicator.impl.protocol.jabber; import java.util.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.carbon.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.mailnotification.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.messagecorrection.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.Message; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.service.protocol.jabberconstants.*; import net.java.sip.communicator.util.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.filter.*; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.provider.*; import org.jivesoftware.smack.util.*; import org.jivesoftware.smackx.*; import org.jivesoftware.smackx.packet.*; /** * A straightforward implementation of the basic instant messaging operation * set. * * @author Damian Minkov * @author Matthieu Helleringer * @author Alain Knaebel * @author Emil Ivov * @author Hristo Terezov */ public class OperationSetBasicInstantMessagingJabberImpl extends AbstractOperationSetBasicInstantMessaging implements OperationSetMessageCorrection { /** * Our class logger */ private static final Logger logger = Logger.getLogger(OperationSetBasicInstantMessagingJabberImpl.class); /** * The maximum number of unread threads that we'd be notifying the user of. */ private static final String PNAME_MAX_GMAIL_THREADS_PER_NOTIFICATION = "net.java.sip.communicator.impl.protocol.jabber." +"MAX_GMAIL_THREADS_PER_NOTIFICATION"; /** * A table mapping contact addresses to full jids that can be used to * target a specific resource (rather than sending a message to all logged * instances of a user). */ private Map<String, StoredThreadID> jids = new Hashtable<String, StoredThreadID>(); /** * The most recent full JID used for the contact address. */ private Map<String, String> recentJIDForAddress = new Hashtable<String, String>(); /** * The smackMessageListener instance listens for incoming messages. * Keep a reference of it so if anything goes wrong we don't add * two different instances. */ private SmackMessageListener smackMessageListener = null; /** * Contains the complete jid of a specific user and the time that it was * last used so that we could remove it after a certain point. */ public static class StoredThreadID { /** The time that we last sent or received a message from this jid */ long lastUpdatedTime; /** The last chat used, this way we will reuse the thread-id */ String threadID; } /** * A prefix helps to make sure that thread ID's are unique across mutliple * instances. */ private static String prefix = StringUtils.randomString(5); /** * Keeps track of the current increment, which is appended to the prefix to * forum a unique thread ID. */ private static long id = 0; /** * The number of milliseconds that we preserve threads with no traffic * before considering them dead. */ private static final long JID_INACTIVITY_TIMEOUT = 10*60*1000;//10 min. /** * Indicates the time of the last Mailbox report that we received from * Google (if this is a Google server we are talking to). Should be included * in all following mailbox queries */ private long lastReceivedMailboxResultTime = -1; /** * The provider that created us. */ private final ProtocolProviderServiceJabberImpl jabberProvider; /** * A reference to the persistent presence operation set that we use * to match incoming messages to <tt>Contact</tt>s and vice versa. */ private OperationSetPersistentPresenceJabberImpl opSetPersPresence = null; /** * The opening BODY HTML TAG: &ltbody&gt */ private static final String OPEN_BODY_TAG = "<body>"; /** * The closing BODY HTML TAG: &ltbody&gt */ private static final String CLOSE_BODY_TAG = "</body>"; /** * The html namespace used as feature * XHTMLManager.namespace */ private final static String HTML_NAMESPACE = "http://jabber.org/protocol/xhtml-im"; /** * List of filters to be used to filter which messages to handle * current Operation Set. */ private List<PacketFilter> packetFilters = new ArrayList<PacketFilter>(); /** * Whether carbon is enabled or not. */ private boolean isCarbonEnabled = false; /** * Creates an instance of this operation set. * @param provider a reference to the <tt>ProtocolProviderServiceImpl</tt> * that created us and that we'll use for retrieving the underlying aim * connection. */ OperationSetBasicInstantMessagingJabberImpl( ProtocolProviderServiceJabberImpl provider) { this.jabberProvider = provider; packetFilters.add(new GroupMessagePacketFilter()); packetFilters.add( new PacketTypeFilter(org.jivesoftware.smack.packet.Message.class)); provider.addRegistrationStateChangeListener( new RegistrationStateListener()); ProviderManager man = ProviderManager.getInstance(); MessageCorrectionExtensionProvider extProvider = new MessageCorrectionExtensionProvider(); man.addExtensionProvider(MessageCorrectionExtension.ELEMENT_NAME, MessageCorrectionExtension.NAMESPACE, extProvider); } /** * Create a Message instance with the specified UID, content type * and a default encoding. * This method can be useful when message correction is required. One can * construct the corrected message to have the same UID as the message * before correction. * * @param messageText the string content of the message. * @param contentType the MIME-type for <tt>content</tt> * @param messageUID the unique identifier of this message. * @return Message the newly created message */ public Message createMessageWithUID( String messageText, String contentType, String messageUID) { return new MessageJabberImpl(messageText, contentType, DEFAULT_MIME_ENCODING, null, messageUID); } /** * Create a Message instance for sending arbitrary MIME-encoding content. * * @param content content value * @param contentType the MIME-type for <tt>content</tt> * @return the newly created message. */ public Message createMessage(String content, String contentType) { return createMessage(content, contentType, DEFAULT_MIME_ENCODING, null); } /** * Create a Message instance for sending arbitrary MIME-encoding content. * * @param content content value * @param contentType the MIME-type for <tt>content</tt> * @param subject the Subject of the message that we'd like to create. * @param encoding the enconding of the message that we will be sending. * * @return the newly created message. */ @Override public Message createMessage(String content, String contentType, String encoding, String subject) { return new MessageJabberImpl(content, contentType, encoding, subject); } Message createMessage(String content, String contentType, String messageUID) { return new MessageJabberImpl(content, contentType, DEFAULT_MIME_ENCODING, null, messageUID); } /** * Determines wheter the protocol provider (or the protocol itself) support * sending and receiving offline messages. Most often this method would * return true for protocols that support offline messages and false for * those that don't. It is however possible for a protocol to support these * messages and yet have a particular account that does not (i.e. feature * not enabled on the protocol server). In cases like this it is possible * for this method to return true even when offline messaging is not * supported, and then have the sendMessage method throw an * OperationFailedException with code - OFFLINE_MESSAGES_NOT_SUPPORTED. * * @return <tt>true</tt> if the protocol supports offline messages and * <tt>false</tt> otherwise. */ public boolean isOfflineMessagingSupported() { return true; } /** * Determines wheter the protocol supports the supplied content type * * @param contentType the type we want to check * @return <tt>true</tt> if the protocol supports it and * <tt>false</tt> otherwise. */ public boolean isContentTypeSupported(String contentType) { return (contentType.equals(DEFAULT_MIME_TYPE) || contentType.equals(HTML_MIME_TYPE)); } /** * Determines whether the protocol supports the supplied content type * for the given contact. * * @param contentType the type we want to check * @param contact contact which is checked for supported contentType * @return <tt>true</tt> if the contact supports it and * <tt>false</tt> otherwise. */ @Override public boolean isContentTypeSupported(String contentType, Contact contact) { // by default we support default mime type, for other mimetypes // method must be overriden if(contentType.equals(DEFAULT_MIME_TYPE)) return true; else if(contentType.equals(HTML_MIME_TYPE)) { String toJID = recentJIDForAddress.get(contact.getAddress()); if (toJID == null) toJID = contact.getAddress(); return jabberProvider.isFeatureListSupported( toJID, HTML_NAMESPACE); } return false; } /** * Remove from our <tt>jids</tt> map all entries that have not seen any * activity (i.e. neither outgoing nor incoming messags) for more than * JID_INACTIVITY_TIMEOUT. Note that this method is not synchronous and that * it is only meant for use by the {@link #getThreadIDForAddress(String)} and * {@link #putJidForAddress(String, String)} */ private void purgeOldJids() { long currentTime = System.currentTimeMillis(); Iterator<Map.Entry<String, StoredThreadID>> entries = jids.entrySet().iterator(); while( entries.hasNext() ) { Map.Entry<String, StoredThreadID> entry = entries.next(); StoredThreadID target = entry.getValue(); if (currentTime - target.lastUpdatedTime > JID_INACTIVITY_TIMEOUT) entries.remove(); } } /** * Returns the last jid that the party with the specified <tt>address</tt> * contacted us from or <tt>null</tt>(or bare jid) if we don't have a jid * for the specified <tt>address</tt> yet. The method would also purge all * entries that haven't seen any activity (i.e. no one has tried to get or * remap it) for a delay longer than <tt>JID_INACTIVITY_TIMEOUT</tt>. * * @param jid the <tt>jid</tt> that we'd like to obtain a threadID for. * * @return the last jid that the party with the specified <tt>address</tt> * contacted us from or <tt>null</tt> if we don't have a jid for the * specified <tt>address</tt> yet. */ String getThreadIDForAddress(String jid) { synchronized(jids) { purgeOldJids(); StoredThreadID ta = jids.get(jid); if (ta == null) return null; ta.lastUpdatedTime = System.currentTimeMillis(); return ta.threadID; } } /** * Maps the specified <tt>address</tt> to <tt>jid</tt>. The point of this * method is to allow us to send all messages destined to the contact with * the specified <tt>address</tt> to the <tt>jid</tt> that they last * contacted us from. * * @param threadID the threadID of conversation. * @param jid the jid (i.e. address/resource) that the contact with the * specified <tt>address</tt> last contacted us from. */ private void putJidForAddress(String jid, String threadID) { synchronized(jids) { purgeOldJids(); StoredThreadID ta = jids.get(jid); if (ta == null) { ta = new StoredThreadID(); jids.put(jid, ta); } recentJIDForAddress.put(StringUtils.parseBareAddress(jid), jid); ta.lastUpdatedTime = System.currentTimeMillis(); ta.threadID = threadID; } } /** * Helper function used to send a message to a contact, with the given * extensions attached. * * @param to The contact to send the message to. * @param toResource The resource to send the message to or null if no * resource has been specified * @param message The message to send. * @param extensions The XMPP extensions that should be attached to the * message before sending. * @return The MessageDeliveryEvent that resulted after attempting to * send this message, so the calling function can modify it if needed. */ private MessageDeliveredEvent sendMessage( Contact to, ContactResource toResource, Message message, PacketExtension[] extensions) { if( !(to instanceof ContactJabberImpl) ) throw new IllegalArgumentException( "The specified contact is not a Jabber contact." + to); assertConnected(); org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message(); String toJID = null; if (toResource != null) { if(toResource.equals(ContactResource.BASE_RESOURCE)) { toJID = to.getAddress(); } else toJID = ((ContactResourceJabberImpl) toResource).getFullJid(); } if (toJID == null) { toJID = to.getAddress(); } msg.setPacketID(message.getMessageUID()); msg.setTo(toJID); for (PacketExtension ext : extensions) { msg.addExtension(ext); } if (logger.isTraceEnabled()) logger.trace("Will send a message to:" + toJID + " chat.jid=" + toJID); MessageDeliveredEvent msgDeliveryPendingEvt = new MessageDeliveredEvent(message, to, toResource); MessageDeliveredEvent[] transformedEvents = messageDeliveryPendingTransform(msgDeliveryPendingEvt); if (transformedEvents == null || transformedEvents.length == 0) return null; for (MessageDeliveredEvent event : transformedEvents) { String content = event.getSourceMessage().getContent(); if (message.getContentType().equals(HTML_MIME_TYPE)) { msg.setBody(Html2Text.extractText(content)); // Check if the other user supports XHTML messages // make sure we use our discovery manager as it caches calls if (jabberProvider .isFeatureListSupported(toJID, HTML_NAMESPACE)) { // Add the XHTML text to the message XHTMLManager.addBody(msg, OPEN_BODY_TAG + content + CLOSE_BODY_TAG); } } else { // this is plain text so keep it as it is. msg.setBody(content); } // msg.addExtension(new Version()); if (event.isMessageEncrypted() && isCarbonEnabled) { msg.addExtension(new CarbonPacketExtension.PrivateExtension()); } MessageEventManager.addNotificationsRequests(msg, true, false, false, true); String threadID = getThreadIDForAddress(toJID); if (threadID == null) threadID = nextThreadID(); msg.setThread(threadID); msg.setType(org.jivesoftware.smack.packet.Message.Type.chat); msg.setFrom(jabberProvider.getConnection().getUser()); jabberProvider.getConnection().sendPacket(msg); putJidForAddress(toJID, threadID); } return new MessageDeliveredEvent(message, to, toResource); } /** * Sends the <tt>message</tt> to the destination indicated by the * <tt>to</tt> contact. * * @param to the <tt>Contact</tt> to send <tt>message</tt> to * @param message the <tt>Message</tt> to send. * @throws java.lang.IllegalStateException if the underlying stack is * not registered and initialized. * @throws java.lang.IllegalArgumentException if <tt>to</tt> is not an * instance of ContactImpl. */ public void sendInstantMessage(Contact to, Message message) throws IllegalStateException, IllegalArgumentException { sendInstantMessage(to, null, message); } /** * Sends the <tt>message</tt> to the destination indicated by the * <tt>to</tt>. Provides a default implementation of this method. * * @param to the <tt>Contact</tt> to send <tt>message</tt> to * @param toResource the resource to which the message should be send * @param message the <tt>Message</tt> to send. * @throws java.lang.IllegalStateException if the underlying ICQ stack is * not registered and initialized. * @throws java.lang.IllegalArgumentException if <tt>to</tt> is not an * instance belonging to the underlying implementation. */ @Override public void sendInstantMessage( Contact to, ContactResource toResource, Message message) throws IllegalStateException, IllegalArgumentException { MessageDeliveredEvent msgDelivered = sendMessage(to, toResource, message, new PacketExtension[0]); fireMessageEvent(msgDelivered); } /** * Replaces the message with ID <tt>correctedMessageUID</tt> sent to * the contact <tt>to</tt> with the message <tt>message</tt> * * @param to The contact to send the message to. * @param message The new message. * @param correctedMessageUID The ID of the message being replaced. */ public void correctMessage( Contact to, ContactResource resource, Message message, String correctedMessageUID) { PacketExtension[] exts = new PacketExtension[1]; exts[0] = new MessageCorrectionExtension(correctedMessageUID); MessageDeliveredEvent msgDelivered = sendMessage(to, resource, message, exts); msgDelivered.setCorrectedMessageUID(correctedMessageUID); fireMessageEvent(msgDelivered); } /** * Utility method throwing an exception if the stack is not properly * initialized. * * @throws java.lang.IllegalStateException if the underlying stack is * not registered and initialized. */ private void assertConnected() throws IllegalStateException { if (opSetPersPresence == null) { throw new IllegalStateException( "The provider must be signed on the service before" + " being able to communicate."); } else opSetPersPresence.assertConnected(); } /** * Our listener that will tell us when we're registered to */ private class RegistrationStateListener implements RegistrationStateChangeListener { /** * The method is called by a ProtocolProvider implementation whenever * a change in the registration state of the corresponding provider had * occurred. * @param evt ProviderStatusChangeEvent the event describing the status * change. */ public void registrationStateChanged(RegistrationStateChangeEvent evt) { if (logger.isDebugEnabled()) logger.debug("The provider changed state from: " + evt.getOldState() + " to: " + evt.getNewState()); if (evt.getNewState() == RegistrationState.REGISTERING) { opSetPersPresence = (OperationSetPersistentPresenceJabberImpl) jabberProvider.getOperationSet( OperationSetPersistentPresence.class); if(smackMessageListener == null) { smackMessageListener = new SmackMessageListener(); } else { // make sure this listener is not already installed in this // connection jabberProvider.getConnection() .removePacketListener(smackMessageListener); } jabberProvider.getConnection().addPacketListener( smackMessageListener, new AndFilter( packetFilters.toArray( new PacketFilter[packetFilters.size()]))); } else if (evt.getNewState() == RegistrationState.REGISTERED) { new Thread(new Runnable() { @Override public void run() { initAdditionalServices(); } }).start(); } else if(evt.getNewState() == RegistrationState.UNREGISTERED || evt.getNewState() == RegistrationState.CONNECTION_FAILED || evt.getNewState() == RegistrationState.AUTHENTICATION_FAILED) { if(jabberProvider.getConnection() != null) { if(smackMessageListener != null) jabberProvider.getConnection().removePacketListener( smackMessageListener); } smackMessageListener = null; } } } /** * Initialize additional services, like gmail notifications and message * carbons. */ private void initAdditionalServices() { //subscribe for Google (Gmail or Google Apps) notifications //for new mail messages. boolean enableGmailNotifications = jabberProvider .getAccountID() .getAccountPropertyBoolean( "GMAIL_NOTIFICATIONS_ENABLED", false); if (enableGmailNotifications) subscribeForGmailNotifications(); boolean enableCarbon = isCarbonSupported() && !jabberProvider.getAccountID() .getAccountPropertyBoolean( ProtocolProviderFactory.IS_CARBON_DISABLED, false); if(enableCarbon) { enableDisableCarbon(true); } else { isCarbonEnabled = false; } } /** * Sends enable or disable carbon packet to the server. * @param enable if <tt>true</tt> sends enable packet otherwise sends * disable packet. */ private void enableDisableCarbon(final boolean enable) { IQ iq = new IQ(){ @Override public String getChildElementXML() { return "<" + (enable? "enable" : "disable") + " xmlns='urn:xmpp:carbons:2' />"; } }; Packet response = null; try { PacketCollector packetCollector = jabberProvider.getConnection().createPacketCollector( new PacketIDFilter(iq.getPacketID())); iq.setFrom(jabberProvider.getOurJID()); iq.setType(IQ.Type.SET); jabberProvider.getConnection().sendPacket(iq); response = packetCollector.nextResult( SmackConfiguration.getPacketReplyTimeout()); packetCollector.cancel(); } catch(Exception e) { logger.error("Failed to enable carbon.", e); } isCarbonEnabled = false; if (response == null) { logger.error( "Failed to enable carbon. No response is received."); } else if (response.getError() != null) { logger.error( "Failed to enable carbon: " + response.getError()); } else if (!(response instanceof IQ) || !((IQ) response).getType().equals(IQ.Type.RESULT)) { logger.error( "Failed to enable carbon. The response is not correct."); } else { isCarbonEnabled = true; } } /** * Checks whether the carbon is supported by the server or not. * @return <tt>true</tt> if carbon is supported by the server and * <tt>false</tt> if not. */ private boolean isCarbonSupported() { try { return jabberProvider.getDiscoveryManager().discoverInfo( jabberProvider.getAccountID().getService()) .containsFeature(CarbonPacketExtension.NAMESPACE); } catch (XMPPException e) { logger.warn("Failed to retrieve carbon support." + e.getMessage()); } return false; } /** * The listener that we use in order to handle incoming messages. */ @SuppressWarnings("unchecked") private class SmackMessageListener implements PacketListener { /** * Handles incoming messages and dispatches whatever events are * necessary. * @param packet the packet that we need to handle (if it is a message). */ public void processPacket(Packet packet) { if(!(packet instanceof org.jivesoftware.smack.packet.Message)) return; org.jivesoftware.smack.packet.Message msg = (org.jivesoftware.smack.packet.Message)packet; boolean isForwardedSentMessage = false; if(msg.getBody() == null) { CarbonPacketExtension carbonExt = (CarbonPacketExtension) msg.getExtension( CarbonPacketExtension.NAMESPACE); if(carbonExt == null) return; isForwardedSentMessage = (carbonExt.getElementName() == CarbonPacketExtension.SENT_ELEMENT_NAME); List<ForwardedPacketExtension> extensions = carbonExt.getChildExtensionsOfType( ForwardedPacketExtension.class); if(extensions.isEmpty()) return; ForwardedPacketExtension forwardedExt = extensions.get(0); msg = forwardedExt.getMessage(); if(msg == null || msg.getBody() == null) return; } Object multiChatExtension = msg.getExtension("x", "http://jabber.org/protocol/muc#user"); // its not for us if(multiChatExtension != null) return; String userFullId = isForwardedSentMessage? msg.getTo() : msg.getFrom(); String userBareID = StringUtils.parseBareAddress(userFullId); boolean isPrivateMessaging = false; ChatRoom privateContactRoom = null; OperationSetMultiUserChatJabberImpl mucOpSet = (OperationSetMultiUserChatJabberImpl)jabberProvider .getOperationSet(OperationSetMultiUserChat.class); if(mucOpSet != null) privateContactRoom = mucOpSet.getChatRoom(userBareID); if(privateContactRoom != null) { isPrivateMessaging = true; } if(logger.isDebugEnabled()) { if (logger.isDebugEnabled()) logger.debug("Received from " + userBareID + " the message " + msg.toXML()); } Message newMessage = createMessage(msg.getBody(), DEFAULT_MIME_TYPE, msg.getPacketID()); //check if the message is available in xhtml PacketExtension ext = msg.getExtension( "http://jabber.org/protocol/xhtml-im"); if(ext != null) { XHTMLExtension xhtmlExt = (XHTMLExtension)ext; //parse all bodies Iterator<String> bodies = xhtmlExt.getBodies(); StringBuffer messageBuff = new StringBuffer(); while (bodies.hasNext()) { String body = bodies.next(); messageBuff.append(body); } if (messageBuff.length() > 0) { // we remove body tags around message cause their // end body tag is breaking // the visualization as html in the UI String receivedMessage = messageBuff.toString() // removes body start tag .replaceAll("\\<[bB][oO][dD][yY].*?>","") // removes body end tag .replaceAll("\\</[bB][oO][dD][yY].*?>",""); // for some reason &apos; is not rendered correctly // from our ui, lets use its equivalent. Other // similar chars(< > & ") seem ok. receivedMessage = receivedMessage.replaceAll("&apos;", "&#39;"); newMessage = createMessage(receivedMessage, HTML_MIME_TYPE, msg.getPacketID()); } } PacketExtension correctionExtension = msg.getExtension(MessageCorrectionExtension.NAMESPACE); String correctedMessageUID = null; if (correctionExtension != null) { correctedMessageUID = ((MessageCorrectionExtension) correctionExtension).getCorrectedMessageUID(); } Contact sourceContact = opSetPersPresence.findContactByID( (isPrivateMessaging? userFullId : userBareID)); if(msg.getType() == org.jivesoftware.smack.packet.Message.Type.error) { // error which is multichat and we don't know about the contact // is a muc message error which is missing muc extension // and is coming from the room, when we try to send message to // room which was deleted or offline on the server if(isPrivateMessaging && sourceContact == null) { if(privateContactRoom != null) { XMPPError error = packet.getError(); int errorResultCode = ChatRoomMessageDeliveryFailedEvent.UNKNOWN_ERROR; if(error != null && error.getCode() == 403) { errorResultCode = ChatRoomMessageDeliveryFailedEvent.FORBIDDEN; } String errorReason = error.getMessage(); ChatRoomMessageDeliveryFailedEvent evt = new ChatRoomMessageDeliveryFailedEvent( privateContactRoom, null, errorResultCode, errorReason, new Date(), newMessage); ((ChatRoomJabberImpl)privateContactRoom) .fireMessageEvent(evt); } return; } if (logger.isInfoEnabled()) logger.info("Message error received from " + userBareID); int errorResultCode = MessageDeliveryFailedEvent.UNKNOWN_ERROR; if (packet.getError() != null) { int errorCode = packet.getError().getCode(); if(errorCode == 503) { org.jivesoftware.smackx.packet.MessageEvent msgEvent = (org.jivesoftware.smackx.packet.MessageEvent) packet.getExtension("x", "jabber:x:event"); if(msgEvent != null && msgEvent.isOffline()) { errorResultCode = MessageDeliveryFailedEvent .OFFLINE_MESSAGES_NOT_SUPPORTED; } } } if (sourceContact == null) { sourceContact = opSetPersPresence.createVolatileContact( userFullId, isPrivateMessaging); } MessageDeliveryFailedEvent ev = new MessageDeliveryFailedEvent(newMessage, sourceContact, correctedMessageUID, errorResultCode); // ev = messageDeliveryFailedTransform(ev); if (ev != null) fireMessageEvent(ev); return; } putJidForAddress(userFullId, msg.getThread()); // In the second condition we filter all group chat messages, // because they are managed by the multi user chat operation set. if(sourceContact == null) { if (logger.isDebugEnabled()) logger.debug("received a message from an unknown contact: " + userBareID); //create the volatile contact sourceContact = opSetPersPresence .createVolatileContact( userFullId, isPrivateMessaging); } Date timestamp = new Date(); //Check for XEP-0091 timestamp (deprecated) PacketExtension delay = msg.getExtension("x", "jabber:x:delay"); if(delay != null && delay instanceof DelayInformation) { timestamp = ((DelayInformation)delay).getStamp(); } //check for XEP-0203 timestamp delay = msg.getExtension("delay", "urn:xmpp:delay"); if(delay != null && delay instanceof DelayInfo) { timestamp = ((DelayInfo)delay).getStamp(); } ContactResource resource = ((ContactJabberImpl) sourceContact) .getResourceFromJid(userFullId); EventObject msgEvt = null; if(!isForwardedSentMessage) msgEvt = new MessageReceivedEvent( newMessage, sourceContact, resource, timestamp, correctedMessageUID, isPrivateMessaging, privateContactRoom); else msgEvt = new MessageDeliveredEvent(newMessage, sourceContact, timestamp); // msgReceivedEvt = messageReceivedTransform(msgReceivedEvt); if (msgEvt != null) fireMessageEvent(msgEvt); } } /** * A filter that prevents this operation set from handling multi user chat * messages. */ private static class GroupMessagePacketFilter implements PacketFilter { /** * Returns <tt>true</tt> if <tt>packet</tt> is a <tt>Message</tt> and * false otherwise. * * @param packet the packet that we need to check. * * @return <tt>true</tt> if <tt>packet</tt> is a <tt>Message</tt> and * false otherwise. */ public boolean accept(Packet packet) { if(!(packet instanceof org.jivesoftware.smack.packet.Message)) return false; org.jivesoftware.smack.packet.Message msg = (org.jivesoftware.smack.packet.Message) packet; return !msg.getType().equals( org.jivesoftware.smack.packet.Message.Type.groupchat); } } /** * Subscribes this provider as interested in receiving notifications for * new mail messages from Google mail services such as Gmail or Google Apps. */ private void subscribeForGmailNotifications() { // first check support for the notification service String accountIDService = jabberProvider.getAccountID().getService(); boolean notificationsAreSupported = jabberProvider.isFeatureSupported( accountIDService, NewMailNotificationIQ.NAMESPACE); if (!notificationsAreSupported) { if (logger.isDebugEnabled()) logger.debug(accountIDService +" does not seem to provide a Gmail notification " +" service so we won't be trying to subscribe for it"); return; } if (logger.isDebugEnabled()) logger.debug(accountIDService +" seems to provide a Gmail notification " +" service so we will try to subscribe for it"); ProviderManager providerManager = ProviderManager.getInstance(); providerManager.addIQProvider( MailboxIQ.ELEMENT_NAME, MailboxIQ.NAMESPACE, new MailboxIQProvider()); providerManager.addIQProvider( NewMailNotificationIQ.ELEMENT_NAME, NewMailNotificationIQ.NAMESPACE, new NewMailNotificationProvider()); Connection connection = jabberProvider.getConnection(); connection.addPacketListener( new MailboxIQListener(), new PacketTypeFilter(MailboxIQ.class)); connection.addPacketListener( new NewMailNotificationListener(), new PacketTypeFilter(NewMailNotificationIQ.class)); if(opSetPersPresence.getCurrentStatusMessage().equals( JabberStatusEnum.OFFLINE)) return; //create a query with -1 values for newer-than-tid and //newer-than-time attributes MailboxQueryIQ mailboxQuery = new MailboxQueryIQ(); if (logger.isTraceEnabled()) logger.trace("sending mailNotification for acc: " + jabberProvider.getAccountID().getAccountUniqueID()); jabberProvider.getConnection().sendPacket(mailboxQuery); } /** * Creates an html description of the specified mailbox. * * @param mailboxIQ the mailboxIQ that we are to describe. * * @return an html description of <tt>mailboxIQ</tt> */ private String createMailboxDescription(MailboxIQ mailboxIQ) { int threadCount = mailboxIQ.getThreadCount(); String resourceHeaderKey = threadCount > 1 ? "service.gui.NEW_GMAIL_MANY_HEADER" : "service.gui.NEW_GMAIL_HEADER"; String resourceFooterKey = threadCount > 1 ? "service.gui.NEW_GMAIL_MANY_FOOTER" : "service.gui.NEW_GMAIL_FOOTER"; // FIXME Escape HTML! String newMailHeader = JabberActivator.getResources().getI18NString( resourceHeaderKey, new String[] { jabberProvider.getAccountID() .getService(), //{0} - service name mailboxIQ.getUrl(), //{1} - inbox URI Integer.toString( threadCount )//{2} - thread count }); StringBuilder message = new StringBuilder(newMailHeader); //we now start an html table for the threads. message.append("<table width=100% cellpadding=2 cellspacing=0 "); message.append("border=0 bgcolor=#e8eef7>"); Iterator<MailThreadInfo> threads = mailboxIQ.threads(); String maxThreadsStr = (String)JabberActivator.getConfigurationService() .getProperty(PNAME_MAX_GMAIL_THREADS_PER_NOTIFICATION); int maxThreads = 5; try { if(maxThreadsStr != null) maxThreads = Integer.parseInt(maxThreadsStr); } catch (NumberFormatException e) { if (logger.isDebugEnabled()) logger.debug("Failed to parse max threads count: "+maxThreads +". Going for default."); } //print a maximum of MAX_THREADS for (int i = 0; i < maxThreads && threads.hasNext(); i++) { message.append(threads.next().createHtmlDescription()); } message.append("</table><br/>"); if(threadCount > maxThreads) { String messageFooter = JabberActivator.getResources().getI18NString( resourceFooterKey, new String[] { mailboxIQ.getUrl(), //{0} - inbox URI Integer.toString( threadCount - maxThreads )//{1} - thread count }); message.append(messageFooter); } return message.toString(); } public String getRecentJIDForAddress(String address) { return recentJIDForAddress.get(address); } /** * Receives incoming MailNotification Packets */ private class MailboxIQListener implements PacketListener { /** * Handles incoming <tt>MailboxIQ</tt> packets. * * @param packet the IQ that we need to handle in case it is a * <tt>MailboxIQ</tt>. */ public void processPacket(Packet packet) { if(packet != null && !(packet instanceof MailboxIQ)) return; MailboxIQ mailboxIQ = (MailboxIQ) packet; if(mailboxIQ.getTotalMatched() < 1) return; //Get a reference to a dummy volatile contact Contact sourceContact = opSetPersPresence .findContactByID(jabberProvider.getAccountID().getService()); if(sourceContact == null) sourceContact = opSetPersPresence.createVolatileContact( jabberProvider.getAccountID().getService()); lastReceivedMailboxResultTime = mailboxIQ.getResultTime(); String newMail = createMailboxDescription(mailboxIQ); Message newMailMessage = new MessageJabberImpl( newMail, HTML_MIME_TYPE, DEFAULT_MIME_ENCODING, null); MessageReceivedEvent msgReceivedEvt = new MessageReceivedEvent( newMailMessage, sourceContact, new Date(), MessageReceivedEvent.SYSTEM_MESSAGE_RECEIVED); fireMessageEvent(msgReceivedEvt); } } /** * Receives incoming NewMailNotification Packets. */ private class NewMailNotificationListener implements PacketListener { /** * Handles incoming <tt>NewMailNotificationIQ</tt> packets. * * @param packet the IQ that we need to handle in case it is a * <tt>NewMailNotificationIQ</tt>. */ public void processPacket(Packet packet) { if(packet != null && !(packet instanceof NewMailNotificationIQ)) return; //check whether we are still enabled. boolean enableGmailNotifications = jabberProvider .getAccountID() .getAccountPropertyBoolean( "GMAIL_NOTIFICATIONS_ENABLED", false); if (!enableGmailNotifications) return; if(opSetPersPresence.getCurrentStatusMessage() .equals(JabberStatusEnum.OFFLINE)) return; MailboxQueryIQ mailboxQueryIQ = new MailboxQueryIQ(); if(lastReceivedMailboxResultTime != -1) mailboxQueryIQ.setNewerThanTime( lastReceivedMailboxResultTime); if (logger.isTraceEnabled()) logger.trace( "send mailNotification for acc: " + jabberProvider.getAccountID().getAccountUniqueID()); jabberProvider.getConnection().sendPacket(mailboxQueryIQ); } } /** * Returns the inactivity timeout in milliseconds. * * @return The inactivity timeout in milliseconds. Or -1 if undefined */ public long getInactivityTimeout() { return JID_INACTIVITY_TIMEOUT; } /** * Adds additional filters for incoming messages. To be able to skip some * messages. * @param filter to add */ public void addMessageFilters(PacketFilter filter) { this.packetFilters.add(filter); } /** * Returns the next unique thread id. Each thread id made up of a short * alphanumeric prefix along with a unique numeric value. * * @return the next thread id. */ public static synchronized String nextThreadID() { return prefix + Long.toString(id++); } }
./CrossVul/dataset_final_sorted/CWE-346/java/bad_3133_0
crossvul-java_data_bad_3047_1
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc. * * 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.model; import hudson.Util; import hudson.XmlFile; import hudson.model.listeners.ItemListener; import hudson.security.AccessControlled; import hudson.util.CopyOnWriteMap; import hudson.util.Function1; import hudson.util.Secret; import jenkins.model.Jenkins; import jenkins.util.xml.XMLUtils; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import jenkins.security.NotReallyRoleSensitiveCallable; import org.acegisecurity.AccessDeniedException; import org.xml.sax.SAXException; /** * Defines a bunch of static methods to be used as a "mix-in" for {@link ItemGroup} * implementations. Not meant for a consumption from outside {@link ItemGroup}s. * * @author Kohsuke Kawaguchi * @see ViewGroupMixIn */ public abstract class ItemGroupMixIn { /** * {@link ItemGroup} for which we are working. */ private final ItemGroup parent; private final AccessControlled acl; protected ItemGroupMixIn(ItemGroup parent, AccessControlled acl) { this.parent = parent; this.acl = acl; } /* * Callback methods to be implemented by the ItemGroup implementation. */ /** * Adds a newly created item to the parent. */ protected abstract void add(TopLevelItem item); /** * Assigns the root directory for a prospective item. */ protected abstract File getRootDirFor(String name); /* * The rest is the methods that provide meat. */ /** * Loads all the child {@link Item}s. * * @param modulesDir * Directory that contains sub-directories for each child item. */ public static <K,V extends Item> Map<K,V> loadChildren(ItemGroup parent, File modulesDir, Function1<? extends K,? super V> key) { modulesDir.mkdirs(); // make sure it exists File[] subdirs = modulesDir.listFiles(new FileFilter() { public boolean accept(File child) { return child.isDirectory(); } }); CopyOnWriteMap.Tree<K,V> configurations = new CopyOnWriteMap.Tree<K,V>(); for (File subdir : subdirs) { try { // Try to retain the identity of an existing child object if we can. V item = (V) parent.getItem(subdir.getName()); if (item == null) { XmlFile xmlFile = Items.getConfigFile(subdir); if (xmlFile.exists()) { item = (V) Items.load(parent, subdir); } else { Logger.getLogger(ItemGroupMixIn.class.getName()).log(Level.WARNING, "could not find file " + xmlFile.getFile()); continue; } } else { item.onLoad(parent, subdir.getName()); } configurations.put(key.call(item), item); } catch (Exception e) { Logger.getLogger(ItemGroupMixIn.class.getName()).log(Level.WARNING, "could not load " + subdir, e); } } return configurations; } /** * {@link Item} -> name function. */ public static final Function1<String,Item> KEYED_BY_NAME = new Function1<String, Item>() { public String call(Item item) { return item.getName(); } }; /** * Creates a {@link TopLevelItem} from the submission of the '/lib/hudson/newFromList/formList' * or throws an exception if it fails. */ public synchronized TopLevelItem createTopLevelItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { acl.checkPermission(Item.CREATE); TopLevelItem result; String requestContentType = req.getContentType(); if(requestContentType==null) throw new Failure("No Content-Type header set"); boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml"); String name = req.getParameter("name"); if(name==null) throw new Failure("Query parameter 'name' is required"); {// check if the name looks good Jenkins.checkGoodName(name); name = name.trim(); if(parent.getItem(name)!=null) throw new Failure(Messages.Hudson_JobAlreadyExists(name)); } String mode = req.getParameter("mode"); if(mode!=null && mode.equals("copy")) { String from = req.getParameter("from"); // resolve a name to Item Item src = null; if (!from.startsWith("/")) src = parent.getItem(from); if (src==null) src = Jenkins.getInstance().getItemByFullName(from); if(src==null) { if(Util.fixEmpty(from)==null) throw new Failure("Specify which job to copy"); else throw new Failure("No such job: "+from); } if (!(src instanceof TopLevelItem)) throw new Failure(from+" cannot be copied"); result = copy((TopLevelItem) src,name); } else { if(isXmlSubmission) { result = createProjectFromXML(name, req.getInputStream()); rsp.setStatus(HttpServletResponse.SC_OK); return result; } else { if(mode==null) throw new Failure("No mode given"); TopLevelItemDescriptor descriptor = Items.all().findByName(mode); if (descriptor == null) { throw new Failure("No item type ‘" + mode + "’ is known"); } descriptor.checkApplicableIn(parent); acl.getACL().checkCreatePermission(parent, descriptor); // create empty job and redirect to the project config screen result = createProject(descriptor, name, true); } } rsp.sendRedirect2(redirectAfterCreateItem(req, result)); return result; } /** * Computes the redirection target URL for the newly created {@link TopLevelItem}. */ protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException { return req.getContextPath()+'/'+result.getUrl()+"configure"; } /** * Copies an existing {@link TopLevelItem} to a new name. */ @SuppressWarnings({"unchecked"}) public synchronized <T extends TopLevelItem> T copy(T src, String name) throws IOException { acl.checkPermission(Item.CREATE); src.checkPermission(Item.EXTENDED_READ); XmlFile srcConfigFile = Items.getConfigFile(src); if (!src.hasPermission(Item.CONFIGURE)) { Matcher matcher = AbstractItem.SECRET_PATTERN.matcher(srcConfigFile.asString()); while (matcher.find()) { if (Secret.decrypt(matcher.group(1)) != null) { // AccessDeniedException2 does not permit a custom message, and anyway redirecting the user to the login screen is obviously pointless. throw new AccessDeniedException(Messages.ItemGroupMixIn_may_not_copy_as_it_contains_secrets_and_(src.getFullName(), Jenkins.getAuthentication().getName(), Item.PERMISSIONS.title, Item.EXTENDED_READ.name, Item.CONFIGURE.name)); } } } src.getDescriptor().checkApplicableIn(parent); acl.getACL().checkCreatePermission(parent, src.getDescriptor()); T result = (T)createProject(src.getDescriptor(),name,false); // copy config Util.copyFile(srcConfigFile.getFile(), Items.getConfigFile(result).getFile()); // reload from the new config final File rootDir = result.getRootDir(); result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<T,IOException>() { @Override public T call() throws IOException { return (T) Items.load(parent, rootDir); } }); result.onCopiedFrom(src); add(result); ItemListener.fireOnCopied(src,result); Jenkins.getInstance().rebuildDependencyGraphAsync(); return result; } public synchronized TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { acl.checkPermission(Item.CREATE); Jenkins.getInstance().getProjectNamingStrategy().checkName(name); if (parent.getItem(name) != null) { throw new IllegalArgumentException(parent.getDisplayName() + " already contains an item '" + name + "'"); } // TODO what if we have no DISCOVER permission on the existing job? // place it as config.xml File configXml = Items.getConfigFile(getRootDirFor(name)).getFile(); final File dir = configXml.getParentFile(); dir.mkdirs(); boolean success = false; try { XMLUtils.safeTransform((Source)new StreamSource(xml), new StreamResult(configXml)); // load it TopLevelItem result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<TopLevelItem,IOException>() { @Override public TopLevelItem call() throws IOException { return (TopLevelItem) Items.load(parent, dir); } }); success = acl.getACL().hasCreatePermission(Jenkins.getAuthentication(), parent, result.getDescriptor()) && result.getDescriptor().isApplicableIn(parent); add(result); ItemListener.fireOnCreated(result); Jenkins.getInstance().rebuildDependencyGraphAsync(); return result; } catch (TransformerException e) { success = false; throw new IOException("Failed to persist config.xml", e); } catch (SAXException e) { success = false; throw new IOException("Failed to persist config.xml", e); } catch (IOException e) { success = false; throw e; } catch (RuntimeException e) { success = false; throw e; } finally { if (!success) { // if anything fails, delete the config file to avoid further confusion Util.deleteRecursive(dir); } } } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException { acl.checkPermission(Item.CREATE); type.checkApplicableIn(parent); acl.getACL().checkCreatePermission(parent, type); Jenkins.getInstance().getProjectNamingStrategy().checkName(name); if(parent.getItem(name)!=null) throw new IllegalArgumentException("Project of the name "+name+" already exists"); // TODO problem with DISCOVER as noted above TopLevelItem item = type.newInstance(parent, name); try { callOnCreatedFromScratch(item); } catch (AbstractMethodError e) { // ignore this error. Must be older plugin that doesn't have this method } item.save(); add(item); Jenkins.getInstance().rebuildDependencyGraphAsync(); if (notify) ItemListener.fireOnCreated(item); return item; } /** * Pointless wrapper to avoid HotSpot problem. See JENKINS-5756 */ private void callOnCreatedFromScratch(TopLevelItem item) { item.onCreatedFromScratch(); } }
./CrossVul/dataset_final_sorted/CWE-269/java/bad_3047_1
crossvul-java_data_bad_3047_2
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * 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.model; import com.thoughtworks.xstream.XStream; import hudson.DescriptorExtensionList; import hudson.Extension; import hudson.XmlFile; import hudson.model.listeners.ItemListener; import hudson.remoting.Callable; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.triggers.Trigger; import hudson.util.DescriptorList; import hudson.util.EditDistance; import hudson.util.XStream2; import jenkins.model.Jenkins; import org.acegisecurity.Authentication; import org.apache.commons.lang.StringUtils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Stack; import java.util.StringTokenizer; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import jenkins.model.DirectlyModifiableTopLevelItemGroup; import org.apache.commons.io.FileUtils; /** * Convenience methods related to {@link Item}. * * @author Kohsuke Kawaguchi */ public class Items { /** * List of all installed {@link TopLevelItem} types. * * @deprecated as of 1.286 * Use {@link #all()} for read access and {@link Extension} for registration. */ @Deprecated public static final List<TopLevelItemDescriptor> LIST = (List)new DescriptorList<TopLevelItem>(TopLevelItem.class); /** * Used to behave differently when loading posted configuration as opposed to persisted configuration. * @see Trigger#start * @since 1.482 */ private static final ThreadLocal<Boolean> updatingByXml = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; /** * Runs a block while making {@link #currentlyUpdatingByXml} be temporarily true. * Use this when you are creating or changing an item. * @param <V> a return value type (may be {@link Void}) * @param <T> an error type (may be {@link Error}) * @param callable a block, typically running {@link #load} or {@link Item#onLoad} * @return whatever {@code callable} returned * @throws T anything {@code callable} throws * @since 1.546 */ public static <V,T extends Throwable> V whileUpdatingByXml(Callable<V,T> callable) throws T { updatingByXml.set(true); try { return callable.call(); } finally { updatingByXml.set(false); } } /** * Checks whether we are in the middle of creating or configuring an item via XML. * Used to determine the {@code newInstance} parameter for {@link Trigger#start}. * @return true if {@link #whileUpdatingByXml} is currently being called, false for example when merely starting Jenkins or reloading from disk * @since 1.546 */ public static boolean currentlyUpdatingByXml() { return updatingByXml.get(); } /** * Returns all the registered {@link TopLevelItemDescriptor}s. */ public static DescriptorExtensionList<TopLevelItem,TopLevelItemDescriptor> all() { return Jenkins.getInstance().<TopLevelItem,TopLevelItemDescriptor>getDescriptorList(TopLevelItem.class); } /** * Returns all the registered {@link TopLevelItemDescriptor}s that the current security principal is allowed to * create within the specified item group. * * @since TODO */ public static List<TopLevelItemDescriptor> all(ItemGroup c) { return all(Jenkins.getAuthentication(), c); } /** * Returns all the registered {@link TopLevelItemDescriptor}s that the specified security principal is allowed to * create within the specified item group. * * @since TODO */ public static List<TopLevelItemDescriptor> all(Authentication a, ItemGroup c) { List<TopLevelItemDescriptor> result = new ArrayList<TopLevelItemDescriptor>(); ACL acl; if (c instanceof AccessControlled) { acl = ((AccessControlled) c).getACL(); } else { // fall back to root acl = Jenkins.getInstance().getACL(); } for (TopLevelItemDescriptor d: all()) { if (acl.hasCreatePermission(a, c, d) && d.isApplicableIn(c)) { result.add(d); } } return result; } /** * @deprecated Underspecified what the parameter is. {@link Descriptor#getId}? A {@link Describable} class name? */ public static TopLevelItemDescriptor getDescriptor(String fqcn) { return Descriptor.find(all(), fqcn); } /** * Converts a list of items into a comma-separated list of full names. */ public static String toNameList(Collection<? extends Item> items) { StringBuilder buf = new StringBuilder(); for (Item item : items) { if(buf.length()>0) buf.append(", "); buf.append(item.getFullName()); } return buf.toString(); } /** * @deprecated as of 1.406 * Use {@link #fromNameList(ItemGroup, String, Class)} */ @Deprecated public static <T extends Item> List<T> fromNameList(String list, Class<T> type) { return fromNameList(null,list,type); } /** * Does the opposite of {@link #toNameList(Collection)}. */ public static <T extends Item> List<T> fromNameList(ItemGroup context, @Nonnull String list, @Nonnull Class<T> type) { Jenkins hudson = Jenkins.getInstance(); List<T> r = new ArrayList<T>(); StringTokenizer tokens = new StringTokenizer(list,","); while(tokens.hasMoreTokens()) { String fullName = tokens.nextToken().trim(); T item = hudson.getItem(fullName, context, type); if(item!=null) r.add(item); } return r; } /** * Computes the canonical full name of a relative path in an {@link ItemGroup} context, handling relative * positions ".." and "." as absolute path starting with "/". The resulting name is the item fullName from Jenkins * root. */ public static String getCanonicalName(ItemGroup context, String path) { String[] c = context.getFullName().split("/"); String[] p = path.split("/"); Stack<String> name = new Stack<String>(); for (int i=0; i<c.length;i++) { if (i==0 && c[i].equals("")) continue; name.push(c[i]); } for (int i=0; i<p.length;i++) { if (i==0 && p[i].equals("")) { // Absolute path starting with a "/" name.clear(); continue; } if (p[i].equals("..")) { if (name.size() == 0) { throw new IllegalArgumentException(String.format( "Illegal relative path '%s' within context '%s'", path, context.getFullName() )); } name.pop(); continue; } if (p[i].equals(".")) { continue; } name.push(p[i]); } return StringUtils.join(name, '/'); } /** * Computes the relative name of list of items after a rename or move occurred. * Used to manage job references as names in plugins to support {@link hudson.model.listeners.ItemListener#onLocationChanged}. * <p> * In a hierarchical context, when a plugin has a reference to a job as <code>../foo/bar</code> this method will * handle the relative path as "foo" is renamed to "zot" to compute <code>../zot/bar</code> * * @param oldFullName the old full name of the item * @param newFullName the new full name of the item * @param relativeNames coma separated list of Item relative names * @param context the {link ItemGroup} relative names refer to * @return relative name for the renamed item, based on the same ItemGroup context */ public static String computeRelativeNamesAfterRenaming(String oldFullName, String newFullName, String relativeNames, ItemGroup context) { StringTokenizer tokens = new StringTokenizer(relativeNames,","); List<String> newValue = new ArrayList<String>(); while(tokens.hasMoreTokens()) { String relativeName = tokens.nextToken().trim(); String canonicalName = getCanonicalName(context, relativeName); if (canonicalName.equals(oldFullName) || canonicalName.startsWith(oldFullName+'/')) { String newCanonicalName = newFullName + canonicalName.substring(oldFullName.length()); if (relativeName.startsWith("/")) { newValue.add("/" + newCanonicalName); } else { newValue.add(getRelativeNameFrom(newCanonicalName, context.getFullName())); } } else { newValue.add(relativeName); } } return StringUtils.join(newValue, ","); } // Had difficulty adapting the version in Functions to use no live items, so rewrote it: static String getRelativeNameFrom(String itemFullName, String groupFullName) { String[] itemFullNameA = itemFullName.isEmpty() ? new String[0] : itemFullName.split("/"); String[] groupFullNameA = groupFullName.isEmpty() ? new String[0] : groupFullName.split("/"); for (int i = 0; ; i++) { if (i == itemFullNameA.length) { if (i == groupFullNameA.length) { // itemFullName and groupFullName are identical return "."; } else { // itemFullName is an ancestor of groupFullName; insert ../ for rest of groupFullName StringBuilder b = new StringBuilder(); for (int j = 0; j < groupFullNameA.length - itemFullNameA.length; j++) { if (j > 0) { b.append('/'); } b.append(".."); } return b.toString(); } } else if (i == groupFullNameA.length) { // groupFullName is an ancestor of itemFullName; insert rest of itemFullName StringBuilder b = new StringBuilder(); for (int j = i; j < itemFullNameA.length; j++) { if (j > i) { b.append('/'); } b.append(itemFullNameA[j]); } return b.toString(); } else if (itemFullNameA[i].equals(groupFullNameA[i])) { // identical up to this point continue; } else { // first mismatch; insert ../ for rest of groupFullName, then rest of itemFullName StringBuilder b = new StringBuilder(); for (int j = i; j < groupFullNameA.length; j++) { if (j > i) { b.append('/'); } b.append(".."); } for (int j = i; j < itemFullNameA.length; j++) { b.append('/').append(itemFullNameA[j]); } return b.toString(); } } } /** * Loads a {@link Item} from a config file. * * @param dir * The directory that contains the config file, not the config file itself. */ public static Item load(ItemGroup parent, File dir) throws IOException { Item item = (Item)getConfigFile(dir).read(); item.onLoad(parent,dir.getName()); return item; } /** * The file we save our configuration. */ public static XmlFile getConfigFile(File dir) { return new XmlFile(XSTREAM,new File(dir,"config.xml")); } /** * The file we save our configuration. */ public static XmlFile getConfigFile(Item item) { return getConfigFile(item.getRootDir()); } /** * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree * and filter them by the given type. * * @since 1.512 */ public static <T extends Item> List<T> getAllItems(final ItemGroup root, Class<T> type) { List<T> r = new ArrayList<T>(); getAllItems(root, type, r); return r; } private static <T extends Item> void getAllItems(final ItemGroup root, Class<T> type, List<T> r) { List<Item> items = new ArrayList<Item>(((ItemGroup<?>) root).getItems()); Collections.sort(items, new Comparator<Item>() { @Override public int compare(Item i1, Item i2) { return name(i1).compareToIgnoreCase(name(i2)); } String name(Item i) { String n = i.getName(); if (i instanceof ItemGroup) { n += '/'; } return n; } }); for (Item i : items) { if (type.isInstance(i)) { if (i.hasPermission(Item.READ)) { r.add(type.cast(i)); } } if (i instanceof ItemGroup) { getAllItems((ItemGroup) i, type, r); } } } /** * Finds an item whose name (when referenced from the specified context) is closest to the given name. * @param <T> the type of item being considered * @param type same as {@code T} * @param name the supplied name * @param context a context to start from (used to compute relative names) * @return the closest available item * @since 1.538 */ public static @CheckForNull <T extends Item> T findNearest(Class<T> type, String name, ItemGroup context) { List<T> projects = Jenkins.getInstance().getAllItems(type); String[] names = new String[projects.size()]; for (int i = 0; i < projects.size(); i++) { names[i] = projects.get(i).getRelativeNameFrom(context); } String nearest = EditDistance.findNearest(name, names); return Jenkins.getInstance().getItem(nearest, context, type); } /** * Moves an item between folders (or top level). * Fires all relevant events but does not verify that the item’s directory is not currently being used in some way (for example by a running build). * Does not check any permissions. * @param item some item (job or folder) * @param destination the destination of the move (a folder or {@link Jenkins}); not the current parent (or you could just call {@link AbstractItem#renameTo}) * @return the new item (usually the same object as {@code item}) * @throws IOException if the move fails, or some subsequent step fails (directory might have already been moved) * @throws IllegalArgumentException if the move would really be a rename, or the destination cannot accept the item, or the destination already has an item of that name * @since 1.548 */ public static <I extends AbstractItem & TopLevelItem> I move(I item, DirectlyModifiableTopLevelItemGroup destination) throws IOException, IllegalArgumentException { DirectlyModifiableTopLevelItemGroup oldParent = (DirectlyModifiableTopLevelItemGroup) item.getParent(); if (oldParent == destination) { throw new IllegalArgumentException(); } // TODO verify that destination is to not equal to, or inside, item if (!destination.canAdd(item)) { throw new IllegalArgumentException(); } String name = item.getName(); if (destination.getItem(name) != null) { throw new IllegalArgumentException(name + " already exists"); } String oldFullName = item.getFullName(); // TODO AbstractItem.renameTo has a more baroque implementation; factor it out into a utility method perhaps? File destDir = destination.getRootDirFor(item); FileUtils.forceMkdir(destDir.getParentFile()); FileUtils.moveDirectory(item.getRootDir(), destDir); oldParent.remove(item); I newItem = destination.add(item, name); item.movedTo(destination, newItem, destDir); ItemListener.fireLocationChange(newItem, oldFullName); return newItem; } /** * Used to load/save job configuration. * * When you extend {@link Job} in a plugin, try to put the alias so * that it produces a reasonable XML. */ public static final XStream XSTREAM = new XStream2(); /** * Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily. */ public static final XStream2 XSTREAM2 = (XStream2)XSTREAM; static { XSTREAM.alias("project",FreeStyleProject.class); } }
./CrossVul/dataset_final_sorted/CWE-269/java/bad_3047_2
crossvul-java_data_good_3057_0
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe, * Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc., * Yahoo!, Inc. * * 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 jenkins.model; import antlr.ANTLRException; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.inject.Injector; import com.thoughtworks.xstream.XStream; import hudson.BulkChange; import hudson.DNSMultiCast; import hudson.DescriptorExtensionList; import hudson.Extension; import hudson.ExtensionComponent; import hudson.ExtensionFinder; import hudson.ExtensionList; import hudson.ExtensionPoint; import hudson.FilePath; import hudson.Functions; import hudson.Launcher; import hudson.Launcher.LocalLauncher; import hudson.LocalPluginManager; import hudson.Lookup; import hudson.Plugin; import hudson.PluginManager; import hudson.PluginWrapper; import hudson.ProxyConfiguration; import hudson.TcpSlaveAgentListener; import hudson.UDPBroadcastThread; import hudson.Util; import hudson.WebAppMain; import hudson.XmlFile; import hudson.cli.declarative.CLIMethod; import hudson.cli.declarative.CLIResolver; import hudson.init.InitMilestone; import hudson.init.InitStrategy; import hudson.init.TerminatorFinder; import hudson.lifecycle.Lifecycle; import hudson.lifecycle.RestartNotSupportedException; import hudson.logging.LogRecorderManager; import hudson.markup.EscapedMarkupFormatter; import hudson.markup.MarkupFormatter; import hudson.model.AbstractCIBase; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.AdministrativeMonitor; import hudson.model.AllView; import hudson.model.Api; import hudson.model.Computer; import hudson.model.ComputerSet; import hudson.model.DependencyGraph; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Descriptor.FormException; import hudson.model.DescriptorByNameOwner; import hudson.model.DirectoryBrowserSupport; import hudson.model.Failure; import hudson.model.Fingerprint; import hudson.model.FingerprintCleanupThread; import hudson.model.FingerprintMap; import hudson.model.Hudson; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.ItemGroupMixIn; import hudson.model.Items; import hudson.model.JDK; import hudson.model.Job; import hudson.model.JobPropertyDescriptor; import hudson.model.Label; import hudson.model.ListView; import hudson.model.LoadBalancer; import hudson.model.LoadStatistics; import hudson.model.ManagementLink; import hudson.model.Messages; import hudson.model.ModifiableViewGroup; import hudson.model.NoFingerprintMatch; import hudson.model.Node; import hudson.model.OverallLoadStatistics; import hudson.model.PaneStatusProperties; import hudson.model.Project; import hudson.model.Queue; import hudson.model.Queue.FlyweightTask; import hudson.model.RestartListener; import hudson.model.RootAction; import hudson.model.Slave; import hudson.model.TaskListener; import hudson.model.TopLevelItem; import hudson.model.TopLevelItemDescriptor; import hudson.model.UnprotectedRootAction; import hudson.model.UpdateCenter; import hudson.model.User; import hudson.model.View; import hudson.model.ViewGroupMixIn; import hudson.model.WorkspaceCleanupThread; import hudson.model.labels.LabelAtom; import hudson.model.listeners.ItemListener; import hudson.model.listeners.SCMListener; import hudson.model.listeners.SaveableListener; import hudson.remoting.Callable; import hudson.remoting.LocalChannel; import hudson.remoting.VirtualChannel; import hudson.scm.RepositoryBrowser; import hudson.scm.SCM; import hudson.search.CollectionSearchIndex; import hudson.search.SearchIndexBuilder; import hudson.search.SearchItem; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.security.AuthorizationStrategy; import hudson.security.BasicAuthenticationFilter; import hudson.security.FederatedLoginService; import hudson.security.FullControlOnceLoggedInAuthorizationStrategy; import hudson.security.HudsonFilter; import hudson.security.LegacyAuthorizationStrategy; import hudson.security.LegacySecurityRealm; import hudson.security.Permission; import hudson.security.PermissionGroup; import hudson.security.PermissionScope; import hudson.security.SecurityMode; import hudson.security.SecurityRealm; import hudson.security.csrf.CrumbIssuer; import hudson.slaves.Cloud; import hudson.slaves.ComputerListener; import hudson.slaves.DumbSlave; import hudson.slaves.EphemeralNode; import hudson.slaves.NodeDescriptor; import hudson.slaves.NodeList; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.slaves.NodeProvisioner; import hudson.slaves.OfflineCause; import hudson.slaves.RetentionStrategy; import hudson.tasks.BuildWrapper; import hudson.tasks.Builder; import hudson.tasks.Publisher; import hudson.triggers.SafeTimerTask; import hudson.triggers.Trigger; import hudson.triggers.TriggerDescriptor; import hudson.util.AdministrativeError; import hudson.util.CaseInsensitiveComparator; import hudson.util.ClockDifference; import hudson.util.CopyOnWriteList; import hudson.util.CopyOnWriteMap; import hudson.util.DaemonThreadFactory; import hudson.util.DescribableList; import hudson.util.FormApply; import hudson.util.FormValidation; import hudson.util.Futures; import hudson.util.HudsonIsLoading; import hudson.util.HudsonIsRestarting; import hudson.util.IOUtils; import hudson.util.Iterators; import hudson.util.JenkinsReloadFailed; import hudson.util.Memoizer; import hudson.util.MultipartFormDataParser; import hudson.util.NamingThreadFactory; import hudson.util.RemotingDiagnostics; import hudson.util.RemotingDiagnostics.HeapDump; import hudson.util.TextFile; import hudson.util.TimeUnit2; import hudson.util.VersionNumber; import hudson.util.XStream2; import hudson.views.DefaultMyViewsTabBar; import hudson.views.DefaultViewsTabBar; import hudson.views.MyViewsTabBar; import hudson.views.ViewsTabBar; import hudson.widgets.Widget; import jenkins.ExtensionComponentSet; import jenkins.ExtensionRefreshException; import jenkins.InitReactorRunner; import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy; import jenkins.security.ConfidentialKey; import jenkins.security.ConfidentialStore; import jenkins.security.SecurityListener; import jenkins.security.MasterToSlaveCallable; import jenkins.slaves.WorkspaceLocator; import jenkins.util.Timer; import jenkins.util.io.FileBoolean; import net.sf.json.JSONObject; import org.acegisecurity.AccessDeniedException; import org.acegisecurity.AcegiSecurityException; import org.acegisecurity.Authentication; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.GrantedAuthorityImpl; import org.acegisecurity.context.SecurityContextHolder; import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken; import org.acegisecurity.ui.AbstractProcessingFilter; import org.apache.commons.jelly.JellyException; import org.apache.commons.jelly.Script; import org.apache.commons.logging.LogFactory; import org.jvnet.hudson.reactor.Executable; import org.jvnet.hudson.reactor.Reactor; import org.jvnet.hudson.reactor.ReactorException; import org.jvnet.hudson.reactor.Task; import org.jvnet.hudson.reactor.TaskBuilder; import org.jvnet.hudson.reactor.TaskGraphBuilder; import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.MetaClass; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerFallback; import org.kohsuke.stapler.StaplerProxy; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.WebApp; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import org.kohsuke.stapler.framework.adjunct.AdjunctManager; import org.kohsuke.stapler.interceptor.RequirePOST; import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff; import org.kohsuke.stapler.jelly.JellyRequestDispatcher; import org.xml.sax.InputSource; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.crypto.SecretKey; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.BindException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import static hudson.Util.*; import static hudson.init.InitMilestone.*; import hudson.util.LogTaskListener; import static java.util.logging.Level.*; import static javax.servlet.http.HttpServletResponse.*; import org.kohsuke.stapler.WebMethod; /** * Root object of the system. * * @author Kohsuke Kawaguchi */ @ExportedBean public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback, ModifiableViewGroup, AccessControlled, DescriptorByNameOwner, ModelObjectWithContextMenu, ModelObjectWithChildren { private transient final Queue queue; /** * Stores various objects scoped to {@link Jenkins}. */ public transient final Lookup lookup = new Lookup(); /** * We update this field to the current version of Jenkins whenever we save {@code config.xml}. * This can be used to detect when an upgrade happens from one version to next. * * <p> * Since this field is introduced starting 1.301, "1.0" is used to represent every version * up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or * "?", etc., so parsing needs to be done with a care. * * @since 1.301 */ // this field needs to be at the very top so that other components can look at this value even during unmarshalling private String version = "1.0"; /** * Number of executors of the master node. */ private int numExecutors = 2; /** * Job allocation strategy. */ private Mode mode = Mode.NORMAL; /** * False to enable anyone to do anything. * Left as a field so that we can still read old data that uses this flag. * * @see #authorizationStrategy * @see #securityRealm */ private Boolean useSecurity; /** * Controls how the * <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a> * is handled in Jenkins. * <p> * This ultimately controls who has access to what. * * Never null. */ private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED; /** * Controls a part of the * <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a> * handling in Jenkins. * <p> * Intuitively, this corresponds to the user database. * * See {@link HudsonFilter} for the concrete authentication protocol. * * Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to * update this field. * * @see #getSecurity() * @see #setSecurityRealm(SecurityRealm) */ private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION; /** * Disables the remember me on this computer option in the standard login screen. * * @since 1.534 */ private volatile boolean disableRememberMe; /** * The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention? */ private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; /** * Root directory for the workspaces. * This value will be variable-expanded as per {@link #expandVariablesForDirectory}. * @see #getWorkspaceFor(TopLevelItem) */ private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME; /** * Root directory for the builds. * This value will be variable-expanded as per {@link #expandVariablesForDirectory}. * @see #getBuildDirFor(Job) */ private String buildsDir = "${ITEM_ROOTDIR}/builds"; /** * Message displayed in the top page. */ private String systemMessage; private MarkupFormatter markupFormatter; /** * Root directory of the system. */ public transient final File root; /** * Where are we in the initialization? */ private transient volatile InitMilestone initLevel = InitMilestone.STARTED; /** * All {@link Item}s keyed by their {@link Item#getName() name}s. */ /*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE); /** * The sole instance. */ private static Jenkins theInstance; private transient volatile boolean isQuietingDown; private transient volatile boolean terminating; private List<JDK> jdks = new ArrayList<JDK>(); private transient volatile DependencyGraph dependencyGraph; private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean(); /** * Currently active Views tab bar. */ private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar(); /** * Currently active My Views tab bar. */ private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar(); /** * All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}. */ private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() { public ExtensionList compute(Class key) { return ExtensionList.create(Jenkins.this,key); } }; /** * All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}. */ private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() { public DescriptorExtensionList compute(Class key) { return DescriptorExtensionList.createDescriptorList(Jenkins.this,key); } }; /** * {@link Computer}s in this Jenkins system. Read-only. */ protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>(); /** * Active {@link Cloud}s. */ public final Hudson.CloudList clouds = new Hudson.CloudList(this); public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> { public CloudList(Jenkins h) { super(h); } public CloudList() {// needed for XStream deserialization } public Cloud getByName(String name) { for (Cloud c : this) if (c.name.equals(name)) return c; return null; } @Override protected void onModified() throws IOException { super.onModified(); Jenkins.getInstance().trimLabels(); } } /** * Legacy store of the set of installed cluster nodes. * @deprecated in favour of {@link Nodes} */ @Deprecated protected transient volatile NodeList slaves; /** * The holder of the set of installed cluster nodes. * * @since 1.607 */ private transient final Nodes nodes = new Nodes(this); /** * Quiet period. * * This is {@link Integer} so that we can initialize it to '5' for upgrading users. */ /*package*/ Integer quietPeriod; /** * Global default for {@link AbstractProject#getScmCheckoutRetryCount()} */ /*package*/ int scmCheckoutRetryCount; /** * {@link View}s. */ private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>(); /** * Name of the primary view. * <p> * Start with null, so that we can upgrade pre-1.269 data well. * @since 1.269 */ private volatile String primaryView; private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) { protected List<View> views() { return views; } protected String primaryView() { return primaryView; } protected void primaryView(String name) { primaryView=name; } }; private transient final FingerprintMap fingerprintMap = new FingerprintMap(); /** * Loaded plugins. */ public transient final PluginManager pluginManager; public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener; private transient UDPBroadcastThread udpBroadcastThread; private transient DNSMultiCast dnsMultiCast; /** * List of registered {@link SCMListener}s. */ private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>(); /** * TCP slave agent port. * 0 for random, -1 to disable. */ private int slaveAgentPort =0; /** * Whitespace-separated labels assigned to the master as a {@link Node}. */ private String label=""; /** * {@link hudson.security.csrf.CrumbIssuer} */ private volatile CrumbIssuer crumbIssuer; /** * All labels known to Jenkins. This allows us to reuse the same label instances * as much as possible, even though that's not a strict requirement. */ private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>(); /** * Load statistics of the entire system. * * This includes every executor and every job in the system. */ @Exported public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics(); /** * Load statistics of the free roaming jobs and slaves. * * This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes. * * @since 1.467 */ @Exported public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics(); /** * {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}. * @since 1.467 */ public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad); /** * @deprecated as of 1.467 * Use {@link #unlabeledNodeProvisioner}. * This was broken because it was tracking all the executors in the system, but it was only tracking * free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive * slaves and free-roaming jobs in the queue. */ @Restricted(NoExternalUse.class) @Deprecated public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner; public transient final ServletContext servletContext; /** * Transient action list. Useful for adding navigation items to the navigation bar * on the left. */ private transient final List<Action> actions = new CopyOnWriteArrayList<Action>(); /** * List of master node properties */ private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this); /** * List of global properties */ private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this); /** * {@link AdministrativeMonitor}s installed on this system. * * @see AdministrativeMonitor */ public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class); /** * Widgets on Jenkins. */ private transient final List<Widget> widgets = getExtensionList(Widget.class); /** * {@link AdjunctManager} */ private transient final AdjunctManager adjuncts; /** * Code that handles {@link ItemGroup} work. */ private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) { @Override protected void add(TopLevelItem item) { items.put(item.getName(),item); } @Override protected File getRootDirFor(String name) { return Jenkins.this.getRootDirFor(name); } }; /** * Hook for a test harness to intercept Jenkins.getInstance() * * Do not use in the production code as the signature may change. */ public interface JenkinsHolder { @CheckForNull Jenkins getInstance(); } static JenkinsHolder HOLDER = new JenkinsHolder() { public @CheckForNull Jenkins getInstance() { return theInstance; } }; /** * Gets the {@link Jenkins} singleton. * {@link #getInstance()} provides the unchecked versions of the method. * @return {@link Jenkins} instance * @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down * @since 1.590 */ public static @Nonnull Jenkins getActiveInstance() throws IllegalStateException { Jenkins instance = HOLDER.getInstance(); if (instance == null) { throw new IllegalStateException("Jenkins has not been started, or was already shut down"); } return instance; } /** * Gets the {@link Jenkins} singleton. * {@link #getActiveInstance()} provides the checked versions of the method. * @return The instance. Null if the {@link Jenkins} instance has not been started, * or was already shut down */ @CLIResolver @CheckForNull public static Jenkins getInstance() { return HOLDER.getInstance(); } /** * Secret key generated once and used for a long time, beyond * container start/stop. Persisted outside <tt>config.xml</tt> to avoid * accidental exposure. */ private transient final String secretKey; private transient final UpdateCenter updateCenter = new UpdateCenter(); /** * True if the user opted out from the statistics tracking. We'll never send anything if this is true. */ private Boolean noUsageStatistics; /** * HTTP proxy configuration. */ public transient volatile ProxyConfiguration proxy; /** * Bound to "/log". */ private transient final LogRecorderManager log = new LogRecorderManager(); protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException { this(root,context,null); } /** * @param pluginManager * If non-null, use existing plugin manager. create a new one. */ @edu.umd.cs.findbugs.annotations.SuppressWarnings({ "SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer }) protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException { long start = System.currentTimeMillis(); // As Jenkins is starting, grant this process full control ACL.impersonate(ACL.SYSTEM); try { this.root = root; this.servletContext = context; computeVersion(context); if(theInstance!=null) throw new IllegalStateException("second instance"); theInstance = this; if (!new File(root,"jobs").exists()) { // if this is a fresh install, use more modern default layout that's consistent with slaves workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}"; } // doing this early allows InitStrategy to set environment upfront final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader()); Trigger.timer = new java.util.Timer("Jenkins cron thread"); queue = new Queue(LoadBalancer.CONSISTENT_HASH); try { dependencyGraph = DependencyGraph.EMPTY; } catch (InternalError e) { if(e.getMessage().contains("window server")) { throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e); } throw e; } // get or create the secret TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key")); if(secretFile.exists()) { secretKey = secretFile.readTrim(); } else { SecureRandom sr = new SecureRandom(); byte[] random = new byte[32]; sr.nextBytes(random); secretKey = Util.toHexString(random); secretFile.write(secretKey); // this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49. // this indicates that there's no need to rewrite secrets on disk new FileBoolean(new File(root,"secret.key.not-so-secret")).on(); } try { proxy = ProxyConfiguration.load(); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to load proxy configuration", e); } if (pluginManager==null) pluginManager = new LocalPluginManager(this); this.pluginManager = pluginManager; // JSON binding needs to be able to see all the classes from all the plugins WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader); adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365)); // initialization consists of ... executeReactor( is, pluginManager.initTasks(is), // loading and preparing plugins loadTasks(), // load jobs InitMilestone.ordering() // forced ordering among key milestones ); if(KILL_AFTER_LOAD) System.exit(0); if(slaveAgentPort!=-1) { try { tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); } catch (BindException e) { new AdministrativeError(getClass().getName()+".tcpBind", "Failed to listen to incoming slave connection", "Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e); } } else tcpSlaveAgentListener = null; if (UDPBroadcastThread.PORT != -1) { try { udpBroadcastThread = new UDPBroadcastThread(this); udpBroadcastThread.start(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e); } } dnsMultiCast = new DNSMultiCast(this); Timer.get().scheduleAtFixedRate(new SafeTimerTask() { @Override protected void doRun() throws Exception { trimLabels(); } }, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS); updateComputerList(); {// master is online now Computer c = toComputer(); if(c!=null) for (ComputerListener cl : ComputerListener.all()) cl.onOnline(c, new LogTaskListener(LOGGER, INFO)); } for (ItemListener l : ItemListener.all()) { long itemListenerStart = System.currentTimeMillis(); try { l.onLoaded(); } catch (RuntimeException x) { LOGGER.log(Level.WARNING, null, x); } if (LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for item listener %s startup", System.currentTimeMillis()-itemListenerStart,l.getClass().getName())); } if (LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for complete Jenkins startup", System.currentTimeMillis()-start)); } finally { SecurityContextHolder.clearContext(); } } /** * Executes a reactor. * * @param is * If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins. */ private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException { Reactor reactor = new Reactor(builders) { /** * Sets the thread name to the task for better diagnostics. */ @Override protected void runTask(Task task) throws Exception { if (is!=null && is.skipInitTask(task)) return; ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread String taskName = task.getDisplayName(); Thread t = Thread.currentThread(); String name = t.getName(); if (taskName !=null) t.setName(taskName); try { long start = System.currentTimeMillis(); super.runTask(task); if(LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for %s by %s", System.currentTimeMillis()-start, taskName, name)); } finally { t.setName(name); SecurityContextHolder.clearContext(); } } }; new InitReactorRunner() { @Override protected void onInitMilestoneAttained(InitMilestone milestone) { initLevel = milestone; } }.run(reactor); } public TcpSlaveAgentListener getTcpSlaveAgentListener() { return tcpSlaveAgentListener; } /** * Makes {@link AdjunctManager} URL-bound. * The dummy parameter allows us to use different URLs for the same adjunct, * for proper cache handling. */ public AdjunctManager getAdjuncts(String dummy) { return adjuncts; } @Exported public int getSlaveAgentPort() { return slaveAgentPort; } /** * @param port * 0 to indicate random available TCP port. -1 to disable this service. */ public void setSlaveAgentPort(int port) throws IOException { this.slaveAgentPort = port; // relaunch the agent if(tcpSlaveAgentListener==null) { if(slaveAgentPort!=-1) tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); } else { if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) { tcpSlaveAgentListener.shutdown(); tcpSlaveAgentListener = null; if(slaveAgentPort!=-1) tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); } } } public void setNodeName(String name) { throw new UnsupportedOperationException(); // not allowed } public String getNodeDescription() { return Messages.Hudson_NodeDescription(); } @Exported public String getDescription() { return systemMessage; } public PluginManager getPluginManager() { return pluginManager; } public UpdateCenter getUpdateCenter() { return updateCenter; } public boolean isUsageStatisticsCollected() { return noUsageStatistics==null || !noUsageStatistics; } public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException { this.noUsageStatistics = noUsageStatistics; save(); } public View.People getPeople() { return new View.People(this); } /** * @since 1.484 */ public View.AsynchPeople getAsynchPeople() { return new View.AsynchPeople(this); } /** * Does this {@link View} has any associated user information recorded? * @deprecated Potentially very expensive call; do not use from Jelly views. */ @Deprecated public boolean hasPeople() { return View.People.isApplicable(items.values()); } public Api getApi() { return new Api(this); } /** * Returns a secret key that survives across container start/stop. * <p> * This value is useful for implementing some of the security features. * * @deprecated * Due to the past security advisory, this value should not be used any more to protect sensitive information. * See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets. */ @Deprecated public String getSecretKey() { return secretKey; } /** * Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128. * @since 1.308 * @deprecated * See {@link #getSecretKey()}. */ @Deprecated public SecretKey getSecretKeyAsAES128() { return Util.toAes128Key(secretKey); } /** * Returns the unique identifier of this Jenkins that has been historically used to identify * this Jenkins to the outside world. * * <p> * This form of identifier is weak in that it can be impersonated by others. See * https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID * that can be challenged and verified. * * @since 1.498 */ @SuppressWarnings("deprecation") public String getLegacyInstanceId() { return Util.getDigestOf(getSecretKey()); } /** * Gets the SCM descriptor by name. Primarily used for making them web-visible. */ public Descriptor<SCM> getScm(String shortClassName) { return findDescriptor(shortClassName,SCM.all()); } /** * Gets the repository browser descriptor by name. Primarily used for making them web-visible. */ public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) { return findDescriptor(shortClassName,RepositoryBrowser.all()); } /** * Gets the builder descriptor by name. Primarily used for making them web-visible. */ public Descriptor<Builder> getBuilder(String shortClassName) { return findDescriptor(shortClassName, Builder.all()); } /** * Gets the build wrapper descriptor by name. Primarily used for making them web-visible. */ public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) { return findDescriptor(shortClassName, BuildWrapper.all()); } /** * Gets the publisher descriptor by name. Primarily used for making them web-visible. */ public Descriptor<Publisher> getPublisher(String shortClassName) { return findDescriptor(shortClassName, Publisher.all()); } /** * Gets the trigger descriptor by name. Primarily used for making them web-visible. */ public TriggerDescriptor getTrigger(String shortClassName) { return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all()); } /** * Gets the retention strategy descriptor by name. Primarily used for making them web-visible. */ public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) { return findDescriptor(shortClassName, RetentionStrategy.all()); } /** * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible. */ public JobPropertyDescriptor getJobProperty(String shortClassName) { // combining these two lines triggers javac bug. See issue #610. Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all()); return (JobPropertyDescriptor) d; } /** * @deprecated * UI method. Not meant to be used programatically. */ @Deprecated public ComputerSet getComputer() { return new ComputerSet(); } /** * Exposes {@link Descriptor} by its name to URL. * * After doing all the {@code getXXX(shortClassName)} methods, I finally realized that * this just doesn't scale. * * @param id * Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility) * @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast) */ @SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix public Descriptor getDescriptor(String id) { // legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly. Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances()); for (Descriptor d : descriptors) { if (d.getId().equals(id)) { return d; } } Descriptor candidate = null; for (Descriptor d : descriptors) { String name = d.getId(); if (name.substring(name.lastIndexOf('.') + 1).equals(id)) { if (candidate == null) { candidate = d; } else { throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId()); } } } return candidate; } /** * Alias for {@link #getDescriptor(String)}. */ public Descriptor getDescriptorByName(String id) { return getDescriptor(id); } /** * Gets the {@link Descriptor} that corresponds to the given {@link Describable} type. * <p> * If you have an instance of {@code type} and call {@link Describable#getDescriptor()}, * you'll get the same instance that this method returns. */ public Descriptor getDescriptor(Class<? extends Describable> type) { for( Descriptor d : getExtensionList(Descriptor.class) ) if(d.clazz==type) return d; return null; } /** * Works just like {@link #getDescriptor(Class)} but don't take no for an answer. * * @throws AssertionError * If the descriptor is missing. * @since 1.326 */ public Descriptor getDescriptorOrDie(Class<? extends Describable> type) { Descriptor d = getDescriptor(type); if (d==null) throw new AssertionError(type+" is missing its descriptor"); return d; } /** * Gets the {@link Descriptor} instance in the current Jenkins by its type. */ public <T extends Descriptor> T getDescriptorByType(Class<T> type) { for( Descriptor d : getExtensionList(Descriptor.class) ) if(d.getClass()==type) return type.cast(d); return null; } /** * Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible. */ public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) { return findDescriptor(shortClassName,SecurityRealm.all()); } /** * Finds a descriptor that has the specified name. */ private <T extends Describable<T>> Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) { String name = '.'+shortClassName; for (Descriptor<T> d : descriptors) { if(d.clazz.getName().endsWith(name)) return d; } return null; } protected void updateComputerList() { updateComputerList(AUTOMATIC_SLAVE_LAUNCH); } /** @deprecated Use {@link SCMListener#all} instead. */ @Deprecated public CopyOnWriteList<SCMListener> getSCMListeners() { return scmListeners; } /** * Gets the plugin object from its short name. * * <p> * This allows URL <tt>hudson/plugin/ID</tt> to be served by the views * of the plugin class. */ public Plugin getPlugin(String shortName) { PluginWrapper p = pluginManager.getPlugin(shortName); if(p==null) return null; return p.getPlugin(); } /** * Gets the plugin object from its class. * * <p> * This allows easy storage of plugin information in the plugin singleton without * every plugin reimplementing the singleton pattern. * * @param clazz The plugin class (beware class-loader fun, this will probably only work * from within the jpi that defines the plugin class, it may or may not work in other cases) * * @return The plugin instance. */ @SuppressWarnings("unchecked") public <P extends Plugin> P getPlugin(Class<P> clazz) { PluginWrapper p = pluginManager.getPlugin(clazz); if(p==null) return null; return (P) p.getPlugin(); } /** * Gets the plugin objects from their super-class. * * @param clazz The plugin class (beware class-loader fun) * * @return The plugin instances. */ public <P extends Plugin> List<P> getPlugins(Class<P> clazz) { List<P> result = new ArrayList<P>(); for (PluginWrapper w: pluginManager.getPlugins(clazz)) { result.add((P)w.getPlugin()); } return Collections.unmodifiableList(result); } /** * Synonym for {@link #getDescription}. */ public String getSystemMessage() { return systemMessage; } /** * Gets the markup formatter used in the system. * * @return * never null. * @since 1.391 */ public @Nonnull MarkupFormatter getMarkupFormatter() { MarkupFormatter f = markupFormatter; return f != null ? f : new EscapedMarkupFormatter(); } /** * Sets the markup formatter used in the system globally. * * @since 1.391 */ public void setMarkupFormatter(MarkupFormatter f) { this.markupFormatter = f; } /** * Sets the system message. */ public void setSystemMessage(String message) throws IOException { this.systemMessage = message; save(); } public FederatedLoginService getFederatedLoginService(String name) { for (FederatedLoginService fls : FederatedLoginService.all()) { if (fls.getUrlName().equals(name)) return fls; } return null; } public List<FederatedLoginService> getFederatedLoginServices() { return FederatedLoginService.all(); } public Launcher createLauncher(TaskListener listener) { return new LocalLauncher(listener).decorateFor(this); } public String getFullName() { return ""; } public String getFullDisplayName() { return ""; } /** * Returns the transient {@link Action}s associated with the top page. * * <p> * Adding {@link Action} is primarily useful for plugins to contribute * an item to the navigation bar of the top page. See existing {@link Action} * implementation for it affects the GUI. * * <p> * To register an {@link Action}, implement {@link RootAction} extension point, or write code like * {@code Jenkins.getInstance().getActions().add(...)}. * * @return * Live list where the changes can be made. Can be empty but never null. * @since 1.172 */ public List<Action> getActions() { return actions; } /** * Gets just the immediate children of {@link Jenkins}. * * @see #getAllItems(Class) */ @Exported(name="jobs") public List<TopLevelItem> getItems() { if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured || authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) { return new ArrayList(items.values()); } List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>(); for (TopLevelItem item : items.values()) { if (item.hasPermission(Item.READ)) viewableItems.add(item); } return viewableItems; } /** * Returns the read-only view of all the {@link TopLevelItem}s keyed by their names. * <p> * This method is efficient, as it doesn't involve any copying. * * @since 1.296 */ public Map<String,TopLevelItem> getItemMap() { return Collections.unmodifiableMap(items); } /** * Gets just the immediate children of {@link Jenkins} but of the given type. */ public <T> List<T> getItems(Class<T> type) { List<T> r = new ArrayList<T>(); for (TopLevelItem i : getItems()) if (type.isInstance(i)) r.add(type.cast(i)); return r; } /** * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree * and filter them by the given type. */ public <T extends Item> List<T> getAllItems(Class<T> type) { return Items.getAllItems(this, type); } /** * Gets all the items recursively. * * @since 1.402 */ public List<Item> getAllItems() { return getAllItems(Item.class); } /** * Gets a list of simple top-level projects. * @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders. * You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject}, * perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s. * (That will also consider the caller's permissions.) * If you really want to get just {@link Project}s at top level, ignoring permissions, * you can filter the values from {@link #getItemMap} using {@link Util#createSubList}. */ @Deprecated public List<Project> getProjects() { return Util.createSubList(items.values(),Project.class); } /** * Gets the names of all the {@link Job}s. */ public Collection<String> getJobNames() { List<String> names = new ArrayList<String>(); for (Job j : getAllItems(Job.class)) names.add(j.getFullName()); return names; } public List<Action> getViewActions() { return getActions(); } /** * Gets the names of all the {@link TopLevelItem}s. */ public Collection<String> getTopLevelItemNames() { List<String> names = new ArrayList<String>(); for (TopLevelItem j : items.values()) names.add(j.getName()); return names; } public View getView(String name) { return viewGroupMixIn.getView(name); } /** * Gets the read-only list of all {@link View}s. */ @Exported public Collection<View> getViews() { return viewGroupMixIn.getViews(); } @Override public void addView(View v) throws IOException { viewGroupMixIn.addView(v); } public boolean canDelete(View view) { return viewGroupMixIn.canDelete(view); } public synchronized void deleteView(View view) throws IOException { viewGroupMixIn.deleteView(view); } public void onViewRenamed(View view, String oldName, String newName) { viewGroupMixIn.onViewRenamed(view,oldName,newName); } /** * Returns the primary {@link View} that renders the top-page of Jenkins. */ @Exported public View getPrimaryView() { return viewGroupMixIn.getPrimaryView(); } public void setPrimaryView(View v) { this.primaryView = v.getViewName(); } public ViewsTabBar getViewsTabBar() { return viewsTabBar; } public void setViewsTabBar(ViewsTabBar viewsTabBar) { this.viewsTabBar = viewsTabBar; } public Jenkins getItemGroup() { return this; } public MyViewsTabBar getMyViewsTabBar() { return myViewsTabBar; } public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) { this.myViewsTabBar = myViewsTabBar; } /** * Returns true if the current running Jenkins is upgraded from a version earlier than the specified version. * * <p> * This method continues to return true until the system configuration is saved, at which point * {@link #version} will be overwritten and Jenkins forgets the upgrade history. * * <p> * To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version * equal or younger than N. So say if you implement a feature in 1.301 and you want to check * if the installation upgraded from pre-1.301, pass in "1.300.*" * * @since 1.301 */ public boolean isUpgradedFromBefore(VersionNumber v) { try { return new VersionNumber(version).isOlderThan(v); } catch (IllegalArgumentException e) { // fail to parse this version number return false; } } /** * Gets the read-only list of all {@link Computer}s. */ public Computer[] getComputers() { Computer[] r = computers.values().toArray(new Computer[computers.size()]); Arrays.sort(r,new Comparator<Computer>() { @Override public int compare(Computer lhs, Computer rhs) { if(lhs.getNode()==Jenkins.this) return -1; if(rhs.getNode()==Jenkins.this) return 1; return lhs.getName().compareTo(rhs.getName()); } }); return r; } @CLIResolver public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) { if(name.equals("(master)")) name = ""; for (Computer c : computers.values()) { if(c.getName().equals(name)) return c; } return null; } /** * Gets the label that exists on this system by the name. * * @return null if name is null. * @see Label#parseExpression(String) (String) */ public Label getLabel(String expr) { if(expr==null) return null; expr = hudson.util.QuotedStringTokenizer.unquote(expr); while(true) { Label l = labels.get(expr); if(l!=null) return l; // non-existent try { labels.putIfAbsent(expr,Label.parseExpression(expr)); } catch (ANTLRException e) { // laxly accept it as a single label atom for backward compatibility return getLabelAtom(expr); } } } /** * Returns the label atom of the given name. * @return non-null iff name is non-null */ public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) { if (name==null) return null; while(true) { Label l = labels.get(name); if(l!=null) return (LabelAtom)l; // non-existent LabelAtom la = new LabelAtom(name); if (labels.putIfAbsent(name, la)==null) la.load(); } } /** * Gets all the active labels in the current system. */ public Set<Label> getLabels() { Set<Label> r = new TreeSet<Label>(); for (Label l : labels.values()) { if(!l.isEmpty()) r.add(l); } return r; } public Set<LabelAtom> getLabelAtoms() { Set<LabelAtom> r = new TreeSet<LabelAtom>(); for (Label l : labels.values()) { if(!l.isEmpty() && l instanceof LabelAtom) r.add((LabelAtom)l); } return r; } public Queue getQueue() { return queue; } @Override public String getDisplayName() { return Messages.Hudson_DisplayName(); } public synchronized List<JDK> getJDKs() { if(jdks==null) jdks = new ArrayList<JDK>(); return jdks; } /** * Replaces all JDK installations with those from the given collection. * * Use {@link hudson.model.JDK.DescriptorImpl#setInstallations(JDK...)} to * set JDK installations from external code. */ @Restricted(NoExternalUse.class) public synchronized void setJDKs(Collection<? extends JDK> jdks) { this.jdks = new ArrayList<JDK>(jdks); } /** * Gets the JDK installation of the given name, or returns null. */ public JDK getJDK(String name) { if(name==null) { // if only one JDK is configured, "default JDK" should mean that JDK. List<JDK> jdks = getJDKs(); if(jdks.size()==1) return jdks.get(0); return null; } for (JDK j : getJDKs()) { if(j.getName().equals(name)) return j; } return null; } /** * Gets the slave node of the give name, hooked under this Jenkins. */ public @CheckForNull Node getNode(String name) { return nodes.getNode(name); } /** * Gets a {@link Cloud} by {@link Cloud#name its name}, or null. */ public Cloud getCloud(String name) { return clouds.getByName(name); } protected Map<Node,Computer> getComputerMap() { return computers; } /** * Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which * represents the master. */ public List<Node> getNodes() { return nodes.getNodes(); } /** * Get the {@link Nodes} object that handles maintaining individual {@link Node}s. * @return The Nodes object. */ @Restricted(NoExternalUse.class) public Nodes getNodesObject() { // TODO replace this with something better when we properly expose Nodes. return nodes; } /** * Adds one more {@link Node} to Jenkins. */ public void addNode(Node n) throws IOException { nodes.addNode(n); } /** * Removes a {@link Node} from Jenkins. */ public void removeNode(@Nonnull Node n) throws IOException { nodes.removeNode(n); } public void setNodes(final List<? extends Node> n) throws IOException { nodes.setNodes(n); } public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() { return nodeProperties; } public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() { return globalNodeProperties; } /** * Resets all labels and remove invalid ones. * * This should be called when the assumptions behind label cache computation changes, * but we also call this periodically to self-heal any data out-of-sync issue. */ /*package*/ void trimLabels() { for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) { Label l = itr.next(); resetLabel(l); if(l.isEmpty()) itr.remove(); } } /** * Binds {@link AdministrativeMonitor}s to URL. */ public AdministrativeMonitor getAdministrativeMonitor(String id) { for (AdministrativeMonitor m : administrativeMonitors) if(m.id.equals(id)) return m; return null; } public NodeDescriptor getDescriptor() { return DescriptorImpl.INSTANCE; } public static final class DescriptorImpl extends NodeDescriptor { @Extension public static final DescriptorImpl INSTANCE = new DescriptorImpl(); public String getDisplayName() { return ""; } @Override public boolean isInstantiable() { return false; } public FormValidation doCheckNumExecutors(@QueryParameter String value) { return FormValidation.validateNonNegativeInteger(value); } public FormValidation doCheckRawBuildsDir(@QueryParameter String value) { // do essentially what expandVariablesForDirectory does, without an Item String replacedValue = expandVariablesForDirectory(value, "doCheckRawBuildsDir-Marker:foo", Jenkins.getInstance().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo"); File replacedFile = new File(replacedValue); if (!replacedFile.isAbsolute()) { return FormValidation.error(value + " does not resolve to an absolute path"); } if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) { return FormValidation.error(value + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects"); } if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) { // make sure platform can handle colon try { File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar"); tmp.delete(); } catch (IOException e) { return FormValidation.error(value + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead"); } } File d = new File(replacedValue); if (!d.isDirectory()) { // if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to d = d.getParentFile(); while (!d.exists()) { d = d.getParentFile(); } if (!d.canWrite()) { return FormValidation.error(value + " does not exist and probably cannot be created"); } } return FormValidation.ok(); } // to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx public Object getDynamic(String token) { return Jenkins.getInstance().getDescriptor(token); } } /** * Gets the system default quiet period. */ public int getQuietPeriod() { return quietPeriod!=null ? quietPeriod : 5; } /** * Sets the global quiet period. * * @param quietPeriod * null to the default value. */ public void setQuietPeriod(Integer quietPeriod) throws IOException { this.quietPeriod = quietPeriod; save(); } /** * Gets the global SCM check out retry count. */ public int getScmCheckoutRetryCount() { return scmCheckoutRetryCount; } public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException { this.scmCheckoutRetryCount = scmCheckoutRetryCount; save(); } @Override public String getSearchUrl() { return ""; } @Override public SearchIndexBuilder makeSearchIndex() { return super.makeSearchIndex() .add("configure", "config","configure") .add("manage") .add("log") .add(new CollectionSearchIndex<TopLevelItem>() { protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); } protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); } }) .add(getPrimaryView().makeSearchIndex()) .add(new CollectionSearchIndex() {// for computers protected Computer get(String key) { return getComputer(key); } protected Collection<Computer> all() { return computers.values(); } }) .add(new CollectionSearchIndex() {// for users protected User get(String key) { return User.get(key,false); } protected Collection<User> all() { return User.getAll(); } }) .add(new CollectionSearchIndex() {// for views protected View get(String key) { return getView(key); } protected Collection<View> all() { return viewGroupMixIn.getViews(); } }); } public String getUrlChildPrefix() { return "job"; } /** * Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}. * * <p> * This method first tries to use the manually configured value, then * fall back to {@link #getRootUrlFromRequest}. * It is done in this order so that it can work correctly even in the face * of a reverse proxy. * * @return null if this parameter is not configured by the user and the calling thread is not in an HTTP request; otherwise the returned URL will always have the trailing {@code /} * @since 1.66 * @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a> */ public @Nullable String getRootUrl() { String url = JenkinsLocationConfiguration.get().getUrl(); if(url!=null) { return Util.ensureEndsWith(url,"/"); } StaplerRequest req = Stapler.getCurrentRequest(); if(req!=null) return getRootUrlFromRequest(); return null; } /** * Is Jenkins running in HTTPS? * * Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated * in the reverse proxy. */ public boolean isRootUrlSecure() { String url = getRootUrl(); return url!=null && url.startsWith("https"); } /** * Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}. * * <p> * Unlike {@link #getRootUrl()}, which uses the manually configured value, * this one uses the current request to reconstruct the URL. The benefit is * that this is immune to the configuration mistake (users often fail to set the root URL * correctly, especially when a migration is involved), but the downside * is that unless you are processing a request, this method doesn't work. * * <p>Please note that this will not work in all cases if Jenkins is running behind a * reverse proxy which has not been fully configured. * Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set. * <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a> * shows some examples of configuration. * @since 1.263 */ public @Nonnull String getRootUrlFromRequest() { StaplerRequest req = Stapler.getCurrentRequest(); if (req == null) { throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread"); } StringBuilder buf = new StringBuilder(); String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme()); buf.append(scheme).append("://"); String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName()); int index = host.indexOf(':'); int port = req.getServerPort(); if (index == -1) { // Almost everyone else except Nginx put the host and port in separate headers buf.append(host); } else { // Nginx uses the same spec as for the Host header, i.e. hostanme:port buf.append(host.substring(0, index)); if (index + 1 < host.length()) { try { port = Integer.parseInt(host.substring(index + 1)); } catch (NumberFormatException e) { // ignore } } // but if a user has configured Nginx with an X-Forwarded-Port, that will win out. } String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null); if (forwardedPort != null) { try { port = Integer.parseInt(forwardedPort); } catch (NumberFormatException e) { // ignore } } if (port != ("https".equals(scheme) ? 443 : 80)) { buf.append(':').append(port); } buf.append(req.getContextPath()).append('/'); return buf.toString(); } /** * Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating * header is the first header. If the originating header contains a comma separated list, the originating entry * is the first one. * @param req the request * @param header the header name * @param defaultValue the value to return if the header is absent. * @return the originating entry of the header or the default value if the header was not present. */ private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) { String value = req.getHeader(header); if (value != null) { int index = value.indexOf(','); return index == -1 ? value.trim() : value.substring(0,index).trim(); } return defaultValue; } public File getRootDir() { return root; } public FilePath getWorkspaceFor(TopLevelItem item) { for (WorkspaceLocator l : WorkspaceLocator.all()) { FilePath workspace = l.locate(item, this); if (workspace != null) { return workspace; } } return new FilePath(expandVariablesForDirectory(workspaceDir, item)); } public File getBuildDirFor(Job job) { return expandVariablesForDirectory(buildsDir, job); } private File expandVariablesForDirectory(String base, Item item) { return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath())); } @Restricted(NoExternalUse.class) static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) { return Util.replaceMacro(base, ImmutableMap.of( "JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath(), "ITEM_ROOTDIR", itemRootDir, "ITEM_FULLNAME", itemFullName, // legacy, deprecated "ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251 } public String getRawWorkspaceDir() { return workspaceDir; } public String getRawBuildsDir() { return buildsDir; } @Restricted(NoExternalUse.class) public void setRawBuildsDir(String buildsDir) { this.buildsDir = buildsDir; } @Override public @Nonnull FilePath getRootPath() { return new FilePath(getRootDir()); } @Override public FilePath createPath(String absolutePath) { return new FilePath((VirtualChannel)null,absolutePath); } public ClockDifference getClockDifference() { return ClockDifference.ZERO; } @Override public Callable<ClockDifference, IOException> getClockDifferenceCallable() { return new MasterToSlaveCallable<ClockDifference, IOException>() { public ClockDifference call() throws IOException { return new ClockDifference(0); } }; } /** * For binding {@link LogRecorderManager} to "/log". * Everything below here is admin-only, so do the check here. */ public LogRecorderManager getLog() { checkPermission(ADMINISTER); return log; } /** * A convenience method to check if there's some security * restrictions in place. */ @Exported public boolean isUseSecurity() { return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED; } public boolean isUseProjectNamingStrategy(){ return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; } /** * If true, all the POST requests to Jenkins would have to have crumb in it to protect * Jenkins from CSRF vulnerabilities. */ @Exported public boolean isUseCrumbs() { return crumbIssuer!=null; } /** * Returns the constant that captures the three basic security modes in Jenkins. */ public SecurityMode getSecurity() { // fix the variable so that this code works under concurrent modification to securityRealm. SecurityRealm realm = securityRealm; if(realm==SecurityRealm.NO_AUTHENTICATION) return SecurityMode.UNSECURED; if(realm instanceof LegacySecurityRealm) return SecurityMode.LEGACY; return SecurityMode.SECURED; } /** * @return * never null. */ public SecurityRealm getSecurityRealm() { return securityRealm; } public void setSecurityRealm(SecurityRealm securityRealm) { if(securityRealm==null) securityRealm= SecurityRealm.NO_AUTHENTICATION; this.useSecurity = true; IdStrategy oldUserIdStrategy = this.securityRealm == null ? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load : this.securityRealm.getUserIdStrategy(); this.securityRealm = securityRealm; // reset the filters and proxies for the new SecurityRealm try { HudsonFilter filter = HudsonFilter.get(servletContext); if (filter == null) { // Fix for #3069: This filter is not necessarily initialized before the servlets. // when HudsonFilter does come back, it'll initialize itself. LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now"); } else { LOGGER.fine("HudsonFilter has been previously initialized: Setting security up"); filter.reset(securityRealm); LOGGER.fine("Security is now fully set up"); } if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) { User.rekey(); } } catch (ServletException e) { // for binary compatibility, this method cannot throw a checked exception throw new AcegiSecurityException("Failed to configure filter",e) {}; } } public void setAuthorizationStrategy(AuthorizationStrategy a) { if (a == null) a = AuthorizationStrategy.UNSECURED; useSecurity = true; authorizationStrategy = a; } public boolean isDisableRememberMe() { return disableRememberMe; } public void setDisableRememberMe(boolean disableRememberMe) { this.disableRememberMe = disableRememberMe; } public void disableSecurity() { useSecurity = null; setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); authorizationStrategy = AuthorizationStrategy.UNSECURED; } public void setProjectNamingStrategy(ProjectNamingStrategy ns) { if(ns == null){ ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; } projectNamingStrategy = ns; } public Lifecycle getLifecycle() { return Lifecycle.get(); } /** * Gets the dependency injection container that hosts all the extension implementations and other * components in Jenkins. * * @since 1.433 */ public Injector getInjector() { return lookup(Injector.class); } /** * Returns {@link ExtensionList} that retains the discovered instances for the given extension type. * * @param extensionType * The base type that represents the extension point. Normally {@link ExtensionPoint} subtype * but that's not a hard requirement. * @return * Can be an empty list but never null. * @see ExtensionList#lookup */ @SuppressWarnings({"unchecked"}) public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) { return extensionLists.get(extensionType); } /** * Used to bind {@link ExtensionList}s to URLs. * * @since 1.349 */ public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException { return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType)); } /** * Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given * kind of {@link Describable}. * * @return * Can be an empty list but never null. */ @SuppressWarnings({"unchecked"}) public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) { return descriptorLists.get(type); } /** * Refresh {@link ExtensionList}s by adding all the newly discovered extensions. * * Exposed only for {@link PluginManager#dynamicLoad(File)}. */ public void refreshExtensions() throws ExtensionRefreshException { ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class); for (ExtensionFinder ef : finders) { if (!ef.isRefreshable()) throw new ExtensionRefreshException(ef+" doesn't support refresh"); } List<ExtensionComponentSet> fragments = Lists.newArrayList(); for (ExtensionFinder ef : finders) { fragments.add(ef.refresh()); } ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered(); // if we find a new ExtensionFinder, we need it to list up all the extension points as well List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class)); while (!newFinders.isEmpty()) { ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance(); ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered(); newFinders.addAll(ecs.find(ExtensionFinder.class)); delta = ExtensionComponentSet.union(delta, ecs); } for (ExtensionList el : extensionLists.values()) { el.refresh(delta); } for (ExtensionList el : descriptorLists.values()) { el.refresh(delta); } // TODO: we need some generalization here so that extension points can be notified when a refresh happens? for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) { Action a = ea.getInstance(); if (!actions.contains(a)) actions.add(a); } } /** * Returns the root {@link ACL}. * * @see AuthorizationStrategy#getRootACL() */ @Override public ACL getACL() { return authorizationStrategy.getRootACL(); } /** * @return * never null. */ public AuthorizationStrategy getAuthorizationStrategy() { return authorizationStrategy; } /** * The strategy used to check the project names. * @return never <code>null</code> */ public ProjectNamingStrategy getProjectNamingStrategy() { return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy; } /** * Returns true if Jenkins is quieting down. * <p> * No further jobs will be executed unless it * can be finished while other current pending builds * are still in progress. */ @Exported public boolean isQuietingDown() { return isQuietingDown; } /** * Returns true if the container initiated the termination of the web application. */ public boolean isTerminating() { return terminating; } /** * Gets the initialization milestone that we've already reached. * * @return * {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method * never returns null. */ public InitMilestone getInitLevel() { return initLevel; } public void setNumExecutors(int n) throws IOException { if (this.numExecutors != n) { this.numExecutors = n; updateComputerList(); save(); } } /** * {@inheritDoc}. * * Note that the look up is case-insensitive. */ @Override public TopLevelItem getItem(String name) throws AccessDeniedException { if (name==null) return null; TopLevelItem item = items.get(name); if (item==null) return null; if (!item.hasPermission(Item.READ)) { if (item.hasPermission(Item.DISCOVER)) { throw new AccessDeniedException("Please login to access job " + name); } return null; } return item; } /** * Gets the item by its path name from the given context * * <h2>Path Names</h2> * <p> * If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute. * Otherwise, the name should be something like "foo/bar" and it's interpreted like * relative path name in the file system is, against the given context. * <p>For compatibility, as a fallback when nothing else matches, a simple path * like {@code foo/bar} can also be treated with {@link #getItemByFullName}. * @param context * null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation. * @since 1.406 */ public Item getItem(String pathName, ItemGroup context) { if (context==null) context = this; if (pathName==null) return null; if (pathName.startsWith("/")) // absolute return getItemByFullName(pathName); Object/*Item|ItemGroup*/ ctx = context; StringTokenizer tokens = new StringTokenizer(pathName,"/"); while (tokens.hasMoreTokens()) { String s = tokens.nextToken(); if (s.equals("..")) { if (ctx instanceof Item) { ctx = ((Item)ctx).getParent(); continue; } ctx=null; // can't go up further break; } if (s.equals(".")) { continue; } if (ctx instanceof ItemGroup) { ItemGroup g = (ItemGroup) ctx; Item i = g.getItem(s); if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER ctx=null; // can't go up further break; } ctx=i; } else { return null; } } if (ctx instanceof Item) return (Item)ctx; // fall back to the classic interpretation return getItemByFullName(pathName); } public final Item getItem(String pathName, Item context) { return getItem(pathName,context!=null?context.getParent():null); } public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) { Item r = getItem(pathName, context); if (type.isInstance(r)) return type.cast(r); return null; } public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) { return getItem(pathName,context!=null?context.getParent():null,type); } public File getRootDirFor(TopLevelItem child) { return getRootDirFor(child.getName()); } private File getRootDirFor(String name) { return new File(new File(getRootDir(),"jobs"), name); } /** * Gets the {@link Item} object by its full name. * Full names are like path names, where each name of {@link Item} is * combined by '/'. * * @return * null if either such {@link Item} doesn't exist under the given full name, * or it exists but it's no an instance of the given type. * @throws AccessDeniedException as per {@link ItemGroup#getItem} */ public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) throws AccessDeniedException { StringTokenizer tokens = new StringTokenizer(fullName,"/"); ItemGroup parent = this; if(!tokens.hasMoreTokens()) return null; // for example, empty full name. while(true) { Item item = parent.getItem(tokens.nextToken()); if(!tokens.hasMoreTokens()) { if(type.isInstance(item)) return type.cast(item); else return null; } if(!(item instanceof ItemGroup)) return null; // this item can't have any children if (!item.hasPermission(Item.READ)) return null; // TODO consider DISCOVER parent = (ItemGroup) item; } } public @CheckForNull Item getItemByFullName(String fullName) { return getItemByFullName(fullName,Item.class); } /** * Gets the user of the given name. * * @return the user of the given name (which may or may not be an id), if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null * @see User#get(String,boolean), {@link User#getById(String, boolean)} */ public @CheckForNull User getUser(String name) { return User.get(name,hasPermission(ADMINISTER)); } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException { return createProject(type, name, true); } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException { return itemGroupMixIn.createProject(type,name,notify); } /** * Overwrites the existing item by new one. * * <p> * This is a short cut for deleting an existing job and adding a new one. */ public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException { String name = item.getName(); TopLevelItem old = items.get(name); if (old ==item) return; // noop checkPermission(Item.CREATE); if (old!=null) old.delete(); items.put(name,item); ItemListener.fireOnCreated(item); } /** * Creates a new job. * * <p> * This version infers the descriptor from the type of the top-level item. * * @throws IllegalArgumentException * if the project of the given name already exists. */ public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException { return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name)); } /** * Called by {@link Job#renameTo(String)} to update relevant data structure. * assumed to be synchronized on Jenkins by the caller. */ public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException { items.remove(oldName); items.put(newName,job); // For compatibility with old views: for (View v : views) v.onJobRenamed(job, oldName, newName); } /** * Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)} */ public void onDeleted(TopLevelItem item) throws IOException { ItemListener.fireOnDeleted(item); items.remove(item.getName()); // For compatibility with old views: for (View v : views) v.onJobRenamed(item, item.getName(), null); } @Override public boolean canAdd(TopLevelItem item) { return true; } @Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException { if (items.containsKey(name)) { throw new IllegalArgumentException("already an item '" + name + "'"); } items.put(name, item); return item; } @Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException { items.remove(item.getName()); } public FingerprintMap getFingerprintMap() { return fingerprintMap; } // if no finger print matches, display "not found page". public Object getFingerprint( String md5sum ) throws IOException { Fingerprint r = fingerprintMap.get(md5sum); if(r==null) return new NoFingerprintMatch(md5sum); else return r; } /** * Gets a {@link Fingerprint} object if it exists. * Otherwise null. */ public Fingerprint _getFingerprint( String md5sum ) throws IOException { return fingerprintMap.get(md5sum); } /** * The file we save our configuration. */ private XmlFile getConfigFile() { return new XmlFile(XSTREAM, new File(root,"config.xml")); } public int getNumExecutors() { return numExecutors; } public Mode getMode() { return mode; } public void setMode(Mode m) throws IOException { this.mode = m; save(); } public String getLabelString() { return fixNull(label).trim(); } @Override public void setLabelString(String label) throws IOException { this.label = label; save(); } @Override public LabelAtom getSelfLabel() { return getLabelAtom("master"); } public Computer createComputer() { return new Hudson.MasterComputer(); } private synchronized TaskBuilder loadTasks() throws IOException { File projectsDir = new File(root,"jobs"); if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) { if(projectsDir.exists()) throw new IOException(projectsDir+" is not a directory"); throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually."); } File[] subdirs = projectsDir.listFiles(); final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>()); TaskGraphBuilder g = new TaskGraphBuilder(); Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() { public void run(Reactor session) throws Exception { XmlFile cfg = getConfigFile(); if (cfg.exists()) { // reset some data that may not exist in the disk file // so that we can take a proper compensation action later. primaryView = null; views.clear(); // load from disk cfg.unmarshal(Jenkins.this); } // if we are loading old data that doesn't have this field if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) { nodes.setNodes(slaves); slaves = null; } else { nodes.load(); } clouds.setOwner(Jenkins.this); } }); for (final File subdir : subdirs) { g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() { public void run(Reactor session) throws Exception { if(!Items.getConfigFile(subdir).exists()) { //Does not have job config file, so it is not a jenkins job hence skip it return; } TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir); items.put(item.getName(), item); loadedNames.add(item.getName()); } }); } g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() { public void run(Reactor reactor) throws Exception { // anything we didn't load from disk, throw them away. // doing this after loading from disk allows newly loaded items // to inspect what already existed in memory (in case of reloading) // retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one // hopefully there shouldn't be too many of them. for (String name : items.keySet()) { if (!loadedNames.contains(name)) items.remove(name); } } }); g.requires(JOB_LOADED).add("Finalizing set up",new Executable() { public void run(Reactor session) throws Exception { rebuildDependencyGraph(); {// recompute label objects - populates the labels mapping. for (Node slave : nodes.getNodes()) // Note that not all labels are visible until the slaves have connected. slave.getAssignedLabels(); getAssignedLabels(); } // initialize views by inserting the default view if necessary // this is both for clean Jenkins and for backward compatibility. if(views.size()==0 || primaryView==null) { View v = new AllView(Messages.Hudson_ViewName()); setViewOwner(v); views.add(0,v); primaryView = v.getViewName(); } if (useSecurity!=null && !useSecurity) { // forced reset to the unsecure mode. // this works as an escape hatch for people who locked themselves out. authorizationStrategy = AuthorizationStrategy.UNSECURED; setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); } else { // read in old data that doesn't have the security field set if(authorizationStrategy==null) { if(useSecurity==null) authorizationStrategy = AuthorizationStrategy.UNSECURED; else authorizationStrategy = new LegacyAuthorizationStrategy(); } if(securityRealm==null) { if(useSecurity==null) setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); else setSecurityRealm(new LegacySecurityRealm()); } else { // force the set to proxy setSecurityRealm(securityRealm); } } // Initialize the filter with the crumb issuer setCrumbIssuer(crumbIssuer); // auto register root actions for (Action a : getExtensionList(RootAction.class)) if (!actions.contains(a)) actions.add(a); } }); return g; } /** * Save the settings to a file. */ public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } /** * Called to shut down the system. */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") public void cleanUp() { for (ItemListener l : ItemListener.all()) l.onBeforeShutdown(); try { final TerminatorFinder tf = new TerminatorFinder( pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader()); new Reactor(tf).execute(new Executor() { @Override public void execute(Runnable command) { command.run(); } }); } catch (InterruptedException e) { LOGGER.log(SEVERE, "Failed to execute termination",e); e.printStackTrace(); } catch (ReactorException e) { LOGGER.log(SEVERE, "Failed to execute termination",e); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to execute termination",e); } final Set<Future<?>> pending = new HashSet<Future<?>>(); terminating = true; // JENKINS-28840 we know we will be interrupting all the Computers so get the Queue lock once for all Queue.withLock(new Runnable() { @Override public void run() { for( Computer c : computers.values() ) { c.interrupt(); killComputer(c); pending.add(c.disconnect(null)); } } }); if(udpBroadcastThread!=null) udpBroadcastThread.shutdown(); if(dnsMultiCast!=null) dnsMultiCast.close(); interruptReloadThread(); java.util.Timer timer = Trigger.timer; if (timer != null) { timer.cancel(); } // TODO: how to wait for the completion of the last job? Trigger.timer = null; Timer.shutdown(); if(tcpSlaveAgentListener!=null) tcpSlaveAgentListener.shutdown(); if(pluginManager!=null) // be defensive. there could be some ugly timing related issues pluginManager.stop(); if(getRootDir().exists()) // if we are aborting because we failed to create JENKINS_HOME, // don't try to save. Issue #536 getQueue().save(); threadPoolForLoad.shutdown(); for (Future<?> f : pending) try { f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; // someone wants us to die now. quick! } catch (ExecutionException e) { LOGGER.log(Level.WARNING, "Failed to shut down properly",e); } catch (TimeoutException e) { LOGGER.log(Level.WARNING, "Failed to shut down properly",e); } LogFactory.releaseAll(); theInstance = null; } public Object getDynamic(String token) { for (Action a : getActions()) { String url = a.getUrlName(); if (url==null) continue; if (url.equals(token) || url.equals('/' + token)) return a; } for (Action a : getManagementLinks()) if(a.getUrlName().equals(token)) return a; return null; } // // // actions // // /** * Accepts submission from the configuration page. */ public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { BulkChange bc = new BulkChange(this); try { checkPermission(ADMINISTER); JSONObject json = req.getSubmittedForm(); workspaceDir = json.getString("rawWorkspaceDir"); buildsDir = json.getString("rawBuildsDir"); systemMessage = Util.nullify(req.getParameter("system_message")); setJDKs(req.bindJSONToList(JDK.class, json.get("jdks"))); boolean result = true; for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified()) result &= configureDescriptor(req,json,d); version = VERSION; save(); updateComputerList(); if(result) FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null); else FormApply.success("configure").generateResponse(req, rsp, null); // back to config } finally { bc.commit(); } } /** * Gets the {@link CrumbIssuer} currently in use. * * @return null if none is in use. */ public CrumbIssuer getCrumbIssuer() { return crumbIssuer; } public void setCrumbIssuer(CrumbIssuer issuer) { crumbIssuer = issuer; } public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { rsp.sendRedirect("foo"); } private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException { // collapse the structure to remain backward compatible with the JSON structure before 1. String name = d.getJsonSafeClassName(); JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object. json.putAll(js); return d.configure(req, js); } /** * Accepts submission from the node configuration page. */ @RequirePOST public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(ADMINISTER); BulkChange bc = new BulkChange(this); try { JSONObject json = req.getSubmittedForm(); MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class); if (mbc!=null) mbc.configure(req,json); getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all()); } finally { bc.commit(); } updateComputerList(); rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page } /** * Accepts the new description. */ @RequirePOST public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { getPrimaryView().doSubmitDescription(req, rsp); } @RequirePOST // TODO does not seem to work on _either_ overload! public synchronized HttpRedirect doQuietDown() throws IOException { try { return doQuietDown(false,0); } catch (InterruptedException e) { throw new AssertionError(); // impossible } } @CLIMethod(name="quiet-down") @RequirePOST public HttpRedirect doQuietDown( @Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block, @Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException { synchronized (this) { checkPermission(ADMINISTER); isQuietingDown = true; } if (block) { long waitUntil = timeout; if (timeout > 0) waitUntil += System.currentTimeMillis(); while (isQuietingDown && (timeout <= 0 || System.currentTimeMillis() < waitUntil) && !RestartListener.isAllReady()) { Thread.sleep(1000); } } return new HttpRedirect("."); } @CLIMethod(name="cancel-quiet-down") @RequirePOST // TODO the cancel link needs to be updated accordingly public synchronized HttpRedirect doCancelQuietDown() { checkPermission(ADMINISTER); isQuietingDown = false; getQueue().scheduleMaintenance(); return new HttpRedirect("."); } public HttpResponse doToggleCollapse() throws ServletException, IOException { final StaplerRequest request = Stapler.getCurrentRequest(); final String paneId = request.getParameter("paneId"); PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId); return HttpResponses.forwardToPreviousPage(); } /** * Backward compatibility. Redirect to the thread dump. */ public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException { rsp.sendRedirect2("threadDump"); } /** * Obtains the thread dump of all slaves (including the master.) * * <p> * Since this is for diagnostics, it has a built-in precautionary measure against hang slaves. */ public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException { checkPermission(ADMINISTER); // issue the requests all at once Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>(); for (Computer c : getComputers()) { try { future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel())); } catch(Exception e) { LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage()); } } if (toComputer() == null) { future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel)); } // if the result isn't available in 5 sec, ignore that. // this is a precaution against hang nodes long endTime = System.currentTimeMillis() + 5000; Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>(); for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) { try { r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS)); } catch (Exception x) { StringWriter sw = new StringWriter(); x.printStackTrace(new PrintWriter(sw,true)); r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString())); } } return Collections.unmodifiableSortedMap(new TreeMap<String, Map<String, String>>(r)); } @RequirePOST public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { return itemGroupMixIn.createTopLevelItem(req, rsp); } /** * @since 1.319 */ public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { return itemGroupMixIn.createProjectFromXML(name, xml); } @SuppressWarnings({"unchecked"}) public <T extends TopLevelItem> T copy(T src, String name) throws IOException { return itemGroupMixIn.copy(src, name); } // a little more convenient overloading that assumes the caller gives us the right type // (or else it will fail with ClassCastException) public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException { return (T)copy((TopLevelItem)src,name); } @RequirePOST public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(View.CREATE); addView(View.create(req,rsp, this)); } /** * Check if the given name is suitable as a name * for job, view, etc. * * @throws Failure * if the given name is not good */ public static void checkGoodName(String name) throws Failure { if(name==null || name.length()==0) throw new Failure(Messages.Hudson_NoName()); if(".".equals(name.trim())) throw new Failure(Messages.Jenkins_NotAllowedName(".")); if("..".equals(name.trim())) throw new Failure(Messages.Jenkins_NotAllowedName("..")); for( int i=0; i<name.length(); i++ ) { char ch = name.charAt(i); if(Character.isISOControl(ch)) { throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name))); } if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1) throw new Failure(Messages.Hudson_UnsafeChar(ch)); } // looks good } /** * Makes sure that the given name is good as a job name. * @return trimmed name if valid; throws Failure if not */ private String checkJobName(String name) throws Failure { checkGoodName(name); name = name.trim(); projectNamingStrategy.checkName(name); if(getItem(name)!=null) throw new Failure(Messages.Hudson_JobAlreadyExists(name)); // looks good return name; } private static String toPrintableName(String name) { StringBuilder printableName = new StringBuilder(); for( int i=0; i<name.length(); i++ ) { char ch = name.charAt(i); if(Character.isISOControl(ch)) printableName.append("\\u").append((int)ch).append(';'); else printableName.append(ch); } return printableName.toString(); } /** * Checks if the user was successfully authenticated. * * @see BasicAuthenticationFilter */ public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { // TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active) if(req.getUserPrincipal()==null) { // authentication must have failed rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } // the user is now authenticated, so send him back to the target String path = req.getContextPath()+req.getOriginalRestOfPath(); String q = req.getQueryString(); if(q!=null) path += '?'+q; rsp.sendRedirect2(path); } /** * Called once the user logs in. Just forward to the top page. * Used only by {@link LegacySecurityRealm}. */ public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException { if(req.getUserPrincipal()==null) { rsp.sendRedirect2("noPrincipal"); return; } // TODO fire something in SecurityListener? String from = req.getParameter("from"); if(from!=null && from.startsWith("/") && !from.equals("/loginError")) { rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain return; } String url = AbstractProcessingFilter.obtainFullRequestUrl(req); if(url!=null) { // if the login redirect is initiated by Acegi // this should send the user back to where s/he was from. rsp.sendRedirect2(url); return; } rsp.sendRedirect2("."); } /** * Logs out the user. */ public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { String user = getAuthentication().getName(); securityRealm.doLogout(req, rsp); SecurityListener.fireLoggedOut(user); } /** * Serves jar files for JNLP slave agents. */ public Slave.JnlpJar getJnlpJars(String fileName) { return new Slave.JnlpJar(fileName); } public Slave.JnlpJar doJnlpJars(StaplerRequest req) { return new Slave.JnlpJar(req.getRestOfPath().substring(1)); } /** * Reloads the configuration. */ @CLIMethod(name="reload-configuration") @RequirePOST public synchronized HttpResponse doReload() throws IOException { checkPermission(ADMINISTER); // engage "loading ..." UI and then run the actual task in a separate thread servletContext.setAttribute("app", new HudsonIsLoading()); new Thread("Jenkins config reload thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); reload(); } catch (Exception e) { LOGGER.log(SEVERE,"Failed to reload Jenkins config",e); new JenkinsReloadFailed(e).publish(servletContext,root); } } }.start(); return HttpResponses.redirectViaContextPath("/"); } /** * Reloads the configuration synchronously. */ public void reload() throws IOException, InterruptedException, ReactorException { executeReactor(null, loadTasks()); User.reload(); servletContext.setAttribute("app", this); } /** * Do a finger-print check. */ public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { // Parse the request MultipartFormDataParser p = new MultipartFormDataParser(req); if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found"); } try { rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+ Util.getDigestOf(p.getFileItem("name").getInputStream())+'/'); } finally { p.cleanUp(); } } /** * For debugging. Expose URL to perform GC. */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC") @RequirePOST public void doGc(StaplerResponse rsp) throws IOException { checkPermission(Jenkins.ADMINISTER); System.gc(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("GCed"); } /** * End point that intentionally throws an exception to test the error behaviour. * @since 1.467 */ public void doException() { throw new RuntimeException(); } public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException { ContextMenu menu = new ContextMenu().from(this, request, response); for (MenuItem i : menu.items) { if (i.url.equals(request.getContextPath() + "/manage")) { // add "Manage Jenkins" subitems i.subMenu = new ContextMenu().from(this, request, response, "manage"); } } return menu; } public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception { ContextMenu menu = new ContextMenu(); for (View view : getViews()) { menu.add(view.getViewUrl(),view.getDisplayName()); } return menu; } /** * Obtains the heap dump. */ public HeapDump getHeapDump() throws IOException { return new HeapDump(this,FilePath.localChannel); } /** * Simulates OutOfMemoryError. * Useful to make sure OutOfMemoryHeapDump setting. */ @RequirePOST public void doSimulateOutOfMemory() throws IOException { checkPermission(ADMINISTER); System.out.println("Creating artificial OutOfMemoryError situation"); List<Object> args = new ArrayList<Object>(); while (true) args.add(new byte[1024*1024]); } /** * Binds /userContent/... to $JENKINS_HOME/userContent. */ public DirectoryBrowserSupport doUserContent() { return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true); } /** * Perform a restart of Jenkins, if we can. * * This first replaces "app" to {@link HudsonIsRestarting} */ @CLIMethod(name="restart") public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException { checkPermission(ADMINISTER); if (req != null && req.getMethod().equals("GET")) { req.getView(this,"_restart.jelly").forward(req,rsp); return; } restart(); if (rsp != null) // null for CLI rsp.sendRedirect2("."); } /** * Queues up a restart of Jenkins for when there are no builds running, if we can. * * This first replaces "app" to {@link HudsonIsRestarting} * * @since 1.332 */ @CLIMethod(name="safe-restart") public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException { checkPermission(ADMINISTER); if (req != null && req.getMethod().equals("GET")) return HttpResponses.forwardToView(this,"_safeRestart.jelly"); safeRestart(); return HttpResponses.redirectToDot(); } /** * Performs a restart. */ public void restart() throws RestartNotSupportedException { final Lifecycle lifecycle = Lifecycle.get(); lifecycle.verifyRestartable(); // verify that Jenkins is restartable servletContext.setAttribute("app", new HudsonIsRestarting()); new Thread("restart thread") { final String exitUser = getAuthentication().getName(); @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); // give some time for the browser to load the "reloading" page Thread.sleep(5000); LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser)); for (RestartListener listener : RestartListener.all()) listener.onRestart(); lifecycle.restart(); } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e); } } }.start(); } /** * Queues up a restart to be performed once there are no builds currently running. * @since 1.332 */ public void safeRestart() throws RestartNotSupportedException { final Lifecycle lifecycle = Lifecycle.get(); lifecycle.verifyRestartable(); // verify that Jenkins is restartable // Quiet down so that we won't launch new builds. isQuietingDown = true; new Thread("safe-restart thread") { final String exitUser = getAuthentication().getName(); @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); // Wait 'til we have no active executors. doQuietDown(true, 0); // Make sure isQuietingDown is still true. if (isQuietingDown) { servletContext.setAttribute("app",new HudsonIsRestarting()); // give some time for the browser to load the "reloading" page LOGGER.info("Restart in 10 seconds"); Thread.sleep(10000); LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser)); for (RestartListener listener : RestartListener.all()) listener.onRestart(); lifecycle.restart(); } else { LOGGER.info("Safe-restart mode cancelled"); } } catch (Throwable e) { LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e); } } }.start(); } @Extension @Restricted(NoExternalUse.class) public static class MasterRestartNotifyier extends RestartListener { @Override public void onRestart() { Computer computer = Jenkins.getInstance().toComputer(); if (computer == null) return; RestartCause cause = new RestartCause(); for (ComputerListener listener: ComputerListener.all()) { listener.onOffline(computer, cause); } } @Override public boolean isReadyToRestart() throws IOException, InterruptedException { return true; } private static class RestartCause extends OfflineCause.SimpleOfflineCause { protected RestartCause() { super(Messages._Jenkins_IsRestarting()); } } } /** * Shutdown the system. * @since 1.161 */ @CLIMethod(name="shutdown") @RequirePOST public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException { checkPermission(ADMINISTER); LOGGER.severe(String.format("Shutting down VM as requested by %s from %s", getAuthentication().getName(), req!=null?req.getRemoteAddr():"???")); if (rsp!=null) { rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); PrintWriter w = rsp.getWriter(); w.println("Shutting down"); w.close(); } System.exit(0); } /** * Shutdown the system safely. * @since 1.332 */ @CLIMethod(name="safe-shutdown") @RequirePOST public HttpResponse doSafeExit(StaplerRequest req) throws IOException { checkPermission(ADMINISTER); isQuietingDown = true; final String exitUser = getAuthentication().getName(); final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown"; new Thread("safe-exit thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); LOGGER.severe(String.format("Shutting down VM as requested by %s from %s", exitUser, exitAddr)); // Wait 'til we have no active executors. doQuietDown(true, 0); // Make sure isQuietingDown is still true. if (isQuietingDown) { cleanUp(); System.exit(0); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e); } } }.start(); return HttpResponses.plainText("Shutting down as soon as all jobs are complete"); } /** * Gets the {@link Authentication} object that represents the user * associated with the current request. */ public static @Nonnull Authentication getAuthentication() { Authentication a = SecurityContextHolder.getContext().getAuthentication(); // on Tomcat while serving the login page, this is null despite the fact // that we have filters. Looking at the stack trace, Tomcat doesn't seem to // run the request through filters when this is the login request. // see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html if(a==null) a = ANONYMOUS; return a; } /** * For system diagnostics. * Run arbitrary Groovy script. */ public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { _doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL()); } /** * Run arbitrary Groovy script and return result as plain text. */ public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { _doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL()); } /** * @since 1.509.1 */ public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException { // ability to run arbitrary script is dangerous acl.checkPermission(RUN_SCRIPTS); String text = req.getParameter("script"); if (text != null) { if (!"POST".equals(req.getMethod())) { throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST"); } if (channel == null) { throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline"); } try { req.setAttribute("output", RemotingDiagnostics.executeGroovy(text, channel)); } catch (InterruptedException e) { throw new ServletException(e); } } view.forward(req, rsp); } /** * Evaluates the Jelly script submitted by the client. * * This is useful for system administration as well as unit testing. */ @RequirePOST public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(RUN_SCRIPTS); try { MetaClass mc = WebApp.getCurrent().getMetaClass(getClass()); Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader())); new JellyRequestDispatcher(this,script).forward(req,rsp); } catch (JellyException e) { throw new ServletException(e); } } /** * Sign up for the user account. */ public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { if (getSecurityRealm().allowsSignup()) { req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp); return; } req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp); } /** * Changes the icon size by changing the cookie */ public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { String qs = req.getQueryString(); if(qs==null) throw new ServletException(); Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs)); cookie.setMaxAge(/* ~4 mo. */9999999); // #762 rsp.addCookie(cookie); String ref = req.getHeader("Referer"); if(ref==null) ref="."; rsp.sendRedirect2(ref); } @RequirePOST public void doFingerprintCleanup(StaplerResponse rsp) throws IOException { checkPermission(ADMINISTER); FingerprintCleanupThread.invoke(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("Invoked"); } @RequirePOST public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException { checkPermission(ADMINISTER); WorkspaceCleanupThread.invoke(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("Invoked"); } /** * If the user chose the default JDK, make sure we got 'java' in PATH. */ public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) { if(!value.equals(JDK.DEFAULT_NAME)) // assume the user configured named ones properly in system config --- // or else system config should have reported form field validation errors. return FormValidation.ok(); // default JDK selected. Does such java really exist? if(JDK.isDefaultJDKValid(Jenkins.this)) return FormValidation.ok(); else return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath())); } /** * Makes sure that the given name is good as a job name. */ public FormValidation doCheckJobName(@QueryParameter String value) { // this method can be used to check if a file exists anywhere in the file system, // so it should be protected. checkPermission(Item.CREATE); if(fixEmpty(value)==null) return FormValidation.ok(); try { checkJobName(value); return FormValidation.ok(); } catch (Failure e) { return FormValidation.error(e.getMessage()); } } /** * Checks if a top-level view with the given name exists and * make sure that the name is good as a view name. */ public FormValidation doCheckViewName(@QueryParameter String value) { checkPermission(View.CREATE); String name = fixEmpty(value); if (name == null) return FormValidation.ok(); // already exists? if (getView(name) != null) return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name)); // good view name? try { checkGoodName(name); } catch (Failure e) { return FormValidation.error(e.getMessage()); } return FormValidation.ok(); } /** * Checks if a top-level view with the given name exists. * @deprecated 1.512 */ @Deprecated public FormValidation doViewExistsCheck(@QueryParameter String value) { checkPermission(View.CREATE); String view = fixEmpty(value); if(view==null) return FormValidation.ok(); if(getView(view)==null) return FormValidation.ok(); else return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view)); } /** * Serves static resources placed along with Jelly view files. * <p> * This method can serve a lot of files, so care needs to be taken * to make this method secure. It's not clear to me what's the best * strategy here, though the current implementation is based on * file extensions. */ public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); // cut off the "..." portion of /resources/.../path/to/file // as this is only used to make path unique (which in turn // allows us to set a long expiration date path = path.substring(path.indexOf('/',1)+1); int idx = path.lastIndexOf('.'); String extension = path.substring(idx+1); if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) { URL url = pluginManager.uberClassLoader.getResource(path); if(url!=null) { long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/ rsp.serveFile(req,url,expires); return; } } rsp.sendError(HttpServletResponse.SC_NOT_FOUND); } /** * Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve. * This set is mutable to allow plugins to add additional extensions. */ public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList( "js|css|jpeg|jpg|png|gif|html|htm".split("\\|") )); /** * Checks if container uses UTF-8 to decode URLs. See * http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n */ public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException { // expected is non-ASCII String final String expected = "\u57f7\u4e8b"; final String value = fixEmpty(request.getParameter("value")); if (!expected.equals(value)) return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL()); return FormValidation.ok(); } /** * Does not check when system default encoding is "ISO-8859-1". */ public static boolean isCheckURIEncodingEnabled() { return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding")); } /** * Rebuilds the dependency map. */ public void rebuildDependencyGraph() { DependencyGraph graph = new DependencyGraph(); graph.build(); // volatile acts a as a memory barrier here and therefore guarantees // that graph is fully build, before it's visible to other threads dependencyGraph = graph; dependencyGraphDirty.set(false); } /** * Rebuilds the dependency map asynchronously. * * <p> * This would keep the UI thread more responsive and helps avoid the deadlocks, * as dependency graph recomputation tends to touch a lot of other things. * * @since 1.522 */ public Future<DependencyGraph> rebuildDependencyGraphAsync() { dependencyGraphDirty.set(true); return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() { @Override public DependencyGraph call() throws Exception { if (dependencyGraphDirty.get()) { rebuildDependencyGraph(); } return dependencyGraph; } }, 500, TimeUnit.MILLISECONDS); } public DependencyGraph getDependencyGraph() { return dependencyGraph; } // for Jelly public List<ManagementLink> getManagementLinks() { return ManagementLink.all(); } /** * Exposes the current user to <tt>/me</tt> URL. */ public User getMe() { User u = User.current(); if (u == null) throw new AccessDeniedException("/me is not available when not logged in"); return u; } /** * Gets the {@link Widget}s registered on this object. * * <p> * Plugins who wish to contribute boxes on the side panel can add widgets * by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}. */ public List<Widget> getWidgets() { return widgets; } public Object getTarget() { try { checkPermission(READ); } catch (AccessDeniedException e) { String rest = Stapler.getCurrentRequest().getRestOfPath(); if(rest.startsWith("/login") || rest.startsWith("/logout") || rest.startsWith("/accessDenied") || rest.startsWith("/adjuncts/") || rest.startsWith("/error") || rest.startsWith("/oops") || rest.startsWith("/signup") || rest.startsWith("/tcpSlaveAgentListener") // TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access || rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt")) || rest.startsWith("/federatedLoginService/") || rest.startsWith("/securityRealm")) return this; // URLs that are always visible without READ permission for (String name : getUnprotectedRootActions()) { if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) { return this; } } throw e; } return this; } /** * Gets a list of unprotected root actions. * These URL prefixes should be exempted from access control checks by container-managed security. * Ideally would be synchronized with {@link #getTarget}. * @return a list of {@linkplain Action#getUrlName URL names} * @since 1.495 */ public Collection<String> getUnprotectedRootActions() { Set<String> names = new TreeSet<String>(); names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA // TODO consider caching (expiring cache when actions changes) for (Action a : getActions()) { if (a instanceof UnprotectedRootAction) { names.add(a.getUrlName()); } } return names; } /** * Fallback to the primary view. */ public View getStaplerFallback() { return getPrimaryView(); } /** * This method checks all existing jobs to see if displayName is * unique. It does not check the displayName against the displayName of the * job that the user is configuring though to prevent a validation warning * if the user sets the displayName to what it currently is. * @param displayName * @param currentJobName */ boolean isDisplayNameUnique(String displayName, String currentJobName) { Collection<TopLevelItem> itemCollection = items.values(); // if there are a lot of projects, we'll have to store their // display names in a HashSet or something for a quick check for(TopLevelItem item : itemCollection) { if(item.getName().equals(currentJobName)) { // we won't compare the candidate displayName against the current // item. This is to prevent an validation warning if the user // sets the displayName to what the existing display name is continue; } else if(displayName.equals(item.getDisplayName())) { return false; } } return true; } /** * True if there is no item in Jenkins that has this name * @param name The name to test * @param currentJobName The name of the job that the user is configuring */ boolean isNameUnique(String name, String currentJobName) { Item item = getItem(name); if(null==item) { // the candidate name didn't return any items so the name is unique return true; } else if(item.getName().equals(currentJobName)) { // the candidate name returned an item, but the item is the item // that the user is configuring so this is ok return true; } else { // the candidate name returned an item, so it is not unique return false; } } /** * Checks to see if the candidate displayName collides with any * existing display names or project names * @param displayName The display name to test * @param jobName The name of the job the user is configuring */ public FormValidation doCheckDisplayName(@QueryParameter String displayName, @QueryParameter String jobName) { displayName = displayName.trim(); if(LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Current job name is " + jobName); } if(!isNameUnique(displayName, jobName)) { return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName)); } else if(!isDisplayNameUnique(displayName, jobName)){ return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName)); } else { return FormValidation.ok(); } } public static class MasterComputer extends Computer { protected MasterComputer() { super(Jenkins.getInstance()); } /** * Returns "" to match with {@link Jenkins#getNodeName()}. */ @Override public String getName() { return ""; } @Override public boolean isConnecting() { return false; } @Override public String getDisplayName() { return Messages.Hudson_Computer_DisplayName(); } @Override public String getCaption() { return Messages.Hudson_Computer_Caption(); } @Override public String getUrl() { return "computer/(master)/"; } public RetentionStrategy getRetentionStrategy() { return RetentionStrategy.NOOP; } /** * Will always keep this guy alive so that it can function as a fallback to * execute {@link FlyweightTask}s. See JENKINS-7291. */ @Override protected boolean isAlive() { return true; } @Override public Boolean isUnix() { return !Functions.isWindows(); } /** * Report an error. */ @Override public HttpResponse doDoDelete() throws IOException { throw HttpResponses.status(SC_BAD_REQUEST); } @Override public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp); } @WebMethod(name="config.xml") @Override public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { throw HttpResponses.status(SC_BAD_REQUEST); } @Override public boolean hasPermission(Permission permission) { // no one should be allowed to delete the master. // this hides the "delete" link from the /computer/(master) page. if(permission==Computer.DELETE) return false; // Configuration of master node requires ADMINISTER permission return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission); } @Override public VirtualChannel getChannel() { return FilePath.localChannel; } @Override public Charset getDefaultCharset() { return Charset.defaultCharset(); } public List<LogRecord> getLogRecords() throws IOException, InterruptedException { return logRecords; } @RequirePOST public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this computer never returns null from channel, so // this method shall never be invoked. rsp.sendError(SC_NOT_FOUND); } protected Future<?> _connect(boolean forceReconnect) { return Futures.precomputed(null); } /** * {@link LocalChannel} instance that can be used to execute programs locally. * * @deprecated as of 1.558 * Use {@link FilePath#localChannel} */ @Deprecated public static final LocalChannel localChannel = FilePath.localChannel; } /** * Shortcut for {@code Jenkins.getInstance().lookup.get(type)} */ public static @CheckForNull <T> T lookup(Class<T> type) { Jenkins j = Jenkins.getInstance(); return j != null ? j.lookup.get(type) : null; } /** * Live view of recent {@link LogRecord}s produced by Jenkins. */ public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE /** * Thread-safe reusable {@link XStream}. */ public static final XStream XSTREAM; /** * Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily. */ public static final XStream2 XSTREAM2; private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2); /** * Thread pool used to load configuration in parallel, to improve the start up time. * <p> * The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers. */ /*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor( TWICE_CPU_NUM, TWICE_CPU_NUM, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load")); private static void computeVersion(ServletContext context) { // set the version Properties props = new Properties(); InputStream is = null; try { is = Jenkins.class.getResourceAsStream("jenkins-version.properties"); if(is!=null) props.load(is); } catch (IOException e) { e.printStackTrace(); // if the version properties is missing, that's OK. } finally { IOUtils.closeQuietly(is); } String ver = props.getProperty("version"); if(ver==null) ver="?"; VERSION = ver; context.setAttribute("version",ver); VERSION_HASH = Util.getDigestOf(ver).substring(0, 8); SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8); if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache")) RESOURCE_PATH = ""; else RESOURCE_PATH = "/static/"+SESSION_HASH; VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH; } /** * Version number of this Jenkins. */ public static String VERSION="?"; /** * Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number * (such as when Jenkins is run with "mvn hudson-dev:run") */ public static VersionNumber getVersion() { try { return new VersionNumber(VERSION); } catch (NumberFormatException e) { try { // for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate. int idx = VERSION.indexOf(' '); if (idx>0) return new VersionNumber(VERSION.substring(0,idx)); } catch (NumberFormatException _) { // fall through } // totally unparseable return null; } catch (IllegalArgumentException e) { // totally unparseable return null; } } /** * Hash of {@link #VERSION}. */ public static String VERSION_HASH; /** * Unique random token that identifies the current session. * Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header. * * We used to use {@link #VERSION_HASH}, but making this session local allows us to * reuse the same {@link #RESOURCE_PATH} for static resources in plugins. */ public static String SESSION_HASH; /** * Prefix to static resources like images and javascripts in the war file. * Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up * stale cache when the user upgrades to a different version. * <p> * Value computed in {@link WebAppMain}. */ public static String RESOURCE_PATH = ""; /** * Prefix to resources alongside view scripts. * Strings like "/resources/VERSION", which avoids Jenkins to pick up * stale cache when the user upgrades to a different version. * <p> * Value computed in {@link WebAppMain}. */ public static String VIEW_RESOURCE_PATH = "/resources/TBD"; public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true); public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false); /** * @deprecated No longer used. */ @Deprecated public static boolean FLYWEIGHT_SUPPORT = true; /** * Tentative switch to activate the concurrent build behavior. * When we merge this back to the trunk, this allows us to keep * this feature hidden for a while until we iron out the kinks. * @see AbstractProject#isConcurrentBuild() * @deprecated as of 1.464 * This flag will have no effect. */ @Restricted(NoExternalUse.class) @Deprecated public static boolean CONCURRENT_BUILD = true; /** * Switch to enable people to use a shorter workspace name. */ private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace"); /** * Automatically try to launch a slave when Jenkins is initialized or a new slave is created. */ public static boolean AUTOMATIC_SLAVE_LAUNCH = true; private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName()); public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS; public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER; public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS); public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS); /** * {@link Authentication} object that represents the anonymous user. * Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not * expect the singleton semantics. This is just a convenient instance. * * @since 1.343 */ public static final Authentication ANONYMOUS; static { try { ANONYMOUS = new AnonymousAuthenticationToken( "anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")}); XSTREAM = XSTREAM2 = new XStream2(); XSTREAM.alias("jenkins", Jenkins.class); XSTREAM.alias("slave", DumbSlave.class); XSTREAM.alias("jdk", JDK.class); // for backward compatibility with <1.75, recognize the tag name "view" as well. XSTREAM.alias("view", ListView.class); XSTREAM.alias("listView", ListView.class); XSTREAM2.addCriticalField(Jenkins.class, "securityRealm"); XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy"); // this seems to be necessary to force registration of converter early enough Mode.class.getEnumConstants(); // double check that initialization order didn't do any harm assert PERMISSIONS != null; assert ADMINISTER != null; } catch (RuntimeException e) { // when loaded on a slave and this fails, subsequent NoClassDefFoundError will fail to chain the cause. // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847 // As we don't know where the first exception will go, let's also send this to logging so that // we have a known place to look at. LOGGER.log(SEVERE, "Failed to load Jenkins.class", e); throw e; } catch (Error e) { LOGGER.log(SEVERE, "Failed to load Jenkins.class", e); throw e; } } }
./CrossVul/dataset_final_sorted/CWE-269/java/good_3057_0
crossvul-java_data_good_3047_2
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * 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.model; import com.thoughtworks.xstream.XStream; import hudson.DescriptorExtensionList; import hudson.Extension; import hudson.XmlFile; import hudson.model.listeners.ItemListener; import hudson.remoting.Callable; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.triggers.Trigger; import hudson.util.DescriptorList; import hudson.util.EditDistance; import hudson.util.XStream2; import jenkins.model.Jenkins; import org.acegisecurity.Authentication; import org.apache.commons.lang.StringUtils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Stack; import java.util.StringTokenizer; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import jenkins.model.DirectlyModifiableTopLevelItemGroup; import org.acegisecurity.context.SecurityContext; import org.acegisecurity.context.SecurityContextHolder; import org.apache.commons.io.FileUtils; /** * Convenience methods related to {@link Item}. * * @author Kohsuke Kawaguchi */ public class Items { /** * List of all installed {@link TopLevelItem} types. * * @deprecated as of 1.286 * Use {@link #all()} for read access and {@link Extension} for registration. */ @Deprecated public static final List<TopLevelItemDescriptor> LIST = (List)new DescriptorList<TopLevelItem>(TopLevelItem.class); /** * Used to behave differently when loading posted configuration as opposed to persisted configuration. * @see Trigger#start * @since 1.482 */ private static final ThreadLocal<Boolean> updatingByXml = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; /** * Runs a block while making {@link #currentlyUpdatingByXml} be temporarily true. * Use this when you are creating or changing an item. * @param <V> a return value type (may be {@link Void}) * @param <T> an error type (may be {@link Error}) * @param callable a block, typically running {@link #load} or {@link Item#onLoad} * @return whatever {@code callable} returned * @throws T anything {@code callable} throws * @since 1.546 */ public static <V,T extends Throwable> V whileUpdatingByXml(Callable<V,T> callable) throws T { updatingByXml.set(true); try { return callable.call(); } finally { updatingByXml.set(false); } } /** * Checks whether we are in the middle of creating or configuring an item via XML. * Used to determine the {@code newInstance} parameter for {@link Trigger#start}. * @return true if {@link #whileUpdatingByXml} is currently being called, false for example when merely starting Jenkins or reloading from disk * @since 1.546 */ public static boolean currentlyUpdatingByXml() { return updatingByXml.get(); } /** * Returns all the registered {@link TopLevelItemDescriptor}s. */ public static DescriptorExtensionList<TopLevelItem,TopLevelItemDescriptor> all() { return Jenkins.getInstance().<TopLevelItem,TopLevelItemDescriptor>getDescriptorList(TopLevelItem.class); } /** * Returns all the registered {@link TopLevelItemDescriptor}s that the current security principal is allowed to * create within the specified item group. * * @since TODO */ public static List<TopLevelItemDescriptor> all(ItemGroup c) { return all(Jenkins.getAuthentication(), c); } /** * Returns all the registered {@link TopLevelItemDescriptor}s that the specified security principal is allowed to * create within the specified item group. * * @since TODO */ public static List<TopLevelItemDescriptor> all(Authentication a, ItemGroup c) { List<TopLevelItemDescriptor> result = new ArrayList<TopLevelItemDescriptor>(); ACL acl; if (c instanceof AccessControlled) { acl = ((AccessControlled) c).getACL(); } else { // fall back to root acl = Jenkins.getInstance().getACL(); } for (TopLevelItemDescriptor d: all()) { if (acl.hasCreatePermission(a, c, d) && d.isApplicableIn(c)) { result.add(d); } } return result; } /** * @deprecated Underspecified what the parameter is. {@link Descriptor#getId}? A {@link Describable} class name? */ public static TopLevelItemDescriptor getDescriptor(String fqcn) { return Descriptor.find(all(), fqcn); } /** * Converts a list of items into a comma-separated list of full names. */ public static String toNameList(Collection<? extends Item> items) { StringBuilder buf = new StringBuilder(); for (Item item : items) { if(buf.length()>0) buf.append(", "); buf.append(item.getFullName()); } return buf.toString(); } /** * @deprecated as of 1.406 * Use {@link #fromNameList(ItemGroup, String, Class)} */ @Deprecated public static <T extends Item> List<T> fromNameList(String list, Class<T> type) { return fromNameList(null,list,type); } /** * Does the opposite of {@link #toNameList(Collection)}. */ public static <T extends Item> List<T> fromNameList(ItemGroup context, @Nonnull String list, @Nonnull Class<T> type) { Jenkins hudson = Jenkins.getInstance(); List<T> r = new ArrayList<T>(); StringTokenizer tokens = new StringTokenizer(list,","); while(tokens.hasMoreTokens()) { String fullName = tokens.nextToken().trim(); T item = hudson.getItem(fullName, context, type); if(item!=null) r.add(item); } return r; } /** * Computes the canonical full name of a relative path in an {@link ItemGroup} context, handling relative * positions ".." and "." as absolute path starting with "/". The resulting name is the item fullName from Jenkins * root. */ public static String getCanonicalName(ItemGroup context, String path) { String[] c = context.getFullName().split("/"); String[] p = path.split("/"); Stack<String> name = new Stack<String>(); for (int i=0; i<c.length;i++) { if (i==0 && c[i].equals("")) continue; name.push(c[i]); } for (int i=0; i<p.length;i++) { if (i==0 && p[i].equals("")) { // Absolute path starting with a "/" name.clear(); continue; } if (p[i].equals("..")) { if (name.size() == 0) { throw new IllegalArgumentException(String.format( "Illegal relative path '%s' within context '%s'", path, context.getFullName() )); } name.pop(); continue; } if (p[i].equals(".")) { continue; } name.push(p[i]); } return StringUtils.join(name, '/'); } /** * Computes the relative name of list of items after a rename or move occurred. * Used to manage job references as names in plugins to support {@link hudson.model.listeners.ItemListener#onLocationChanged}. * <p> * In a hierarchical context, when a plugin has a reference to a job as <code>../foo/bar</code> this method will * handle the relative path as "foo" is renamed to "zot" to compute <code>../zot/bar</code> * * @param oldFullName the old full name of the item * @param newFullName the new full name of the item * @param relativeNames coma separated list of Item relative names * @param context the {link ItemGroup} relative names refer to * @return relative name for the renamed item, based on the same ItemGroup context */ public static String computeRelativeNamesAfterRenaming(String oldFullName, String newFullName, String relativeNames, ItemGroup context) { StringTokenizer tokens = new StringTokenizer(relativeNames,","); List<String> newValue = new ArrayList<String>(); while(tokens.hasMoreTokens()) { String relativeName = tokens.nextToken().trim(); String canonicalName = getCanonicalName(context, relativeName); if (canonicalName.equals(oldFullName) || canonicalName.startsWith(oldFullName+'/')) { String newCanonicalName = newFullName + canonicalName.substring(oldFullName.length()); if (relativeName.startsWith("/")) { newValue.add("/" + newCanonicalName); } else { newValue.add(getRelativeNameFrom(newCanonicalName, context.getFullName())); } } else { newValue.add(relativeName); } } return StringUtils.join(newValue, ","); } // Had difficulty adapting the version in Functions to use no live items, so rewrote it: static String getRelativeNameFrom(String itemFullName, String groupFullName) { String[] itemFullNameA = itemFullName.isEmpty() ? new String[0] : itemFullName.split("/"); String[] groupFullNameA = groupFullName.isEmpty() ? new String[0] : groupFullName.split("/"); for (int i = 0; ; i++) { if (i == itemFullNameA.length) { if (i == groupFullNameA.length) { // itemFullName and groupFullName are identical return "."; } else { // itemFullName is an ancestor of groupFullName; insert ../ for rest of groupFullName StringBuilder b = new StringBuilder(); for (int j = 0; j < groupFullNameA.length - itemFullNameA.length; j++) { if (j > 0) { b.append('/'); } b.append(".."); } return b.toString(); } } else if (i == groupFullNameA.length) { // groupFullName is an ancestor of itemFullName; insert rest of itemFullName StringBuilder b = new StringBuilder(); for (int j = i; j < itemFullNameA.length; j++) { if (j > i) { b.append('/'); } b.append(itemFullNameA[j]); } return b.toString(); } else if (itemFullNameA[i].equals(groupFullNameA[i])) { // identical up to this point continue; } else { // first mismatch; insert ../ for rest of groupFullName, then rest of itemFullName StringBuilder b = new StringBuilder(); for (int j = i; j < groupFullNameA.length; j++) { if (j > i) { b.append('/'); } b.append(".."); } for (int j = i; j < itemFullNameA.length; j++) { b.append('/').append(itemFullNameA[j]); } return b.toString(); } } } /** * Loads a {@link Item} from a config file. * * @param dir * The directory that contains the config file, not the config file itself. */ public static Item load(ItemGroup parent, File dir) throws IOException { Item item = (Item)getConfigFile(dir).read(); item.onLoad(parent,dir.getName()); return item; } /** * The file we save our configuration. */ public static XmlFile getConfigFile(File dir) { return new XmlFile(XSTREAM,new File(dir,"config.xml")); } /** * The file we save our configuration. */ public static XmlFile getConfigFile(Item item) { return getConfigFile(item.getRootDir()); } /** * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree * and filter them by the given type. * * @since 1.512 */ public static <T extends Item> List<T> getAllItems(final ItemGroup root, Class<T> type) { List<T> r = new ArrayList<T>(); getAllItems(root, type, r); return r; } private static <T extends Item> void getAllItems(final ItemGroup root, Class<T> type, List<T> r) { List<Item> items = new ArrayList<Item>(((ItemGroup<?>) root).getItems()); Collections.sort(items, new Comparator<Item>() { @Override public int compare(Item i1, Item i2) { return name(i1).compareToIgnoreCase(name(i2)); } String name(Item i) { String n = i.getName(); if (i instanceof ItemGroup) { n += '/'; } return n; } }); for (Item i : items) { if (type.isInstance(i)) { if (i.hasPermission(Item.READ)) { r.add(type.cast(i)); } } if (i instanceof ItemGroup) { getAllItems((ItemGroup) i, type, r); } } } /** * Finds an item whose name (when referenced from the specified context) is closest to the given name. * @param <T> the type of item being considered * @param type same as {@code T} * @param name the supplied name * @param context a context to start from (used to compute relative names) * @return the closest available item * @since 1.538 */ public static @CheckForNull <T extends Item> T findNearest(Class<T> type, String name, ItemGroup context) { List<T> projects = Jenkins.getInstance().getAllItems(type); String[] names = new String[projects.size()]; for (int i = 0; i < projects.size(); i++) { names[i] = projects.get(i).getRelativeNameFrom(context); } String nearest = EditDistance.findNearest(name, names); return Jenkins.getInstance().getItem(nearest, context, type); } /** * Moves an item between folders (or top level). * Fires all relevant events but does not verify that the item’s directory is not currently being used in some way (for example by a running build). * Does not check any permissions. * @param item some item (job or folder) * @param destination the destination of the move (a folder or {@link Jenkins}); not the current parent (or you could just call {@link AbstractItem#renameTo}) * @return the new item (usually the same object as {@code item}) * @throws IOException if the move fails, or some subsequent step fails (directory might have already been moved) * @throws IllegalArgumentException if the move would really be a rename, or the destination cannot accept the item, or the destination already has an item of that name * @since 1.548 */ public static <I extends AbstractItem & TopLevelItem> I move(I item, DirectlyModifiableTopLevelItemGroup destination) throws IOException, IllegalArgumentException { DirectlyModifiableTopLevelItemGroup oldParent = (DirectlyModifiableTopLevelItemGroup) item.getParent(); if (oldParent == destination) { throw new IllegalArgumentException(); } // TODO verify that destination is to not equal to, or inside, item if (!destination.canAdd(item)) { throw new IllegalArgumentException(); } String name = item.getName(); verifyItemDoesNotAlreadyExist(destination, name, null); String oldFullName = item.getFullName(); // TODO AbstractItem.renameTo has a more baroque implementation; factor it out into a utility method perhaps? File destDir = destination.getRootDirFor(item); FileUtils.forceMkdir(destDir.getParentFile()); FileUtils.moveDirectory(item.getRootDir(), destDir); oldParent.remove(item); I newItem = destination.add(item, name); item.movedTo(destination, newItem, destDir); ItemListener.fireLocationChange(newItem, oldFullName); return newItem; } /** * Securely check for the existence of an item before trying to create one with the same name. * @param parent the folder where we are about to create/rename/move an item * @param newName the proposed new name * @param variant if not null, an existing item which we accept could be there * @throws IllegalArgumentException if there is already something there, which you were supposed to know about * @throws Failure if there is already something there but you should not be told details */ static void verifyItemDoesNotAlreadyExist(@Nonnull ItemGroup<?> parent, @Nonnull String newName, @CheckForNull Item variant) throws IllegalArgumentException, Failure { Item existing; SecurityContext orig = ACL.impersonate(ACL.SYSTEM); try { existing = parent.getItem(newName); } finally { SecurityContextHolder.setContext(orig); } if (existing != null && existing != variant) { if (existing.hasPermission(Item.DISCOVER)) { String prefix = parent.getFullName(); throw new IllegalArgumentException((prefix.isEmpty() ? "" : prefix + "/") + newName + " already exists"); } else { // Cannot hide its existence, so at least be as vague as possible. throw new Failure(""); } } } /** * Used to load/save job configuration. * * When you extend {@link Job} in a plugin, try to put the alias so * that it produces a reasonable XML. */ public static final XStream XSTREAM = new XStream2(); /** * Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily. */ public static final XStream2 XSTREAM2 = (XStream2)XSTREAM; static { XSTREAM.alias("project",FreeStyleProject.class); } }
./CrossVul/dataset_final_sorted/CWE-269/java/good_3047_2
crossvul-java_data_good_3047_0
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Daniel Dyer, Tom Huybrechts, Yahoo!, Inc. * * 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.model; import com.infradna.tool.bridge_method_injector.WithBridgeMethods; import hudson.AbortException; import hudson.XmlFile; import hudson.Util; import hudson.Functions; import hudson.BulkChange; import hudson.cli.declarative.CLIMethod; import hudson.cli.declarative.CLIResolver; import hudson.model.listeners.ItemListener; import hudson.model.listeners.SaveableListener; import hudson.security.AccessControlled; import hudson.security.Permission; import hudson.security.ACL; import hudson.util.AlternativeUiTextProvider; import hudson.util.AlternativeUiTextProvider.Message; import hudson.util.AtomicFileWriter; import hudson.util.IOUtils; import hudson.util.Secret; import jenkins.model.DirectlyModifiableTopLevelItemGroup; import jenkins.model.Jenkins; import jenkins.security.NotReallyRoleSensitiveCallable; import jenkins.util.xml.XMLUtils; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.types.FileSet; import org.kohsuke.stapler.WebMethod; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.List; import java.util.ListIterator; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nonnull; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.HttpDeletable; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.stapler.interceptor.RequirePOST; import org.xml.sax.SAXException; import javax.servlet.ServletException; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import org.apache.commons.io.FileUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.Ancestor; /** * Partial default implementation of {@link Item}. * * @author Kohsuke Kawaguchi */ // Item doesn't necessarily have to be Actionable, but // Java doesn't let multiple inheritance. @ExportedBean public abstract class AbstractItem extends Actionable implements Item, HttpDeletable, AccessControlled, DescriptorByNameOwner { private static final Logger LOGGER = Logger.getLogger(AbstractItem.class.getName()); /** * Project name. */ protected /*final*/ transient String name; /** * Project description. Can be HTML. */ protected volatile String description; private transient ItemGroup parent; protected String displayName; protected AbstractItem(ItemGroup parent, String name) { this.parent = parent; doSetName(name); } public void onCreatedFromScratch() { // noop } @Exported(visibility=999) public String getName() { return name; } /** * Get the term used in the UI to represent this kind of * {@link Item}. Must start with a capital letter. */ public String getPronoun() { return AlternativeUiTextProvider.get(PRONOUN, this, Messages.AbstractItem_Pronoun()); } @Exported /** * @return The display name of this object, or if it is not set, the name * of the object. */ public String getDisplayName() { if(null!=displayName) { return displayName; } // if the displayName is not set, then return the name as we use to do return getName(); } @Exported /** * This is intended to be used by the Job configuration pages where * we want to return null if the display name is not set. * @return The display name of this object or null if the display name is not * set */ public String getDisplayNameOrNull() { return displayName; } /** * This method exists so that the Job configuration pages can use * getDisplayNameOrNull so that nothing is shown in the display name text * box if the display name is not set. * @param displayName * @throws IOException */ public void setDisplayNameOrNull(String displayName) throws IOException { setDisplayName(displayName); } public void setDisplayName(String displayName) throws IOException { this.displayName = Util.fixEmpty(displayName); save(); } public File getRootDir() { return getParent().getRootDirFor(this); } /** * This bridge method is to maintain binary compatibility with {@link TopLevelItem#getParent()}. */ @WithBridgeMethods(value=Jenkins.class,castRequired=true) @Override public @Nonnull ItemGroup getParent() { if (parent == null) { throw new IllegalStateException("no parent set on " + getClass().getName() + "[" + name + "]"); } return parent; } /** * Gets the project description HTML. */ @Exported public String getDescription() { return description; } /** * Sets the project description HTML. */ public void setDescription(String description) throws IOException { this.description = description; save(); ItemListener.fireOnUpdated(this); } /** * Just update {@link #name} without performing the rename operation, * which would involve copying files and etc. */ protected void doSetName(String name) { this.name = name; } /** * Renames this item. * Not all the Items need to support this operation, but if you decide to do so, * you can use this method. */ protected void renameTo(final String newName) throws IOException { // always synchronize from bigger objects first final ItemGroup parent = getParent(); String oldName = this.name; String oldFullName = getFullName(); synchronized (parent) { synchronized (this) { // sanity check if (newName == null) throw new IllegalArgumentException("New name is not given"); // noop? if (this.name.equals(newName)) return; // the lookup is case insensitive, so we should not fail if this item was the “existing” one // to allow people to rename "Foo" to "foo", for example. // see http://www.nabble.com/error-on-renaming-project-tt18061629.html Items.verifyItemDoesNotAlreadyExist(parent, newName, this); File oldRoot = this.getRootDir(); doSetName(newName); File newRoot = this.getRootDir(); boolean success = false; try {// rename data files boolean interrupted = false; boolean renamed = false; // try to rename the job directory. // this may fail on Windows due to some other processes // accessing a file. // so retry few times before we fall back to copy. for (int retry = 0; retry < 5; retry++) { if (oldRoot.renameTo(newRoot)) { renamed = true; break; // succeeded } try { Thread.sleep(500); } catch (InterruptedException e) { // process the interruption later interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); if (!renamed) { // failed to rename. it must be that some lengthy // process is going on // to prevent a rename operation. So do a copy. Ideally // we'd like to // later delete the old copy, but we can't reliably do // so, as before the VM // shuts down there might be a new job created under the // old name. Copy cp = new Copy(); cp.setProject(new org.apache.tools.ant.Project()); cp.setTodir(newRoot); FileSet src = new FileSet(); src.setDir(oldRoot); cp.addFileset(src); cp.setOverwrite(true); cp.setPreserveLastModified(true); cp.setFailOnError(false); // keep going even if // there's an error cp.execute(); // try to delete as much as possible try { Util.deleteRecursive(oldRoot); } catch (IOException e) { // but ignore the error, since we expect that e.printStackTrace(); } } success = true; } finally { // if failed, back out the rename. if (!success) doSetName(oldName); } try { parent.onRenamed(this, oldName, newName); } catch (AbstractMethodError _) { // ignore } } } ItemListener.fireLocationChange(this, oldFullName); } /** * Notify this item it's been moved to another location, replaced by newItem (might be the same object, but not guaranteed). * This method is executed <em>after</em> the item root directory has been moved to it's new location. * <p> * Derived classes can override this method to add some specific behavior on move, but have to call parent method * so the item is actually setup within it's new parent. * * @see hudson.model.Items#move(AbstractItem, jenkins.model.DirectlyModifiableTopLevelItemGroup) */ public void movedTo(DirectlyModifiableTopLevelItemGroup destination, AbstractItem newItem, File destDir) throws IOException { newItem.onLoad(destination, name); } /** * Gets all the jobs that this {@link Item} contains as descendants. */ public abstract Collection<? extends Job> getAllJobs(); public final String getFullName() { String n = getParent().getFullName(); if(n.length()==0) return getName(); else return n+'/'+getName(); } public final String getFullDisplayName() { String n = getParent().getFullDisplayName(); if(n.length()==0) return getDisplayName(); else return n+" » "+getDisplayName(); } /** * Gets the display name of the current item relative to the given group. * * @since 1.515 * @param p the ItemGroup used as point of reference for the item * @return * String like "foo » bar" */ public String getRelativeDisplayNameFrom(ItemGroup p) { return Functions.getRelativeDisplayNameFrom(this, p); } /** * This method only exists to disambiguate {@link #getRelativeNameFrom(ItemGroup)} and {@link #getRelativeNameFrom(Item)} * @since 1.512 * @see #getRelativeNameFrom(ItemGroup) */ public String getRelativeNameFromGroup(ItemGroup p) { return getRelativeNameFrom(p); } /** * @param p * The ItemGroup instance used as context to evaluate the relative name of this AbstractItem * @return * The name of the current item, relative to p. * Nested ItemGroups are separated by / character. */ public String getRelativeNameFrom(ItemGroup p) { return Functions.getRelativeNameFrom(this, p); } public String getRelativeNameFrom(Item item) { return getRelativeNameFrom(item.getParent()); } /** * Called right after when a {@link Item} is loaded from disk. * This is an opportunity to do a post load processing. */ public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { this.parent = parent; doSetName(name); } /** * When a {@link Item} is copied from existing one, * the files are first copied on the file system, * then it will be loaded, then this method will be invoked * to perform any implementation-specific work. * * <p> * * * @param src * Item from which it's copied from. The same type as {@code this}. Never null. */ public void onCopiedFrom(Item src) { } public final String getUrl() { // try to stick to the current view if possible StaplerRequest req = Stapler.getCurrentRequest(); String shortUrl = getShortUrl(); String uri = req == null ? null : req.getRequestURI(); if (req != null) { String seed = Functions.getNearestAncestorUrl(req,this); LOGGER.log(Level.FINER, "seed={0} for {1} from {2}", new Object[] {seed, this, uri}); if(seed!=null) { // trim off the context path portion and leading '/', but add trailing '/' return seed.substring(req.getContextPath().length()+1)+'/'; } List<Ancestor> ancestors = req.getAncestors(); if (!ancestors.isEmpty()) { Ancestor last = ancestors.get(ancestors.size() - 1); if (last.getObject() instanceof View) { View view = (View) last.getObject(); if (view.getOwnerItemGroup() == getParent() && !view.isDefault()) { // Showing something inside a view, so should use that as the base URL. String base = last.getUrl().substring(req.getContextPath().length() + 1) + '/'; LOGGER.log(Level.FINER, "using {0}{1} for {2} from {3}", new Object[] {base, shortUrl, this, uri}); return base + shortUrl; } else { LOGGER.log(Level.FINER, "irrelevant {0} for {1} from {2}", new Object[] {view.getViewName(), this, uri}); } } else { LOGGER.log(Level.FINER, "inapplicable {0} for {1} from {2}", new Object[] {last.getObject(), this, uri}); } } else { LOGGER.log(Level.FINER, "no ancestors for {0} from {1}", new Object[] {this, uri}); } } else { LOGGER.log(Level.FINER, "no current request for {0}", this); } // otherwise compute the path normally String base = getParent().getUrl(); LOGGER.log(Level.FINER, "falling back to {0}{1} for {2} from {3}", new Object[] {base, shortUrl, this, uri}); return base + shortUrl; } public String getShortUrl() { String prefix = getParent().getUrlChildPrefix(); String subdir = Util.rawEncode(getName()); return prefix.equals(".") ? subdir + '/' : prefix + '/' + subdir + '/'; } public String getSearchUrl() { return getShortUrl(); } @Exported(visibility=999,name="url") public final String getAbsoluteUrl() { String r = Jenkins.getInstance().getRootUrl(); if(r==null) throw new IllegalStateException("Root URL isn't configured yet. Cannot compute absolute URL."); return Util.encode(r+getUrl()); } /** * Remote API access. */ public final Api getApi() { return new Api(this); } /** * Returns the {@link ACL} for this object. */ public ACL getACL() { return Jenkins.getInstance().getAuthorizationStrategy().getACL(this); } /** * Short for {@code getACL().checkPermission(p)} */ public void checkPermission(Permission p) { getACL().checkPermission(p); } /** * Short for {@code getACL().hasPermission(p)} */ public boolean hasPermission(Permission p) { return getACL().hasPermission(p); } /** * Save the settings to a file. */ public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } public final XmlFile getConfigFile() { return Items.getConfigFile(this); } public Descriptor getDescriptorByName(String className) { return Jenkins.getInstance().getDescriptorByName(className); } /** * Accepts the new description. */ public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { checkPermission(CONFIGURE); setDescription(req.getParameter("description")); rsp.sendRedirect("."); // go to the top page } /** * Deletes this item. * Note on the funny name: for reasons of historical compatibility, this URL is {@code /doDelete} * since it predates {@code <l:confirmationLink>}. {@code /delete} goes to a Jelly page * which should now be unused by core but is left in case plugins are still using it. */ @RequirePOST public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException { delete(); if (req == null || rsp == null) { // CLI return; } List<Ancestor> ancestors = req.getAncestors(); ListIterator<Ancestor> it = ancestors.listIterator(ancestors.size()); String url = getParent().getUrl(); // fallback but we ought to get to Jenkins.instance at the root while (it.hasPrevious()) { Object a = it.previous().getObject(); if (a instanceof View) { url = ((View) a).getUrl(); break; } else if (a instanceof ViewGroup && a != this) { url = ((ViewGroup) a).getUrl(); break; } } rsp.sendRedirect2(req.getContextPath() + '/' + url); } public void delete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { try { doDoDelete(req,rsp); } catch (InterruptedException e) { // TODO: allow this in Stapler throw new ServletException(e); } } /** * Deletes this item. * * <p> * Any exception indicates the deletion has failed, but {@link AbortException} would prevent the caller * from showing the stack trace. This */ public void delete() throws IOException, InterruptedException { checkPermission(DELETE); synchronized (this) { // could just make performDelete synchronized but overriders might not honor that performDelete(); } // JENKINS-19446: leave synch block, but JENKINS-22001: still notify synchronously getParent().onDeleted(AbstractItem.this); Jenkins.getInstance().rebuildDependencyGraphAsync(); } /** * Does the real job of deleting the item. */ protected void performDelete() throws IOException, InterruptedException { getConfigFile().delete(); Util.deleteRecursive(getRootDir()); } /** * Accepts <tt>config.xml</tt> submission, as well as serve it. */ @WebMethod(name = "config.xml") public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException { if (req.getMethod().equals("GET")) { // read rsp.setContentType("application/xml"); writeConfigDotXml(rsp.getOutputStream()); return; } if (req.getMethod().equals("POST")) { // submission updateByXml((Source)new StreamSource(req.getReader())); return; } // huh? rsp.sendError(SC_BAD_REQUEST); } static final Pattern SECRET_PATTERN = Pattern.compile(">(" + Secret.ENCRYPTED_VALUE_PATTERN + ")<"); /** * Writes {@code config.xml} to the specified output stream. * The user must have at least {@link #EXTENDED_READ}. * If he lacks {@link #CONFIGURE}, then any {@link Secret}s detected will be masked out. */ @Restricted(NoExternalUse.class) public void writeConfigDotXml(OutputStream os) throws IOException { checkPermission(EXTENDED_READ); XmlFile configFile = getConfigFile(); if (hasPermission(CONFIGURE)) { IOUtils.copy(configFile.getFile(), os); } else { String encoding = configFile.sniffEncoding(); String xml = FileUtils.readFileToString(configFile.getFile(), encoding); Matcher matcher = SECRET_PATTERN.matcher(xml); StringBuffer cleanXml = new StringBuffer(); while (matcher.find()) { if (Secret.decrypt(matcher.group(1)) != null) { matcher.appendReplacement(cleanXml, ">********<"); } } matcher.appendTail(cleanXml); org.apache.commons.io.IOUtils.write(cleanXml.toString(), os, encoding); } } /** * @deprecated as of 1.473 * Use {@link #updateByXml(Source)} */ @Deprecated public void updateByXml(StreamSource source) throws IOException { updateByXml((Source)source); } /** * Updates an Item by its XML definition. * @param source source of the Item's new definition. * The source should be either a <code>StreamSource</code> or a <code>SAXSource</code>, other * sources may not be handled. * @since 1.473 */ public void updateByXml(Source source) throws IOException { checkPermission(CONFIGURE); XmlFile configXmlFile = getConfigFile(); final AtomicFileWriter out = new AtomicFileWriter(configXmlFile.getFile()); try { try { XMLUtils.safeTransform(source, new StreamResult(out)); out.close(); } catch (TransformerException e) { throw new IOException("Failed to persist config.xml", e); } catch (SAXException e) { throw new IOException("Failed to persist config.xml", e); } // try to reflect the changes by reloading Object o = new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(this); if (o!=this) { // ensure that we've got the same job type. extending this code to support updating // to different job type requires destroying & creating a new job type throw new IOException("Expecting "+this.getClass()+" but got "+o.getClass()+" instead"); } Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<Void,IOException>() { @Override public Void call() throws IOException { onLoad(getParent(), getRootDir().getName()); return null; } }); Jenkins.getInstance().rebuildDependencyGraphAsync(); // if everything went well, commit this new version out.commit(); SaveableListener.fireOnChange(this, getConfigFile()); } finally { out.abort(); // don't leave anything behind } } /** * Reloads this job from the disk. * * Exposed through CLI as well. * * TODO: think about exposing this to UI * * @since 1.556 */ @CLIMethod(name="reload-job") @RequirePOST public void doReload() throws IOException { checkPermission(CONFIGURE); // try to reflect the changes by reloading getConfigFile().unmarshal(this); Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<Void, IOException>() { @Override public Void call() throws IOException { onLoad(getParent(), getRootDir().getName()); return null; } }); Jenkins.getInstance().rebuildDependencyGraphAsync(); SaveableListener.fireOnChange(this, getConfigFile()); } /* (non-Javadoc) * @see hudson.model.AbstractModelObject#getSearchName() */ @Override public String getSearchName() { // the search name of abstract items should be the name and not display name. // this will make suggestions use the names and not the display name // so that the links will 302 directly to the thing the user was finding return getName(); } @Override public String toString() { return super.toString() + '[' + (parent != null ? getFullName() : "?/" + name) + ']'; } /** * Used for CLI binding. */ @CLIResolver public static AbstractItem resolveForCLI( @Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException { // TODO can this (and its pseudo-override in AbstractProject) share code with GenericItemOptionHandler, used for explicit CLICommand’s rather than CLIMethod’s? AbstractItem item = Jenkins.getInstance().getItemByFullName(name, AbstractItem.class); if (item==null) throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName())); return item; } /** * Replaceable pronoun of that points to a job. Defaults to "Job"/"Project" depending on the context. */ public static final Message<AbstractItem> PRONOUN = new Message<AbstractItem>(); }
./CrossVul/dataset_final_sorted/CWE-269/java/good_3047_0
crossvul-java_data_good_3047_1
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc. * * 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.model; import hudson.Util; import hudson.XmlFile; import hudson.model.listeners.ItemListener; import hudson.security.AccessControlled; import hudson.util.CopyOnWriteMap; import hudson.util.Function1; import hudson.util.Secret; import jenkins.model.Jenkins; import jenkins.util.xml.XMLUtils; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import jenkins.security.NotReallyRoleSensitiveCallable; import org.acegisecurity.AccessDeniedException; import org.xml.sax.SAXException; /** * Defines a bunch of static methods to be used as a "mix-in" for {@link ItemGroup} * implementations. Not meant for a consumption from outside {@link ItemGroup}s. * * @author Kohsuke Kawaguchi * @see ViewGroupMixIn */ public abstract class ItemGroupMixIn { /** * {@link ItemGroup} for which we are working. */ private final ItemGroup parent; private final AccessControlled acl; protected ItemGroupMixIn(ItemGroup parent, AccessControlled acl) { this.parent = parent; this.acl = acl; } /* * Callback methods to be implemented by the ItemGroup implementation. */ /** * Adds a newly created item to the parent. */ protected abstract void add(TopLevelItem item); /** * Assigns the root directory for a prospective item. */ protected abstract File getRootDirFor(String name); /* * The rest is the methods that provide meat. */ /** * Loads all the child {@link Item}s. * * @param modulesDir * Directory that contains sub-directories for each child item. */ public static <K,V extends Item> Map<K,V> loadChildren(ItemGroup parent, File modulesDir, Function1<? extends K,? super V> key) { modulesDir.mkdirs(); // make sure it exists File[] subdirs = modulesDir.listFiles(new FileFilter() { public boolean accept(File child) { return child.isDirectory(); } }); CopyOnWriteMap.Tree<K,V> configurations = new CopyOnWriteMap.Tree<K,V>(); for (File subdir : subdirs) { try { // Try to retain the identity of an existing child object if we can. V item = (V) parent.getItem(subdir.getName()); if (item == null) { XmlFile xmlFile = Items.getConfigFile(subdir); if (xmlFile.exists()) { item = (V) Items.load(parent, subdir); } else { Logger.getLogger(ItemGroupMixIn.class.getName()).log(Level.WARNING, "could not find file " + xmlFile.getFile()); continue; } } else { item.onLoad(parent, subdir.getName()); } configurations.put(key.call(item), item); } catch (Exception e) { Logger.getLogger(ItemGroupMixIn.class.getName()).log(Level.WARNING, "could not load " + subdir, e); } } return configurations; } /** * {@link Item} -> name function. */ public static final Function1<String,Item> KEYED_BY_NAME = new Function1<String, Item>() { public String call(Item item) { return item.getName(); } }; /** * Creates a {@link TopLevelItem} from the submission of the '/lib/hudson/newFromList/formList' * or throws an exception if it fails. */ public synchronized TopLevelItem createTopLevelItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { acl.checkPermission(Item.CREATE); TopLevelItem result; String requestContentType = req.getContentType(); if(requestContentType==null) throw new Failure("No Content-Type header set"); boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml"); String name = req.getParameter("name"); if(name==null) throw new Failure("Query parameter 'name' is required"); {// check if the name looks good Jenkins.checkGoodName(name); name = name.trim(); if(parent.getItem(name)!=null) throw new Failure(Messages.Hudson_JobAlreadyExists(name)); } String mode = req.getParameter("mode"); if(mode!=null && mode.equals("copy")) { String from = req.getParameter("from"); // resolve a name to Item Item src = null; if (!from.startsWith("/")) src = parent.getItem(from); if (src==null) src = Jenkins.getInstance().getItemByFullName(from); if(src==null) { if(Util.fixEmpty(from)==null) throw new Failure("Specify which job to copy"); else throw new Failure("No such job: "+from); } if (!(src instanceof TopLevelItem)) throw new Failure(from+" cannot be copied"); result = copy((TopLevelItem) src,name); } else { if(isXmlSubmission) { result = createProjectFromXML(name, req.getInputStream()); rsp.setStatus(HttpServletResponse.SC_OK); return result; } else { if(mode==null) throw new Failure("No mode given"); TopLevelItemDescriptor descriptor = Items.all().findByName(mode); if (descriptor == null) { throw new Failure("No item type ‘" + mode + "’ is known"); } descriptor.checkApplicableIn(parent); acl.getACL().checkCreatePermission(parent, descriptor); // create empty job and redirect to the project config screen result = createProject(descriptor, name, true); } } rsp.sendRedirect2(redirectAfterCreateItem(req, result)); return result; } /** * Computes the redirection target URL for the newly created {@link TopLevelItem}. */ protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException { return req.getContextPath()+'/'+result.getUrl()+"configure"; } /** * Copies an existing {@link TopLevelItem} to a new name. */ @SuppressWarnings({"unchecked"}) public synchronized <T extends TopLevelItem> T copy(T src, String name) throws IOException { acl.checkPermission(Item.CREATE); src.checkPermission(Item.EXTENDED_READ); XmlFile srcConfigFile = Items.getConfigFile(src); if (!src.hasPermission(Item.CONFIGURE)) { Matcher matcher = AbstractItem.SECRET_PATTERN.matcher(srcConfigFile.asString()); while (matcher.find()) { if (Secret.decrypt(matcher.group(1)) != null) { // AccessDeniedException2 does not permit a custom message, and anyway redirecting the user to the login screen is obviously pointless. throw new AccessDeniedException(Messages.ItemGroupMixIn_may_not_copy_as_it_contains_secrets_and_(src.getFullName(), Jenkins.getAuthentication().getName(), Item.PERMISSIONS.title, Item.EXTENDED_READ.name, Item.CONFIGURE.name)); } } } src.getDescriptor().checkApplicableIn(parent); acl.getACL().checkCreatePermission(parent, src.getDescriptor()); T result = (T)createProject(src.getDescriptor(),name,false); // copy config Util.copyFile(srcConfigFile.getFile(), Items.getConfigFile(result).getFile()); // reload from the new config final File rootDir = result.getRootDir(); result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<T,IOException>() { @Override public T call() throws IOException { return (T) Items.load(parent, rootDir); } }); result.onCopiedFrom(src); add(result); ItemListener.fireOnCopied(src,result); Jenkins.getInstance().rebuildDependencyGraphAsync(); return result; } public synchronized TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { acl.checkPermission(Item.CREATE); Jenkins.getInstance().getProjectNamingStrategy().checkName(name); Items.verifyItemDoesNotAlreadyExist(parent, name, null); // place it as config.xml File configXml = Items.getConfigFile(getRootDirFor(name)).getFile(); final File dir = configXml.getParentFile(); dir.mkdirs(); boolean success = false; try { XMLUtils.safeTransform((Source)new StreamSource(xml), new StreamResult(configXml)); // load it TopLevelItem result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<TopLevelItem,IOException>() { @Override public TopLevelItem call() throws IOException { return (TopLevelItem) Items.load(parent, dir); } }); success = acl.getACL().hasCreatePermission(Jenkins.getAuthentication(), parent, result.getDescriptor()) && result.getDescriptor().isApplicableIn(parent); add(result); ItemListener.fireOnCreated(result); Jenkins.getInstance().rebuildDependencyGraphAsync(); return result; } catch (TransformerException e) { success = false; throw new IOException("Failed to persist config.xml", e); } catch (SAXException e) { success = false; throw new IOException("Failed to persist config.xml", e); } catch (IOException e) { success = false; throw e; } catch (RuntimeException e) { success = false; throw e; } finally { if (!success) { // if anything fails, delete the config file to avoid further confusion Util.deleteRecursive(dir); } } } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException { acl.checkPermission(Item.CREATE); type.checkApplicableIn(parent); acl.getACL().checkCreatePermission(parent, type); Jenkins.getInstance().getProjectNamingStrategy().checkName(name); Items.verifyItemDoesNotAlreadyExist(parent, name, null); TopLevelItem item = type.newInstance(parent, name); try { callOnCreatedFromScratch(item); } catch (AbstractMethodError e) { // ignore this error. Must be older plugin that doesn't have this method } item.save(); add(item); Jenkins.getInstance().rebuildDependencyGraphAsync(); if (notify) ItemListener.fireOnCreated(item); return item; } /** * Pointless wrapper to avoid HotSpot problem. See JENKINS-5756 */ private void callOnCreatedFromScratch(TopLevelItem item) { item.onCreatedFromScratch(); } }
./CrossVul/dataset_final_sorted/CWE-269/java/good_3047_1
crossvul-java_data_bad_3047_0
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Daniel Dyer, Tom Huybrechts, Yahoo!, Inc. * * 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.model; import com.infradna.tool.bridge_method_injector.WithBridgeMethods; import hudson.AbortException; import hudson.XmlFile; import hudson.Util; import hudson.Functions; import hudson.BulkChange; import hudson.cli.declarative.CLIMethod; import hudson.cli.declarative.CLIResolver; import hudson.model.listeners.ItemListener; import hudson.model.listeners.SaveableListener; import hudson.security.AccessControlled; import hudson.security.Permission; import hudson.security.ACL; import hudson.util.AlternativeUiTextProvider; import hudson.util.AlternativeUiTextProvider.Message; import hudson.util.AtomicFileWriter; import hudson.util.IOUtils; import hudson.util.Secret; import jenkins.model.DirectlyModifiableTopLevelItemGroup; import jenkins.model.Jenkins; import jenkins.security.NotReallyRoleSensitiveCallable; import org.acegisecurity.Authentication; import jenkins.util.xml.XMLUtils; import org.apache.tools.ant.taskdefs.Copy; import org.apache.tools.ant.types.FileSet; import org.kohsuke.stapler.WebMethod; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.List; import java.util.ListIterator; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nonnull; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.HttpDeletable; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.stapler.interceptor.RequirePOST; import org.xml.sax.SAXException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import org.apache.commons.io.FileUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.Ancestor; /** * Partial default implementation of {@link Item}. * * @author Kohsuke Kawaguchi */ // Item doesn't necessarily have to be Actionable, but // Java doesn't let multiple inheritance. @ExportedBean public abstract class AbstractItem extends Actionable implements Item, HttpDeletable, AccessControlled, DescriptorByNameOwner { private static final Logger LOGGER = Logger.getLogger(AbstractItem.class.getName()); /** * Project name. */ protected /*final*/ transient String name; /** * Project description. Can be HTML. */ protected volatile String description; private transient ItemGroup parent; protected String displayName; protected AbstractItem(ItemGroup parent, String name) { this.parent = parent; doSetName(name); } public void onCreatedFromScratch() { // noop } @Exported(visibility=999) public String getName() { return name; } /** * Get the term used in the UI to represent this kind of * {@link Item}. Must start with a capital letter. */ public String getPronoun() { return AlternativeUiTextProvider.get(PRONOUN, this, Messages.AbstractItem_Pronoun()); } @Exported /** * @return The display name of this object, or if it is not set, the name * of the object. */ public String getDisplayName() { if(null!=displayName) { return displayName; } // if the displayName is not set, then return the name as we use to do return getName(); } @Exported /** * This is intended to be used by the Job configuration pages where * we want to return null if the display name is not set. * @return The display name of this object or null if the display name is not * set */ public String getDisplayNameOrNull() { return displayName; } /** * This method exists so that the Job configuration pages can use * getDisplayNameOrNull so that nothing is shown in the display name text * box if the display name is not set. * @param displayName * @throws IOException */ public void setDisplayNameOrNull(String displayName) throws IOException { setDisplayName(displayName); } public void setDisplayName(String displayName) throws IOException { this.displayName = Util.fixEmpty(displayName); save(); } public File getRootDir() { return getParent().getRootDirFor(this); } /** * This bridge method is to maintain binary compatibility with {@link TopLevelItem#getParent()}. */ @WithBridgeMethods(value=Jenkins.class,castRequired=true) @Override public @Nonnull ItemGroup getParent() { if (parent == null) { throw new IllegalStateException("no parent set on " + getClass().getName() + "[" + name + "]"); } return parent; } /** * Gets the project description HTML. */ @Exported public String getDescription() { return description; } /** * Sets the project description HTML. */ public void setDescription(String description) throws IOException { this.description = description; save(); ItemListener.fireOnUpdated(this); } /** * Just update {@link #name} without performing the rename operation, * which would involve copying files and etc. */ protected void doSetName(String name) { this.name = name; } /** * Renames this item. * Not all the Items need to support this operation, but if you decide to do so, * you can use this method. */ protected void renameTo(final String newName) throws IOException { // always synchronize from bigger objects first final ItemGroup parent = getParent(); String oldName = this.name; String oldFullName = getFullName(); synchronized (parent) { synchronized (this) { // sanity check if (newName == null) throw new IllegalArgumentException("New name is not given"); // noop? if (this.name.equals(newName)) return; // the test to see if the project already exists or not needs to be done in escalated privilege // to avoid overwriting ACL.impersonate(ACL.SYSTEM,new NotReallyRoleSensitiveCallable<Void,IOException>() { final Authentication user = Jenkins.getAuthentication(); @Override public Void call() throws IOException { Item existing = parent.getItem(newName); if (existing != null && existing!=AbstractItem.this) { if (existing.getACL().hasPermission(user,Item.DISCOVER)) // the look up is case insensitive, so we need "existing!=this" // to allow people to rename "Foo" to "foo", for example. // see http://www.nabble.com/error-on-renaming-project-tt18061629.html throw new IllegalArgumentException("Job " + newName + " already exists"); else { // can't think of any real way to hide this, but at least the error message could be vague. throw new IOException("Unable to rename to " + newName); } } return null; } }); File oldRoot = this.getRootDir(); doSetName(newName); File newRoot = this.getRootDir(); boolean success = false; try {// rename data files boolean interrupted = false; boolean renamed = false; // try to rename the job directory. // this may fail on Windows due to some other processes // accessing a file. // so retry few times before we fall back to copy. for (int retry = 0; retry < 5; retry++) { if (oldRoot.renameTo(newRoot)) { renamed = true; break; // succeeded } try { Thread.sleep(500); } catch (InterruptedException e) { // process the interruption later interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); if (!renamed) { // failed to rename. it must be that some lengthy // process is going on // to prevent a rename operation. So do a copy. Ideally // we'd like to // later delete the old copy, but we can't reliably do // so, as before the VM // shuts down there might be a new job created under the // old name. Copy cp = new Copy(); cp.setProject(new org.apache.tools.ant.Project()); cp.setTodir(newRoot); FileSet src = new FileSet(); src.setDir(oldRoot); cp.addFileset(src); cp.setOverwrite(true); cp.setPreserveLastModified(true); cp.setFailOnError(false); // keep going even if // there's an error cp.execute(); // try to delete as much as possible try { Util.deleteRecursive(oldRoot); } catch (IOException e) { // but ignore the error, since we expect that e.printStackTrace(); } } success = true; } finally { // if failed, back out the rename. if (!success) doSetName(oldName); } try { parent.onRenamed(this, oldName, newName); } catch (AbstractMethodError _) { // ignore } } } ItemListener.fireLocationChange(this, oldFullName); } /** * Notify this item it's been moved to another location, replaced by newItem (might be the same object, but not guaranteed). * This method is executed <em>after</em> the item root directory has been moved to it's new location. * <p> * Derived classes can override this method to add some specific behavior on move, but have to call parent method * so the item is actually setup within it's new parent. * * @see hudson.model.Items#move(AbstractItem, jenkins.model.DirectlyModifiableTopLevelItemGroup) */ public void movedTo(DirectlyModifiableTopLevelItemGroup destination, AbstractItem newItem, File destDir) throws IOException { newItem.onLoad(destination, name); } /** * Gets all the jobs that this {@link Item} contains as descendants. */ public abstract Collection<? extends Job> getAllJobs(); public final String getFullName() { String n = getParent().getFullName(); if(n.length()==0) return getName(); else return n+'/'+getName(); } public final String getFullDisplayName() { String n = getParent().getFullDisplayName(); if(n.length()==0) return getDisplayName(); else return n+" » "+getDisplayName(); } /** * Gets the display name of the current item relative to the given group. * * @since 1.515 * @param p the ItemGroup used as point of reference for the item * @return * String like "foo » bar" */ public String getRelativeDisplayNameFrom(ItemGroup p) { return Functions.getRelativeDisplayNameFrom(this, p); } /** * This method only exists to disambiguate {@link #getRelativeNameFrom(ItemGroup)} and {@link #getRelativeNameFrom(Item)} * @since 1.512 * @see #getRelativeNameFrom(ItemGroup) */ public String getRelativeNameFromGroup(ItemGroup p) { return getRelativeNameFrom(p); } /** * @param p * The ItemGroup instance used as context to evaluate the relative name of this AbstractItem * @return * The name of the current item, relative to p. * Nested ItemGroups are separated by / character. */ public String getRelativeNameFrom(ItemGroup p) { return Functions.getRelativeNameFrom(this, p); } public String getRelativeNameFrom(Item item) { return getRelativeNameFrom(item.getParent()); } /** * Called right after when a {@link Item} is loaded from disk. * This is an opportunity to do a post load processing. */ public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { this.parent = parent; doSetName(name); } /** * When a {@link Item} is copied from existing one, * the files are first copied on the file system, * then it will be loaded, then this method will be invoked * to perform any implementation-specific work. * * <p> * * * @param src * Item from which it's copied from. The same type as {@code this}. Never null. */ public void onCopiedFrom(Item src) { } public final String getUrl() { // try to stick to the current view if possible StaplerRequest req = Stapler.getCurrentRequest(); String shortUrl = getShortUrl(); String uri = req == null ? null : req.getRequestURI(); if (req != null) { String seed = Functions.getNearestAncestorUrl(req,this); LOGGER.log(Level.FINER, "seed={0} for {1} from {2}", new Object[] {seed, this, uri}); if(seed!=null) { // trim off the context path portion and leading '/', but add trailing '/' return seed.substring(req.getContextPath().length()+1)+'/'; } List<Ancestor> ancestors = req.getAncestors(); if (!ancestors.isEmpty()) { Ancestor last = ancestors.get(ancestors.size() - 1); if (last.getObject() instanceof View) { View view = (View) last.getObject(); if (view.getOwnerItemGroup() == getParent() && !view.isDefault()) { // Showing something inside a view, so should use that as the base URL. String base = last.getUrl().substring(req.getContextPath().length() + 1) + '/'; LOGGER.log(Level.FINER, "using {0}{1} for {2} from {3}", new Object[] {base, shortUrl, this, uri}); return base + shortUrl; } else { LOGGER.log(Level.FINER, "irrelevant {0} for {1} from {2}", new Object[] {view.getViewName(), this, uri}); } } else { LOGGER.log(Level.FINER, "inapplicable {0} for {1} from {2}", new Object[] {last.getObject(), this, uri}); } } else { LOGGER.log(Level.FINER, "no ancestors for {0} from {1}", new Object[] {this, uri}); } } else { LOGGER.log(Level.FINER, "no current request for {0}", this); } // otherwise compute the path normally String base = getParent().getUrl(); LOGGER.log(Level.FINER, "falling back to {0}{1} for {2} from {3}", new Object[] {base, shortUrl, this, uri}); return base + shortUrl; } public String getShortUrl() { String prefix = getParent().getUrlChildPrefix(); String subdir = Util.rawEncode(getName()); return prefix.equals(".") ? subdir + '/' : prefix + '/' + subdir + '/'; } public String getSearchUrl() { return getShortUrl(); } @Exported(visibility=999,name="url") public final String getAbsoluteUrl() { String r = Jenkins.getInstance().getRootUrl(); if(r==null) throw new IllegalStateException("Root URL isn't configured yet. Cannot compute absolute URL."); return Util.encode(r+getUrl()); } /** * Remote API access. */ public final Api getApi() { return new Api(this); } /** * Returns the {@link ACL} for this object. */ public ACL getACL() { return Jenkins.getInstance().getAuthorizationStrategy().getACL(this); } /** * Short for {@code getACL().checkPermission(p)} */ public void checkPermission(Permission p) { getACL().checkPermission(p); } /** * Short for {@code getACL().hasPermission(p)} */ public boolean hasPermission(Permission p) { return getACL().hasPermission(p); } /** * Save the settings to a file. */ public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } public final XmlFile getConfigFile() { return Items.getConfigFile(this); } public Descriptor getDescriptorByName(String className) { return Jenkins.getInstance().getDescriptorByName(className); } /** * Accepts the new description. */ public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { checkPermission(CONFIGURE); setDescription(req.getParameter("description")); rsp.sendRedirect("."); // go to the top page } /** * Deletes this item. * Note on the funny name: for reasons of historical compatibility, this URL is {@code /doDelete} * since it predates {@code <l:confirmationLink>}. {@code /delete} goes to a Jelly page * which should now be unused by core but is left in case plugins are still using it. */ @RequirePOST public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException { delete(); if (req == null || rsp == null) { // CLI return; } List<Ancestor> ancestors = req.getAncestors(); ListIterator<Ancestor> it = ancestors.listIterator(ancestors.size()); String url = getParent().getUrl(); // fallback but we ought to get to Jenkins.instance at the root while (it.hasPrevious()) { Object a = it.previous().getObject(); if (a instanceof View) { url = ((View) a).getUrl(); break; } else if (a instanceof ViewGroup && a != this) { url = ((ViewGroup) a).getUrl(); break; } } rsp.sendRedirect2(req.getContextPath() + '/' + url); } public void delete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { try { doDoDelete(req,rsp); } catch (InterruptedException e) { // TODO: allow this in Stapler throw new ServletException(e); } } /** * Deletes this item. * * <p> * Any exception indicates the deletion has failed, but {@link AbortException} would prevent the caller * from showing the stack trace. This */ public void delete() throws IOException, InterruptedException { checkPermission(DELETE); synchronized (this) { // could just make performDelete synchronized but overriders might not honor that performDelete(); } // JENKINS-19446: leave synch block, but JENKINS-22001: still notify synchronously getParent().onDeleted(AbstractItem.this); Jenkins.getInstance().rebuildDependencyGraphAsync(); } /** * Does the real job of deleting the item. */ protected void performDelete() throws IOException, InterruptedException { getConfigFile().delete(); Util.deleteRecursive(getRootDir()); } /** * Accepts <tt>config.xml</tt> submission, as well as serve it. */ @WebMethod(name = "config.xml") public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException { if (req.getMethod().equals("GET")) { // read rsp.setContentType("application/xml"); writeConfigDotXml(rsp.getOutputStream()); return; } if (req.getMethod().equals("POST")) { // submission updateByXml((Source)new StreamSource(req.getReader())); return; } // huh? rsp.sendError(SC_BAD_REQUEST); } static final Pattern SECRET_PATTERN = Pattern.compile(">(" + Secret.ENCRYPTED_VALUE_PATTERN + ")<"); /** * Writes {@code config.xml} to the specified output stream. * The user must have at least {@link #EXTENDED_READ}. * If he lacks {@link #CONFIGURE}, then any {@link Secret}s detected will be masked out. */ @Restricted(NoExternalUse.class) public void writeConfigDotXml(OutputStream os) throws IOException { checkPermission(EXTENDED_READ); XmlFile configFile = getConfigFile(); if (hasPermission(CONFIGURE)) { IOUtils.copy(configFile.getFile(), os); } else { String encoding = configFile.sniffEncoding(); String xml = FileUtils.readFileToString(configFile.getFile(), encoding); Matcher matcher = SECRET_PATTERN.matcher(xml); StringBuffer cleanXml = new StringBuffer(); while (matcher.find()) { if (Secret.decrypt(matcher.group(1)) != null) { matcher.appendReplacement(cleanXml, ">********<"); } } matcher.appendTail(cleanXml); org.apache.commons.io.IOUtils.write(cleanXml.toString(), os, encoding); } } /** * @deprecated as of 1.473 * Use {@link #updateByXml(Source)} */ @Deprecated public void updateByXml(StreamSource source) throws IOException { updateByXml((Source)source); } /** * Updates an Item by its XML definition. * @param source source of the Item's new definition. * The source should be either a <code>StreamSource</code> or a <code>SAXSource</code>, other * sources may not be handled. * @since 1.473 */ public void updateByXml(Source source) throws IOException { checkPermission(CONFIGURE); XmlFile configXmlFile = getConfigFile(); final AtomicFileWriter out = new AtomicFileWriter(configXmlFile.getFile()); try { try { XMLUtils.safeTransform(source, new StreamResult(out)); out.close(); } catch (TransformerException e) { throw new IOException("Failed to persist config.xml", e); } catch (SAXException e) { throw new IOException("Failed to persist config.xml", e); } // try to reflect the changes by reloading Object o = new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(this); if (o!=this) { // ensure that we've got the same job type. extending this code to support updating // to different job type requires destroying & creating a new job type throw new IOException("Expecting "+this.getClass()+" but got "+o.getClass()+" instead"); } Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<Void,IOException>() { @Override public Void call() throws IOException { onLoad(getParent(), getRootDir().getName()); return null; } }); Jenkins.getInstance().rebuildDependencyGraphAsync(); // if everything went well, commit this new version out.commit(); SaveableListener.fireOnChange(this, getConfigFile()); } finally { out.abort(); // don't leave anything behind } } /** * Reloads this job from the disk. * * Exposed through CLI as well. * * TODO: think about exposing this to UI * * @since 1.556 */ @CLIMethod(name="reload-job") @RequirePOST public void doReload() throws IOException { checkPermission(CONFIGURE); // try to reflect the changes by reloading getConfigFile().unmarshal(this); Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<Void, IOException>() { @Override public Void call() throws IOException { onLoad(getParent(), getRootDir().getName()); return null; } }); Jenkins.getInstance().rebuildDependencyGraphAsync(); SaveableListener.fireOnChange(this, getConfigFile()); } /* (non-Javadoc) * @see hudson.model.AbstractModelObject#getSearchName() */ @Override public String getSearchName() { // the search name of abstract items should be the name and not display name. // this will make suggestions use the names and not the display name // so that the links will 302 directly to the thing the user was finding return getName(); } @Override public String toString() { return super.toString() + '[' + (parent != null ? getFullName() : "?/" + name) + ']'; } /** * Used for CLI binding. */ @CLIResolver public static AbstractItem resolveForCLI( @Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException { // TODO can this (and its pseudo-override in AbstractProject) share code with GenericItemOptionHandler, used for explicit CLICommand’s rather than CLIMethod’s? AbstractItem item = Jenkins.getInstance().getItemByFullName(name, AbstractItem.class); if (item==null) throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName())); return item; } /** * Replaceable pronoun of that points to a job. Defaults to "Job"/"Project" depending on the context. */ public static final Message<AbstractItem> PRONOUN = new Message<AbstractItem>(); }
./CrossVul/dataset_final_sorted/CWE-269/java/bad_3047_0
crossvul-java_data_bad_3057_0
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe, * Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc., * Yahoo!, Inc. * * 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 jenkins.model; import antlr.ANTLRException; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.inject.Injector; import com.thoughtworks.xstream.XStream; import hudson.BulkChange; import hudson.DNSMultiCast; import hudson.DescriptorExtensionList; import hudson.Extension; import hudson.ExtensionComponent; import hudson.ExtensionFinder; import hudson.ExtensionList; import hudson.ExtensionPoint; import hudson.FilePath; import hudson.Functions; import hudson.Launcher; import hudson.Launcher.LocalLauncher; import hudson.LocalPluginManager; import hudson.Lookup; import hudson.Plugin; import hudson.PluginManager; import hudson.PluginWrapper; import hudson.ProxyConfiguration; import hudson.TcpSlaveAgentListener; import hudson.UDPBroadcastThread; import hudson.Util; import hudson.WebAppMain; import hudson.XmlFile; import hudson.cli.declarative.CLIMethod; import hudson.cli.declarative.CLIResolver; import hudson.init.InitMilestone; import hudson.init.InitStrategy; import hudson.init.TerminatorFinder; import hudson.lifecycle.Lifecycle; import hudson.lifecycle.RestartNotSupportedException; import hudson.logging.LogRecorderManager; import hudson.markup.EscapedMarkupFormatter; import hudson.markup.MarkupFormatter; import hudson.model.AbstractCIBase; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.AdministrativeMonitor; import hudson.model.AllView; import hudson.model.Api; import hudson.model.Computer; import hudson.model.ComputerSet; import hudson.model.DependencyGraph; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Descriptor.FormException; import hudson.model.DescriptorByNameOwner; import hudson.model.DirectoryBrowserSupport; import hudson.model.Failure; import hudson.model.Fingerprint; import hudson.model.FingerprintCleanupThread; import hudson.model.FingerprintMap; import hudson.model.Hudson; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.ItemGroupMixIn; import hudson.model.Items; import hudson.model.JDK; import hudson.model.Job; import hudson.model.JobPropertyDescriptor; import hudson.model.Label; import hudson.model.ListView; import hudson.model.LoadBalancer; import hudson.model.LoadStatistics; import hudson.model.ManagementLink; import hudson.model.Messages; import hudson.model.ModifiableViewGroup; import hudson.model.NoFingerprintMatch; import hudson.model.Node; import hudson.model.OverallLoadStatistics; import hudson.model.PaneStatusProperties; import hudson.model.Project; import hudson.model.Queue; import hudson.model.Queue.FlyweightTask; import hudson.model.RestartListener; import hudson.model.RootAction; import hudson.model.Slave; import hudson.model.TaskListener; import hudson.model.TopLevelItem; import hudson.model.TopLevelItemDescriptor; import hudson.model.UnprotectedRootAction; import hudson.model.UpdateCenter; import hudson.model.User; import hudson.model.View; import hudson.model.ViewGroupMixIn; import hudson.model.WorkspaceCleanupThread; import hudson.model.labels.LabelAtom; import hudson.model.listeners.ItemListener; import hudson.model.listeners.SCMListener; import hudson.model.listeners.SaveableListener; import hudson.remoting.Callable; import hudson.remoting.LocalChannel; import hudson.remoting.VirtualChannel; import hudson.scm.RepositoryBrowser; import hudson.scm.SCM; import hudson.search.CollectionSearchIndex; import hudson.search.SearchIndexBuilder; import hudson.search.SearchItem; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.security.AuthorizationStrategy; import hudson.security.BasicAuthenticationFilter; import hudson.security.FederatedLoginService; import hudson.security.FullControlOnceLoggedInAuthorizationStrategy; import hudson.security.HudsonFilter; import hudson.security.LegacyAuthorizationStrategy; import hudson.security.LegacySecurityRealm; import hudson.security.Permission; import hudson.security.PermissionGroup; import hudson.security.PermissionScope; import hudson.security.SecurityMode; import hudson.security.SecurityRealm; import hudson.security.csrf.CrumbIssuer; import hudson.slaves.Cloud; import hudson.slaves.ComputerListener; import hudson.slaves.DumbSlave; import hudson.slaves.EphemeralNode; import hudson.slaves.NodeDescriptor; import hudson.slaves.NodeList; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.slaves.NodeProvisioner; import hudson.slaves.OfflineCause; import hudson.slaves.RetentionStrategy; import hudson.tasks.BuildWrapper; import hudson.tasks.Builder; import hudson.tasks.Publisher; import hudson.triggers.SafeTimerTask; import hudson.triggers.Trigger; import hudson.triggers.TriggerDescriptor; import hudson.util.AdministrativeError; import hudson.util.CaseInsensitiveComparator; import hudson.util.ClockDifference; import hudson.util.CopyOnWriteList; import hudson.util.CopyOnWriteMap; import hudson.util.DaemonThreadFactory; import hudson.util.DescribableList; import hudson.util.FormApply; import hudson.util.FormValidation; import hudson.util.Futures; import hudson.util.HudsonIsLoading; import hudson.util.HudsonIsRestarting; import hudson.util.IOUtils; import hudson.util.Iterators; import hudson.util.JenkinsReloadFailed; import hudson.util.Memoizer; import hudson.util.MultipartFormDataParser; import hudson.util.NamingThreadFactory; import hudson.util.RemotingDiagnostics; import hudson.util.RemotingDiagnostics.HeapDump; import hudson.util.TextFile; import hudson.util.TimeUnit2; import hudson.util.VersionNumber; import hudson.util.XStream2; import hudson.views.DefaultMyViewsTabBar; import hudson.views.DefaultViewsTabBar; import hudson.views.MyViewsTabBar; import hudson.views.ViewsTabBar; import hudson.widgets.Widget; import jenkins.ExtensionComponentSet; import jenkins.ExtensionRefreshException; import jenkins.InitReactorRunner; import jenkins.model.ProjectNamingStrategy.DefaultProjectNamingStrategy; import jenkins.security.ConfidentialKey; import jenkins.security.ConfidentialStore; import jenkins.security.SecurityListener; import jenkins.security.MasterToSlaveCallable; import jenkins.slaves.WorkspaceLocator; import jenkins.util.Timer; import jenkins.util.io.FileBoolean; import net.sf.json.JSONObject; import org.acegisecurity.AccessDeniedException; import org.acegisecurity.AcegiSecurityException; import org.acegisecurity.Authentication; import org.acegisecurity.GrantedAuthority; import org.acegisecurity.GrantedAuthorityImpl; import org.acegisecurity.context.SecurityContextHolder; import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken; import org.acegisecurity.ui.AbstractProcessingFilter; import org.apache.commons.jelly.JellyException; import org.apache.commons.jelly.Script; import org.apache.commons.logging.LogFactory; import org.jvnet.hudson.reactor.Executable; import org.jvnet.hudson.reactor.Reactor; import org.jvnet.hudson.reactor.ReactorException; import org.jvnet.hudson.reactor.Task; import org.jvnet.hudson.reactor.TaskBuilder; import org.jvnet.hudson.reactor.TaskGraphBuilder; import org.jvnet.hudson.reactor.TaskGraphBuilder.Handle; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.MetaClass; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerFallback; import org.kohsuke.stapler.StaplerProxy; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.WebApp; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import org.kohsuke.stapler.framework.adjunct.AdjunctManager; import org.kohsuke.stapler.interceptor.RequirePOST; import org.kohsuke.stapler.jelly.JellyClassLoaderTearOff; import org.kohsuke.stapler.jelly.JellyRequestDispatcher; import org.xml.sax.InputSource; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.crypto.SecretKey; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.BindException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import static hudson.Util.*; import static hudson.init.InitMilestone.*; import hudson.util.LogTaskListener; import static java.util.logging.Level.*; import static javax.servlet.http.HttpServletResponse.*; import org.kohsuke.stapler.WebMethod; /** * Root object of the system. * * @author Kohsuke Kawaguchi */ @ExportedBean public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLevelItemGroup, StaplerProxy, StaplerFallback, ModifiableViewGroup, AccessControlled, DescriptorByNameOwner, ModelObjectWithContextMenu, ModelObjectWithChildren { private transient final Queue queue; /** * Stores various objects scoped to {@link Jenkins}. */ public transient final Lookup lookup = new Lookup(); /** * We update this field to the current version of Jenkins whenever we save {@code config.xml}. * This can be used to detect when an upgrade happens from one version to next. * * <p> * Since this field is introduced starting 1.301, "1.0" is used to represent every version * up to 1.300. This value may also include non-standard versions like "1.301-SNAPSHOT" or * "?", etc., so parsing needs to be done with a care. * * @since 1.301 */ // this field needs to be at the very top so that other components can look at this value even during unmarshalling private String version = "1.0"; /** * Number of executors of the master node. */ private int numExecutors = 2; /** * Job allocation strategy. */ private Mode mode = Mode.NORMAL; /** * False to enable anyone to do anything. * Left as a field so that we can still read old data that uses this flag. * * @see #authorizationStrategy * @see #securityRealm */ private Boolean useSecurity; /** * Controls how the * <a href="http://en.wikipedia.org/wiki/Authorization">authorization</a> * is handled in Jenkins. * <p> * This ultimately controls who has access to what. * * Never null. */ private volatile AuthorizationStrategy authorizationStrategy = AuthorizationStrategy.UNSECURED; /** * Controls a part of the * <a href="http://en.wikipedia.org/wiki/Authentication">authentication</a> * handling in Jenkins. * <p> * Intuitively, this corresponds to the user database. * * See {@link HudsonFilter} for the concrete authentication protocol. * * Never null. Always use {@link #setSecurityRealm(SecurityRealm)} to * update this field. * * @see #getSecurity() * @see #setSecurityRealm(SecurityRealm) */ private volatile SecurityRealm securityRealm = SecurityRealm.NO_AUTHENTICATION; /** * Disables the remember me on this computer option in the standard login screen. * * @since 1.534 */ private volatile boolean disableRememberMe; /** * The project naming strategy defines/restricts the names which can be given to a project/job. e.g. does the name have to follow a naming convention? */ private ProjectNamingStrategy projectNamingStrategy = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; /** * Root directory for the workspaces. * This value will be variable-expanded as per {@link #expandVariablesForDirectory}. * @see #getWorkspaceFor(TopLevelItem) */ private String workspaceDir = "${ITEM_ROOTDIR}/"+WORKSPACE_DIRNAME; /** * Root directory for the builds. * This value will be variable-expanded as per {@link #expandVariablesForDirectory}. * @see #getBuildDirFor(Job) */ private String buildsDir = "${ITEM_ROOTDIR}/builds"; /** * Message displayed in the top page. */ private String systemMessage; private MarkupFormatter markupFormatter; /** * Root directory of the system. */ public transient final File root; /** * Where are we in the initialization? */ private transient volatile InitMilestone initLevel = InitMilestone.STARTED; /** * All {@link Item}s keyed by their {@link Item#getName() name}s. */ /*package*/ transient final Map<String,TopLevelItem> items = new CopyOnWriteMap.Tree<String,TopLevelItem>(CaseInsensitiveComparator.INSTANCE); /** * The sole instance. */ private static Jenkins theInstance; private transient volatile boolean isQuietingDown; private transient volatile boolean terminating; private List<JDK> jdks = new ArrayList<JDK>(); private transient volatile DependencyGraph dependencyGraph; private final transient AtomicBoolean dependencyGraphDirty = new AtomicBoolean(); /** * Currently active Views tab bar. */ private volatile ViewsTabBar viewsTabBar = new DefaultViewsTabBar(); /** * Currently active My Views tab bar. */ private volatile MyViewsTabBar myViewsTabBar = new DefaultMyViewsTabBar(); /** * All {@link ExtensionList} keyed by their {@link ExtensionList#extensionType}. */ private transient final Memoizer<Class,ExtensionList> extensionLists = new Memoizer<Class,ExtensionList>() { public ExtensionList compute(Class key) { return ExtensionList.create(Jenkins.this,key); } }; /** * All {@link DescriptorExtensionList} keyed by their {@link DescriptorExtensionList#describableType}. */ private transient final Memoizer<Class,DescriptorExtensionList> descriptorLists = new Memoizer<Class,DescriptorExtensionList>() { public DescriptorExtensionList compute(Class key) { return DescriptorExtensionList.createDescriptorList(Jenkins.this,key); } }; /** * {@link Computer}s in this Jenkins system. Read-only. */ protected transient final Map<Node,Computer> computers = new CopyOnWriteMap.Hash<Node,Computer>(); /** * Active {@link Cloud}s. */ public final Hudson.CloudList clouds = new Hudson.CloudList(this); public static class CloudList extends DescribableList<Cloud,Descriptor<Cloud>> { public CloudList(Jenkins h) { super(h); } public CloudList() {// needed for XStream deserialization } public Cloud getByName(String name) { for (Cloud c : this) if (c.name.equals(name)) return c; return null; } @Override protected void onModified() throws IOException { super.onModified(); Jenkins.getInstance().trimLabels(); } } /** * Legacy store of the set of installed cluster nodes. * @deprecated in favour of {@link Nodes} */ @Deprecated protected transient volatile NodeList slaves; /** * The holder of the set of installed cluster nodes. * * @since 1.607 */ private transient final Nodes nodes = new Nodes(this); /** * Quiet period. * * This is {@link Integer} so that we can initialize it to '5' for upgrading users. */ /*package*/ Integer quietPeriod; /** * Global default for {@link AbstractProject#getScmCheckoutRetryCount()} */ /*package*/ int scmCheckoutRetryCount; /** * {@link View}s. */ private final CopyOnWriteArrayList<View> views = new CopyOnWriteArrayList<View>(); /** * Name of the primary view. * <p> * Start with null, so that we can upgrade pre-1.269 data well. * @since 1.269 */ private volatile String primaryView; private transient final ViewGroupMixIn viewGroupMixIn = new ViewGroupMixIn(this) { protected List<View> views() { return views; } protected String primaryView() { return primaryView; } protected void primaryView(String name) { primaryView=name; } }; private transient final FingerprintMap fingerprintMap = new FingerprintMap(); /** * Loaded plugins. */ public transient final PluginManager pluginManager; public transient volatile TcpSlaveAgentListener tcpSlaveAgentListener; private transient UDPBroadcastThread udpBroadcastThread; private transient DNSMultiCast dnsMultiCast; /** * List of registered {@link SCMListener}s. */ private transient final CopyOnWriteList<SCMListener> scmListeners = new CopyOnWriteList<SCMListener>(); /** * TCP slave agent port. * 0 for random, -1 to disable. */ private int slaveAgentPort =0; /** * Whitespace-separated labels assigned to the master as a {@link Node}. */ private String label=""; /** * {@link hudson.security.csrf.CrumbIssuer} */ private volatile CrumbIssuer crumbIssuer; /** * All labels known to Jenkins. This allows us to reuse the same label instances * as much as possible, even though that's not a strict requirement. */ private transient final ConcurrentHashMap<String,Label> labels = new ConcurrentHashMap<String,Label>(); /** * Load statistics of the entire system. * * This includes every executor and every job in the system. */ @Exported public transient final OverallLoadStatistics overallLoad = new OverallLoadStatistics(); /** * Load statistics of the free roaming jobs and slaves. * * This includes all executors on {@link hudson.model.Node.Mode#NORMAL} nodes and jobs that do not have any assigned nodes. * * @since 1.467 */ @Exported public transient final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics(); /** * {@link NodeProvisioner} that reacts to {@link #unlabeledLoad}. * @since 1.467 */ public transient final NodeProvisioner unlabeledNodeProvisioner = new NodeProvisioner(null,unlabeledLoad); /** * @deprecated as of 1.467 * Use {@link #unlabeledNodeProvisioner}. * This was broken because it was tracking all the executors in the system, but it was only tracking * free-roaming jobs in the queue. So {@link Cloud} fails to launch nodes when you have some exclusive * slaves and free-roaming jobs in the queue. */ @Restricted(NoExternalUse.class) @Deprecated public transient final NodeProvisioner overallNodeProvisioner = unlabeledNodeProvisioner; public transient final ServletContext servletContext; /** * Transient action list. Useful for adding navigation items to the navigation bar * on the left. */ private transient final List<Action> actions = new CopyOnWriteArrayList<Action>(); /** * List of master node properties */ private DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this); /** * List of global properties */ private DescribableList<NodeProperty<?>,NodePropertyDescriptor> globalNodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(this); /** * {@link AdministrativeMonitor}s installed on this system. * * @see AdministrativeMonitor */ public transient final List<AdministrativeMonitor> administrativeMonitors = getExtensionList(AdministrativeMonitor.class); /** * Widgets on Jenkins. */ private transient final List<Widget> widgets = getExtensionList(Widget.class); /** * {@link AdjunctManager} */ private transient final AdjunctManager adjuncts; /** * Code that handles {@link ItemGroup} work. */ private transient final ItemGroupMixIn itemGroupMixIn = new ItemGroupMixIn(this,this) { @Override protected void add(TopLevelItem item) { items.put(item.getName(),item); } @Override protected File getRootDirFor(String name) { return Jenkins.this.getRootDirFor(name); } }; /** * Hook for a test harness to intercept Jenkins.getInstance() * * Do not use in the production code as the signature may change. */ public interface JenkinsHolder { @CheckForNull Jenkins getInstance(); } static JenkinsHolder HOLDER = new JenkinsHolder() { public @CheckForNull Jenkins getInstance() { return theInstance; } }; /** * Gets the {@link Jenkins} singleton. * {@link #getInstance()} provides the unchecked versions of the method. * @return {@link Jenkins} instance * @throws IllegalStateException {@link Jenkins} has not been started, or was already shut down * @since 1.590 */ public static @Nonnull Jenkins getActiveInstance() throws IllegalStateException { Jenkins instance = HOLDER.getInstance(); if (instance == null) { throw new IllegalStateException("Jenkins has not been started, or was already shut down"); } return instance; } /** * Gets the {@link Jenkins} singleton. * {@link #getActiveInstance()} provides the checked versions of the method. * @return The instance. Null if the {@link Jenkins} instance has not been started, * or was already shut down */ @CLIResolver @CheckForNull public static Jenkins getInstance() { return HOLDER.getInstance(); } /** * Secret key generated once and used for a long time, beyond * container start/stop. Persisted outside <tt>config.xml</tt> to avoid * accidental exposure. */ private transient final String secretKey; private transient final UpdateCenter updateCenter = new UpdateCenter(); /** * True if the user opted out from the statistics tracking. We'll never send anything if this is true. */ private Boolean noUsageStatistics; /** * HTTP proxy configuration. */ public transient volatile ProxyConfiguration proxy; /** * Bound to "/log". */ private transient final LogRecorderManager log = new LogRecorderManager(); protected Jenkins(File root, ServletContext context) throws IOException, InterruptedException, ReactorException { this(root,context,null); } /** * @param pluginManager * If non-null, use existing plugin manager. create a new one. */ @edu.umd.cs.findbugs.annotations.SuppressWarnings({ "SC_START_IN_CTOR", // bug in FindBugs. It flags UDPBroadcastThread.start() call but that's for another class "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" // Trigger.timer }) protected Jenkins(File root, ServletContext context, PluginManager pluginManager) throws IOException, InterruptedException, ReactorException { long start = System.currentTimeMillis(); // As Jenkins is starting, grant this process full control ACL.impersonate(ACL.SYSTEM); try { this.root = root; this.servletContext = context; computeVersion(context); if(theInstance!=null) throw new IllegalStateException("second instance"); theInstance = this; if (!new File(root,"jobs").exists()) { // if this is a fresh install, use more modern default layout that's consistent with slaves workspaceDir = "${JENKINS_HOME}/workspace/${ITEM_FULLNAME}"; } // doing this early allows InitStrategy to set environment upfront final InitStrategy is = InitStrategy.get(Thread.currentThread().getContextClassLoader()); Trigger.timer = new java.util.Timer("Jenkins cron thread"); queue = new Queue(LoadBalancer.CONSISTENT_HASH); try { dependencyGraph = DependencyGraph.EMPTY; } catch (InternalError e) { if(e.getMessage().contains("window server")) { throw new Error("Looks like the server runs without X. Please specify -Djava.awt.headless=true as JVM option",e); } throw e; } // get or create the secret TextFile secretFile = new TextFile(new File(getRootDir(),"secret.key")); if(secretFile.exists()) { secretKey = secretFile.readTrim(); } else { SecureRandom sr = new SecureRandom(); byte[] random = new byte[32]; sr.nextBytes(random); secretKey = Util.toHexString(random); secretFile.write(secretKey); // this marker indicates that the secret.key is generated by the version of Jenkins post SECURITY-49. // this indicates that there's no need to rewrite secrets on disk new FileBoolean(new File(root,"secret.key.not-so-secret")).on(); } try { proxy = ProxyConfiguration.load(); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to load proxy configuration", e); } if (pluginManager==null) pluginManager = new LocalPluginManager(this); this.pluginManager = pluginManager; // JSON binding needs to be able to see all the classes from all the plugins WebApp.get(servletContext).setClassLoader(pluginManager.uberClassLoader); adjuncts = new AdjunctManager(servletContext, pluginManager.uberClassLoader,"adjuncts/"+SESSION_HASH, TimeUnit2.DAYS.toMillis(365)); // initialization consists of ... executeReactor( is, pluginManager.initTasks(is), // loading and preparing plugins loadTasks(), // load jobs InitMilestone.ordering() // forced ordering among key milestones ); if(KILL_AFTER_LOAD) System.exit(0); if(slaveAgentPort!=-1) { try { tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); } catch (BindException e) { new AdministrativeError(getClass().getName()+".tcpBind", "Failed to listen to incoming slave connection", "Failed to listen to incoming slave connection. <a href='configure'>Change the port number</a> to solve the problem.",e); } } else tcpSlaveAgentListener = null; if (UDPBroadcastThread.PORT != -1) { try { udpBroadcastThread = new UDPBroadcastThread(this); udpBroadcastThread.start(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to broadcast over UDP (use -Dhudson.udp=-1 to disable)", e); } } dnsMultiCast = new DNSMultiCast(this); Timer.get().scheduleAtFixedRate(new SafeTimerTask() { @Override protected void doRun() throws Exception { trimLabels(); } }, TimeUnit2.MINUTES.toMillis(5), TimeUnit2.MINUTES.toMillis(5), TimeUnit.MILLISECONDS); updateComputerList(); {// master is online now Computer c = toComputer(); if(c!=null) for (ComputerListener cl : ComputerListener.all()) cl.onOnline(c, new LogTaskListener(LOGGER, INFO)); } for (ItemListener l : ItemListener.all()) { long itemListenerStart = System.currentTimeMillis(); try { l.onLoaded(); } catch (RuntimeException x) { LOGGER.log(Level.WARNING, null, x); } if (LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for item listener %s startup", System.currentTimeMillis()-itemListenerStart,l.getClass().getName())); } if (LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for complete Jenkins startup", System.currentTimeMillis()-start)); } finally { SecurityContextHolder.clearContext(); } } /** * Executes a reactor. * * @param is * If non-null, this can be consulted for ignoring some tasks. Only used during the initialization of Jenkins. */ private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException { Reactor reactor = new Reactor(builders) { /** * Sets the thread name to the task for better diagnostics. */ @Override protected void runTask(Task task) throws Exception { if (is!=null && is.skipInitTask(task)) return; ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread String taskName = task.getDisplayName(); Thread t = Thread.currentThread(); String name = t.getName(); if (taskName !=null) t.setName(taskName); try { long start = System.currentTimeMillis(); super.runTask(task); if(LOG_STARTUP_PERFORMANCE) LOGGER.info(String.format("Took %dms for %s by %s", System.currentTimeMillis()-start, taskName, name)); } finally { t.setName(name); SecurityContextHolder.clearContext(); } } }; new InitReactorRunner() { @Override protected void onInitMilestoneAttained(InitMilestone milestone) { initLevel = milestone; } }.run(reactor); } public TcpSlaveAgentListener getTcpSlaveAgentListener() { return tcpSlaveAgentListener; } /** * Makes {@link AdjunctManager} URL-bound. * The dummy parameter allows us to use different URLs for the same adjunct, * for proper cache handling. */ public AdjunctManager getAdjuncts(String dummy) { return adjuncts; } @Exported public int getSlaveAgentPort() { return slaveAgentPort; } /** * @param port * 0 to indicate random available TCP port. -1 to disable this service. */ public void setSlaveAgentPort(int port) throws IOException { this.slaveAgentPort = port; // relaunch the agent if(tcpSlaveAgentListener==null) { if(slaveAgentPort!=-1) tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); } else { if(tcpSlaveAgentListener.configuredPort!=slaveAgentPort) { tcpSlaveAgentListener.shutdown(); tcpSlaveAgentListener = null; if(slaveAgentPort!=-1) tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); } } } public void setNodeName(String name) { throw new UnsupportedOperationException(); // not allowed } public String getNodeDescription() { return Messages.Hudson_NodeDescription(); } @Exported public String getDescription() { return systemMessage; } public PluginManager getPluginManager() { return pluginManager; } public UpdateCenter getUpdateCenter() { return updateCenter; } public boolean isUsageStatisticsCollected() { return noUsageStatistics==null || !noUsageStatistics; } public void setNoUsageStatistics(Boolean noUsageStatistics) throws IOException { this.noUsageStatistics = noUsageStatistics; save(); } public View.People getPeople() { return new View.People(this); } /** * @since 1.484 */ public View.AsynchPeople getAsynchPeople() { return new View.AsynchPeople(this); } /** * Does this {@link View} has any associated user information recorded? * @deprecated Potentially very expensive call; do not use from Jelly views. */ @Deprecated public boolean hasPeople() { return View.People.isApplicable(items.values()); } public Api getApi() { return new Api(this); } /** * Returns a secret key that survives across container start/stop. * <p> * This value is useful for implementing some of the security features. * * @deprecated * Due to the past security advisory, this value should not be used any more to protect sensitive information. * See {@link ConfidentialStore} and {@link ConfidentialKey} for how to store secrets. */ @Deprecated public String getSecretKey() { return secretKey; } /** * Gets {@linkplain #getSecretKey() the secret key} as a key for AES-128. * @since 1.308 * @deprecated * See {@link #getSecretKey()}. */ @Deprecated public SecretKey getSecretKeyAsAES128() { return Util.toAes128Key(secretKey); } /** * Returns the unique identifier of this Jenkins that has been historically used to identify * this Jenkins to the outside world. * * <p> * This form of identifier is weak in that it can be impersonated by others. See * https://wiki.jenkins-ci.org/display/JENKINS/Instance+Identity for more modern form of instance ID * that can be challenged and verified. * * @since 1.498 */ @SuppressWarnings("deprecation") public String getLegacyInstanceId() { return Util.getDigestOf(getSecretKey()); } /** * Gets the SCM descriptor by name. Primarily used for making them web-visible. */ public Descriptor<SCM> getScm(String shortClassName) { return findDescriptor(shortClassName,SCM.all()); } /** * Gets the repository browser descriptor by name. Primarily used for making them web-visible. */ public Descriptor<RepositoryBrowser<?>> getRepositoryBrowser(String shortClassName) { return findDescriptor(shortClassName,RepositoryBrowser.all()); } /** * Gets the builder descriptor by name. Primarily used for making them web-visible. */ public Descriptor<Builder> getBuilder(String shortClassName) { return findDescriptor(shortClassName, Builder.all()); } /** * Gets the build wrapper descriptor by name. Primarily used for making them web-visible. */ public Descriptor<BuildWrapper> getBuildWrapper(String shortClassName) { return findDescriptor(shortClassName, BuildWrapper.all()); } /** * Gets the publisher descriptor by name. Primarily used for making them web-visible. */ public Descriptor<Publisher> getPublisher(String shortClassName) { return findDescriptor(shortClassName, Publisher.all()); } /** * Gets the trigger descriptor by name. Primarily used for making them web-visible. */ public TriggerDescriptor getTrigger(String shortClassName) { return (TriggerDescriptor) findDescriptor(shortClassName, Trigger.all()); } /** * Gets the retention strategy descriptor by name. Primarily used for making them web-visible. */ public Descriptor<RetentionStrategy<?>> getRetentionStrategy(String shortClassName) { return findDescriptor(shortClassName, RetentionStrategy.all()); } /** * Gets the {@link JobPropertyDescriptor} by name. Primarily used for making them web-visible. */ public JobPropertyDescriptor getJobProperty(String shortClassName) { // combining these two lines triggers javac bug. See issue #610. Descriptor d = findDescriptor(shortClassName, JobPropertyDescriptor.all()); return (JobPropertyDescriptor) d; } /** * @deprecated * UI method. Not meant to be used programatically. */ @Deprecated public ComputerSet getComputer() { return new ComputerSet(); } /** * Exposes {@link Descriptor} by its name to URL. * * After doing all the {@code getXXX(shortClassName)} methods, I finally realized that * this just doesn't scale. * * @param id * Either {@link Descriptor#getId()} (recommended) or the short name of a {@link Describable} subtype (for compatibility) * @throws IllegalArgumentException if a short name was passed which matches multiple IDs (fail fast) */ @SuppressWarnings({"unchecked", "rawtypes"}) // too late to fix public Descriptor getDescriptor(String id) { // legacy descriptors that are reigstered manually doesn't show up in getExtensionList, so check them explicitly. Iterable<Descriptor> descriptors = Iterators.sequence(getExtensionList(Descriptor.class), DescriptorExtensionList.listLegacyInstances()); for (Descriptor d : descriptors) { if (d.getId().equals(id)) { return d; } } Descriptor candidate = null; for (Descriptor d : descriptors) { String name = d.getId(); if (name.substring(name.lastIndexOf('.') + 1).equals(id)) { if (candidate == null) { candidate = d; } else { throw new IllegalArgumentException(id + " is ambiguous; matches both " + name + " and " + candidate.getId()); } } } return candidate; } /** * Alias for {@link #getDescriptor(String)}. */ public Descriptor getDescriptorByName(String id) { return getDescriptor(id); } /** * Gets the {@link Descriptor} that corresponds to the given {@link Describable} type. * <p> * If you have an instance of {@code type} and call {@link Describable#getDescriptor()}, * you'll get the same instance that this method returns. */ public Descriptor getDescriptor(Class<? extends Describable> type) { for( Descriptor d : getExtensionList(Descriptor.class) ) if(d.clazz==type) return d; return null; } /** * Works just like {@link #getDescriptor(Class)} but don't take no for an answer. * * @throws AssertionError * If the descriptor is missing. * @since 1.326 */ public Descriptor getDescriptorOrDie(Class<? extends Describable> type) { Descriptor d = getDescriptor(type); if (d==null) throw new AssertionError(type+" is missing its descriptor"); return d; } /** * Gets the {@link Descriptor} instance in the current Jenkins by its type. */ public <T extends Descriptor> T getDescriptorByType(Class<T> type) { for( Descriptor d : getExtensionList(Descriptor.class) ) if(d.getClass()==type) return type.cast(d); return null; } /** * Gets the {@link SecurityRealm} descriptors by name. Primarily used for making them web-visible. */ public Descriptor<SecurityRealm> getSecurityRealms(String shortClassName) { return findDescriptor(shortClassName,SecurityRealm.all()); } /** * Finds a descriptor that has the specified name. */ private <T extends Describable<T>> Descriptor<T> findDescriptor(String shortClassName, Collection<? extends Descriptor<T>> descriptors) { String name = '.'+shortClassName; for (Descriptor<T> d : descriptors) { if(d.clazz.getName().endsWith(name)) return d; } return null; } protected void updateComputerList() { updateComputerList(AUTOMATIC_SLAVE_LAUNCH); } /** @deprecated Use {@link SCMListener#all} instead. */ @Deprecated public CopyOnWriteList<SCMListener> getSCMListeners() { return scmListeners; } /** * Gets the plugin object from its short name. * * <p> * This allows URL <tt>hudson/plugin/ID</tt> to be served by the views * of the plugin class. */ public Plugin getPlugin(String shortName) { PluginWrapper p = pluginManager.getPlugin(shortName); if(p==null) return null; return p.getPlugin(); } /** * Gets the plugin object from its class. * * <p> * This allows easy storage of plugin information in the plugin singleton without * every plugin reimplementing the singleton pattern. * * @param clazz The plugin class (beware class-loader fun, this will probably only work * from within the jpi that defines the plugin class, it may or may not work in other cases) * * @return The plugin instance. */ @SuppressWarnings("unchecked") public <P extends Plugin> P getPlugin(Class<P> clazz) { PluginWrapper p = pluginManager.getPlugin(clazz); if(p==null) return null; return (P) p.getPlugin(); } /** * Gets the plugin objects from their super-class. * * @param clazz The plugin class (beware class-loader fun) * * @return The plugin instances. */ public <P extends Plugin> List<P> getPlugins(Class<P> clazz) { List<P> result = new ArrayList<P>(); for (PluginWrapper w: pluginManager.getPlugins(clazz)) { result.add((P)w.getPlugin()); } return Collections.unmodifiableList(result); } /** * Synonym for {@link #getDescription}. */ public String getSystemMessage() { return systemMessage; } /** * Gets the markup formatter used in the system. * * @return * never null. * @since 1.391 */ public @Nonnull MarkupFormatter getMarkupFormatter() { MarkupFormatter f = markupFormatter; return f != null ? f : new EscapedMarkupFormatter(); } /** * Sets the markup formatter used in the system globally. * * @since 1.391 */ public void setMarkupFormatter(MarkupFormatter f) { this.markupFormatter = f; } /** * Sets the system message. */ public void setSystemMessage(String message) throws IOException { this.systemMessage = message; save(); } public FederatedLoginService getFederatedLoginService(String name) { for (FederatedLoginService fls : FederatedLoginService.all()) { if (fls.getUrlName().equals(name)) return fls; } return null; } public List<FederatedLoginService> getFederatedLoginServices() { return FederatedLoginService.all(); } public Launcher createLauncher(TaskListener listener) { return new LocalLauncher(listener).decorateFor(this); } public String getFullName() { return ""; } public String getFullDisplayName() { return ""; } /** * Returns the transient {@link Action}s associated with the top page. * * <p> * Adding {@link Action} is primarily useful for plugins to contribute * an item to the navigation bar of the top page. See existing {@link Action} * implementation for it affects the GUI. * * <p> * To register an {@link Action}, implement {@link RootAction} extension point, or write code like * {@code Jenkins.getInstance().getActions().add(...)}. * * @return * Live list where the changes can be made. Can be empty but never null. * @since 1.172 */ public List<Action> getActions() { return actions; } /** * Gets just the immediate children of {@link Jenkins}. * * @see #getAllItems(Class) */ @Exported(name="jobs") public List<TopLevelItem> getItems() { if (authorizationStrategy instanceof AuthorizationStrategy.Unsecured || authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) { return new ArrayList(items.values()); } List<TopLevelItem> viewableItems = new ArrayList<TopLevelItem>(); for (TopLevelItem item : items.values()) { if (item.hasPermission(Item.READ)) viewableItems.add(item); } return viewableItems; } /** * Returns the read-only view of all the {@link TopLevelItem}s keyed by their names. * <p> * This method is efficient, as it doesn't involve any copying. * * @since 1.296 */ public Map<String,TopLevelItem> getItemMap() { return Collections.unmodifiableMap(items); } /** * Gets just the immediate children of {@link Jenkins} but of the given type. */ public <T> List<T> getItems(Class<T> type) { List<T> r = new ArrayList<T>(); for (TopLevelItem i : getItems()) if (type.isInstance(i)) r.add(type.cast(i)); return r; } /** * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree * and filter them by the given type. */ public <T extends Item> List<T> getAllItems(Class<T> type) { return Items.getAllItems(this, type); } /** * Gets all the items recursively. * * @since 1.402 */ public List<Item> getAllItems() { return getAllItems(Item.class); } /** * Gets a list of simple top-level projects. * @deprecated This method will ignore Maven and matrix projects, as well as projects inside containers such as folders. * You may prefer to call {@link #getAllItems(Class)} on {@link AbstractProject}, * perhaps also using {@link Util#createSubList} to consider only {@link TopLevelItem}s. * (That will also consider the caller's permissions.) * If you really want to get just {@link Project}s at top level, ignoring permissions, * you can filter the values from {@link #getItemMap} using {@link Util#createSubList}. */ @Deprecated public List<Project> getProjects() { return Util.createSubList(items.values(),Project.class); } /** * Gets the names of all the {@link Job}s. */ public Collection<String> getJobNames() { List<String> names = new ArrayList<String>(); for (Job j : getAllItems(Job.class)) names.add(j.getFullName()); return names; } public List<Action> getViewActions() { return getActions(); } /** * Gets the names of all the {@link TopLevelItem}s. */ public Collection<String> getTopLevelItemNames() { List<String> names = new ArrayList<String>(); for (TopLevelItem j : items.values()) names.add(j.getName()); return names; } public View getView(String name) { return viewGroupMixIn.getView(name); } /** * Gets the read-only list of all {@link View}s. */ @Exported public Collection<View> getViews() { return viewGroupMixIn.getViews(); } @Override public void addView(View v) throws IOException { viewGroupMixIn.addView(v); } public boolean canDelete(View view) { return viewGroupMixIn.canDelete(view); } public synchronized void deleteView(View view) throws IOException { viewGroupMixIn.deleteView(view); } public void onViewRenamed(View view, String oldName, String newName) { viewGroupMixIn.onViewRenamed(view,oldName,newName); } /** * Returns the primary {@link View} that renders the top-page of Jenkins. */ @Exported public View getPrimaryView() { return viewGroupMixIn.getPrimaryView(); } public void setPrimaryView(View v) { this.primaryView = v.getViewName(); } public ViewsTabBar getViewsTabBar() { return viewsTabBar; } public void setViewsTabBar(ViewsTabBar viewsTabBar) { this.viewsTabBar = viewsTabBar; } public Jenkins getItemGroup() { return this; } public MyViewsTabBar getMyViewsTabBar() { return myViewsTabBar; } public void setMyViewsTabBar(MyViewsTabBar myViewsTabBar) { this.myViewsTabBar = myViewsTabBar; } /** * Returns true if the current running Jenkins is upgraded from a version earlier than the specified version. * * <p> * This method continues to return true until the system configuration is saved, at which point * {@link #version} will be overwritten and Jenkins forgets the upgrade history. * * <p> * To handle SNAPSHOTS correctly, pass in "1.N.*" to test if it's upgrading from the version * equal or younger than N. So say if you implement a feature in 1.301 and you want to check * if the installation upgraded from pre-1.301, pass in "1.300.*" * * @since 1.301 */ public boolean isUpgradedFromBefore(VersionNumber v) { try { return new VersionNumber(version).isOlderThan(v); } catch (IllegalArgumentException e) { // fail to parse this version number return false; } } /** * Gets the read-only list of all {@link Computer}s. */ public Computer[] getComputers() { Computer[] r = computers.values().toArray(new Computer[computers.size()]); Arrays.sort(r,new Comparator<Computer>() { @Override public int compare(Computer lhs, Computer rhs) { if(lhs.getNode()==Jenkins.this) return -1; if(rhs.getNode()==Jenkins.this) return 1; return lhs.getName().compareTo(rhs.getName()); } }); return r; } @CLIResolver public @CheckForNull Computer getComputer(@Argument(required=true,metaVar="NAME",usage="Node name") @Nonnull String name) { if(name.equals("(master)")) name = ""; for (Computer c : computers.values()) { if(c.getName().equals(name)) return c; } return null; } /** * Gets the label that exists on this system by the name. * * @return null if name is null. * @see Label#parseExpression(String) (String) */ public Label getLabel(String expr) { if(expr==null) return null; expr = hudson.util.QuotedStringTokenizer.unquote(expr); while(true) { Label l = labels.get(expr); if(l!=null) return l; // non-existent try { labels.putIfAbsent(expr,Label.parseExpression(expr)); } catch (ANTLRException e) { // laxly accept it as a single label atom for backward compatibility return getLabelAtom(expr); } } } /** * Returns the label atom of the given name. * @return non-null iff name is non-null */ public @Nullable LabelAtom getLabelAtom(@CheckForNull String name) { if (name==null) return null; while(true) { Label l = labels.get(name); if(l!=null) return (LabelAtom)l; // non-existent LabelAtom la = new LabelAtom(name); if (labels.putIfAbsent(name, la)==null) la.load(); } } /** * Gets all the active labels in the current system. */ public Set<Label> getLabels() { Set<Label> r = new TreeSet<Label>(); for (Label l : labels.values()) { if(!l.isEmpty()) r.add(l); } return r; } public Set<LabelAtom> getLabelAtoms() { Set<LabelAtom> r = new TreeSet<LabelAtom>(); for (Label l : labels.values()) { if(!l.isEmpty() && l instanceof LabelAtom) r.add((LabelAtom)l); } return r; } public Queue getQueue() { return queue; } @Override public String getDisplayName() { return Messages.Hudson_DisplayName(); } public synchronized List<JDK> getJDKs() { if(jdks==null) jdks = new ArrayList<JDK>(); return jdks; } /** * Replaces all JDK installations with those from the given collection. * * Use {@link hudson.model.JDK.DescriptorImpl#setInstallations(JDK...)} to * set JDK installations from external code. */ @Restricted(NoExternalUse.class) public synchronized void setJDKs(Collection<? extends JDK> jdks) { this.jdks = new ArrayList<JDK>(jdks); } /** * Gets the JDK installation of the given name, or returns null. */ public JDK getJDK(String name) { if(name==null) { // if only one JDK is configured, "default JDK" should mean that JDK. List<JDK> jdks = getJDKs(); if(jdks.size()==1) return jdks.get(0); return null; } for (JDK j : getJDKs()) { if(j.getName().equals(name)) return j; } return null; } /** * Gets the slave node of the give name, hooked under this Jenkins. */ public @CheckForNull Node getNode(String name) { return nodes.getNode(name); } /** * Gets a {@link Cloud} by {@link Cloud#name its name}, or null. */ public Cloud getCloud(String name) { return clouds.getByName(name); } protected Map<Node,Computer> getComputerMap() { return computers; } /** * Returns all {@link Node}s in the system, excluding {@link Jenkins} instance itself which * represents the master. */ public List<Node> getNodes() { return nodes.getNodes(); } /** * Get the {@link Nodes} object that handles maintaining individual {@link Node}s. * @return The Nodes object. */ @Restricted(NoExternalUse.class) public Nodes getNodesObject() { // TODO replace this with something better when we properly expose Nodes. return nodes; } /** * Adds one more {@link Node} to Jenkins. */ public void addNode(Node n) throws IOException { nodes.addNode(n); } /** * Removes a {@link Node} from Jenkins. */ public void removeNode(@Nonnull Node n) throws IOException { nodes.removeNode(n); } public void setNodes(final List<? extends Node> n) throws IOException { nodes.setNodes(n); } public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() { return nodeProperties; } public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getGlobalNodeProperties() { return globalNodeProperties; } /** * Resets all labels and remove invalid ones. * * This should be called when the assumptions behind label cache computation changes, * but we also call this periodically to self-heal any data out-of-sync issue. */ /*package*/ void trimLabels() { for (Iterator<Label> itr = labels.values().iterator(); itr.hasNext();) { Label l = itr.next(); resetLabel(l); if(l.isEmpty()) itr.remove(); } } /** * Binds {@link AdministrativeMonitor}s to URL. */ public AdministrativeMonitor getAdministrativeMonitor(String id) { for (AdministrativeMonitor m : administrativeMonitors) if(m.id.equals(id)) return m; return null; } public NodeDescriptor getDescriptor() { return DescriptorImpl.INSTANCE; } public static final class DescriptorImpl extends NodeDescriptor { @Extension public static final DescriptorImpl INSTANCE = new DescriptorImpl(); public String getDisplayName() { return ""; } @Override public boolean isInstantiable() { return false; } public FormValidation doCheckNumExecutors(@QueryParameter String value) { return FormValidation.validateNonNegativeInteger(value); } public FormValidation doCheckRawBuildsDir(@QueryParameter String value) { // do essentially what expandVariablesForDirectory does, without an Item String replacedValue = expandVariablesForDirectory(value, "doCheckRawBuildsDir-Marker:foo", Jenkins.getInstance().getRootDir().getPath() + "/jobs/doCheckRawBuildsDir-Marker$foo"); File replacedFile = new File(replacedValue); if (!replacedFile.isAbsolute()) { return FormValidation.error(value + " does not resolve to an absolute path"); } if (!replacedValue.contains("doCheckRawBuildsDir-Marker")) { return FormValidation.error(value + " does not contain ${ITEM_FULL_NAME} or ${ITEM_ROOTDIR}, cannot distinguish between projects"); } if (replacedValue.contains("doCheckRawBuildsDir-Marker:foo")) { // make sure platform can handle colon try { File tmp = File.createTempFile("Jenkins-doCheckRawBuildsDir", "foo:bar"); tmp.delete(); } catch (IOException e) { return FormValidation.error(value + " contains ${ITEM_FULLNAME} but your system does not support it (JENKINS-12251). Use ${ITEM_FULL_NAME} instead"); } } File d = new File(replacedValue); if (!d.isDirectory()) { // if dir does not exist (almost guaranteed) need to make sure nearest existing ancestor can be written to d = d.getParentFile(); while (!d.exists()) { d = d.getParentFile(); } if (!d.canWrite()) { return FormValidation.error(value + " does not exist and probably cannot be created"); } } return FormValidation.ok(); } // to route /descriptor/FQCN/xxx to getDescriptor(FQCN).xxx public Object getDynamic(String token) { return Jenkins.getInstance().getDescriptor(token); } } /** * Gets the system default quiet period. */ public int getQuietPeriod() { return quietPeriod!=null ? quietPeriod : 5; } /** * Sets the global quiet period. * * @param quietPeriod * null to the default value. */ public void setQuietPeriod(Integer quietPeriod) throws IOException { this.quietPeriod = quietPeriod; save(); } /** * Gets the global SCM check out retry count. */ public int getScmCheckoutRetryCount() { return scmCheckoutRetryCount; } public void setScmCheckoutRetryCount(int scmCheckoutRetryCount) throws IOException { this.scmCheckoutRetryCount = scmCheckoutRetryCount; save(); } @Override public String getSearchUrl() { return ""; } @Override public SearchIndexBuilder makeSearchIndex() { return super.makeSearchIndex() .add("configure", "config","configure") .add("manage") .add("log") .add(new CollectionSearchIndex<TopLevelItem>() { protected SearchItem get(String key) { return getItemByFullName(key, TopLevelItem.class); } protected Collection<TopLevelItem> all() { return getAllItems(TopLevelItem.class); } }) .add(getPrimaryView().makeSearchIndex()) .add(new CollectionSearchIndex() {// for computers protected Computer get(String key) { return getComputer(key); } protected Collection<Computer> all() { return computers.values(); } }) .add(new CollectionSearchIndex() {// for users protected User get(String key) { return User.get(key,false); } protected Collection<User> all() { return User.getAll(); } }) .add(new CollectionSearchIndex() {// for views protected View get(String key) { return getView(key); } protected Collection<View> all() { return viewGroupMixIn.getViews(); } }); } public String getUrlChildPrefix() { return "job"; } /** * Gets the absolute URL of Jenkins, such as {@code http://localhost/jenkins/}. * * <p> * This method first tries to use the manually configured value, then * fall back to {@link #getRootUrlFromRequest}. * It is done in this order so that it can work correctly even in the face * of a reverse proxy. * * @return null if this parameter is not configured by the user and the calling thread is not in an HTTP request; otherwise the returned URL will always have the trailing {@code /} * @since 1.66 * @see <a href="https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML">Hyperlinks in HTML</a> */ public @Nullable String getRootUrl() { String url = JenkinsLocationConfiguration.get().getUrl(); if(url!=null) { return Util.ensureEndsWith(url,"/"); } StaplerRequest req = Stapler.getCurrentRequest(); if(req!=null) return getRootUrlFromRequest(); return null; } /** * Is Jenkins running in HTTPS? * * Note that we can't really trust {@link StaplerRequest#isSecure()} because HTTPS might be terminated * in the reverse proxy. */ public boolean isRootUrlSecure() { String url = getRootUrl(); return url!=null && url.startsWith("https"); } /** * Gets the absolute URL of Jenkins top page, such as {@code http://localhost/jenkins/}. * * <p> * Unlike {@link #getRootUrl()}, which uses the manually configured value, * this one uses the current request to reconstruct the URL. The benefit is * that this is immune to the configuration mistake (users often fail to set the root URL * correctly, especially when a migration is involved), but the downside * is that unless you are processing a request, this method doesn't work. * * <p>Please note that this will not work in all cases if Jenkins is running behind a * reverse proxy which has not been fully configured. * Specifically the {@code Host} and {@code X-Forwarded-Proto} headers must be set. * <a href="https://wiki.jenkins-ci.org/display/JENKINS/Running+Jenkins+behind+Apache">Running Jenkins behind Apache</a> * shows some examples of configuration. * @since 1.263 */ public @Nonnull String getRootUrlFromRequest() { StaplerRequest req = Stapler.getCurrentRequest(); if (req == null) { throw new IllegalStateException("cannot call getRootUrlFromRequest from outside a request handling thread"); } StringBuilder buf = new StringBuilder(); String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme()); buf.append(scheme).append("://"); String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName()); int index = host.indexOf(':'); int port = req.getServerPort(); if (index == -1) { // Almost everyone else except Nginx put the host and port in separate headers buf.append(host); } else { // Nginx uses the same spec as for the Host header, i.e. hostanme:port buf.append(host.substring(0, index)); if (index + 1 < host.length()) { try { port = Integer.parseInt(host.substring(index + 1)); } catch (NumberFormatException e) { // ignore } } // but if a user has configured Nginx with an X-Forwarded-Port, that will win out. } String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null); if (forwardedPort != null) { try { port = Integer.parseInt(forwardedPort); } catch (NumberFormatException e) { // ignore } } if (port != ("https".equals(scheme) ? 443 : 80)) { buf.append(':').append(port); } buf.append(req.getContextPath()).append('/'); return buf.toString(); } /** * Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating * header is the first header. If the originating header contains a comma separated list, the originating entry * is the first one. * @param req the request * @param header the header name * @param defaultValue the value to return if the header is absent. * @return the originating entry of the header or the default value if the header was not present. */ private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) { String value = req.getHeader(header); if (value != null) { int index = value.indexOf(','); return index == -1 ? value.trim() : value.substring(0,index).trim(); } return defaultValue; } public File getRootDir() { return root; } public FilePath getWorkspaceFor(TopLevelItem item) { for (WorkspaceLocator l : WorkspaceLocator.all()) { FilePath workspace = l.locate(item, this); if (workspace != null) { return workspace; } } return new FilePath(expandVariablesForDirectory(workspaceDir, item)); } public File getBuildDirFor(Job job) { return expandVariablesForDirectory(buildsDir, job); } private File expandVariablesForDirectory(String base, Item item) { return new File(expandVariablesForDirectory(base, item.getFullName(), item.getRootDir().getPath())); } @Restricted(NoExternalUse.class) static String expandVariablesForDirectory(String base, String itemFullName, String itemRootDir) { return Util.replaceMacro(base, ImmutableMap.of( "JENKINS_HOME", Jenkins.getInstance().getRootDir().getPath(), "ITEM_ROOTDIR", itemRootDir, "ITEM_FULLNAME", itemFullName, // legacy, deprecated "ITEM_FULL_NAME", itemFullName.replace(':','$'))); // safe, see JENKINS-12251 } public String getRawWorkspaceDir() { return workspaceDir; } public String getRawBuildsDir() { return buildsDir; } @Restricted(NoExternalUse.class) public void setRawBuildsDir(String buildsDir) { this.buildsDir = buildsDir; } @Override public @Nonnull FilePath getRootPath() { return new FilePath(getRootDir()); } @Override public FilePath createPath(String absolutePath) { return new FilePath((VirtualChannel)null,absolutePath); } public ClockDifference getClockDifference() { return ClockDifference.ZERO; } @Override public Callable<ClockDifference, IOException> getClockDifferenceCallable() { return new MasterToSlaveCallable<ClockDifference, IOException>() { public ClockDifference call() throws IOException { return new ClockDifference(0); } }; } /** * For binding {@link LogRecorderManager} to "/log". * Everything below here is admin-only, so do the check here. */ public LogRecorderManager getLog() { checkPermission(ADMINISTER); return log; } /** * A convenience method to check if there's some security * restrictions in place. */ @Exported public boolean isUseSecurity() { return securityRealm!=SecurityRealm.NO_AUTHENTICATION || authorizationStrategy!=AuthorizationStrategy.UNSECURED; } public boolean isUseProjectNamingStrategy(){ return projectNamingStrategy != DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; } /** * If true, all the POST requests to Jenkins would have to have crumb in it to protect * Jenkins from CSRF vulnerabilities. */ @Exported public boolean isUseCrumbs() { return crumbIssuer!=null; } /** * Returns the constant that captures the three basic security modes in Jenkins. */ public SecurityMode getSecurity() { // fix the variable so that this code works under concurrent modification to securityRealm. SecurityRealm realm = securityRealm; if(realm==SecurityRealm.NO_AUTHENTICATION) return SecurityMode.UNSECURED; if(realm instanceof LegacySecurityRealm) return SecurityMode.LEGACY; return SecurityMode.SECURED; } /** * @return * never null. */ public SecurityRealm getSecurityRealm() { return securityRealm; } public void setSecurityRealm(SecurityRealm securityRealm) { if(securityRealm==null) securityRealm= SecurityRealm.NO_AUTHENTICATION; this.useSecurity = true; IdStrategy oldUserIdStrategy = this.securityRealm == null ? securityRealm.getUserIdStrategy() // don't trigger rekey on Jenkins load : this.securityRealm.getUserIdStrategy(); this.securityRealm = securityRealm; // reset the filters and proxies for the new SecurityRealm try { HudsonFilter filter = HudsonFilter.get(servletContext); if (filter == null) { // Fix for #3069: This filter is not necessarily initialized before the servlets. // when HudsonFilter does come back, it'll initialize itself. LOGGER.fine("HudsonFilter has not yet been initialized: Can't perform security setup for now"); } else { LOGGER.fine("HudsonFilter has been previously initialized: Setting security up"); filter.reset(securityRealm); LOGGER.fine("Security is now fully set up"); } if (!oldUserIdStrategy.equals(this.securityRealm.getUserIdStrategy())) { User.rekey(); } } catch (ServletException e) { // for binary compatibility, this method cannot throw a checked exception throw new AcegiSecurityException("Failed to configure filter",e) {}; } } public void setAuthorizationStrategy(AuthorizationStrategy a) { if (a == null) a = AuthorizationStrategy.UNSECURED; useSecurity = true; authorizationStrategy = a; } public boolean isDisableRememberMe() { return disableRememberMe; } public void setDisableRememberMe(boolean disableRememberMe) { this.disableRememberMe = disableRememberMe; } public void disableSecurity() { useSecurity = null; setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); authorizationStrategy = AuthorizationStrategy.UNSECURED; } public void setProjectNamingStrategy(ProjectNamingStrategy ns) { if(ns == null){ ns = DefaultProjectNamingStrategy.DEFAULT_NAMING_STRATEGY; } projectNamingStrategy = ns; } public Lifecycle getLifecycle() { return Lifecycle.get(); } /** * Gets the dependency injection container that hosts all the extension implementations and other * components in Jenkins. * * @since 1.433 */ public Injector getInjector() { return lookup(Injector.class); } /** * Returns {@link ExtensionList} that retains the discovered instances for the given extension type. * * @param extensionType * The base type that represents the extension point. Normally {@link ExtensionPoint} subtype * but that's not a hard requirement. * @return * Can be an empty list but never null. * @see ExtensionList#lookup */ @SuppressWarnings({"unchecked"}) public <T> ExtensionList<T> getExtensionList(Class<T> extensionType) { return extensionLists.get(extensionType); } /** * Used to bind {@link ExtensionList}s to URLs. * * @since 1.349 */ public ExtensionList getExtensionList(String extensionType) throws ClassNotFoundException { return getExtensionList(pluginManager.uberClassLoader.loadClass(extensionType)); } /** * Returns {@link ExtensionList} that retains the discovered {@link Descriptor} instances for the given * kind of {@link Describable}. * * @return * Can be an empty list but never null. */ @SuppressWarnings({"unchecked"}) public <T extends Describable<T>,D extends Descriptor<T>> DescriptorExtensionList<T,D> getDescriptorList(Class<T> type) { return descriptorLists.get(type); } /** * Refresh {@link ExtensionList}s by adding all the newly discovered extensions. * * Exposed only for {@link PluginManager#dynamicLoad(File)}. */ public void refreshExtensions() throws ExtensionRefreshException { ExtensionList<ExtensionFinder> finders = getExtensionList(ExtensionFinder.class); for (ExtensionFinder ef : finders) { if (!ef.isRefreshable()) throw new ExtensionRefreshException(ef+" doesn't support refresh"); } List<ExtensionComponentSet> fragments = Lists.newArrayList(); for (ExtensionFinder ef : finders) { fragments.add(ef.refresh()); } ExtensionComponentSet delta = ExtensionComponentSet.union(fragments).filtered(); // if we find a new ExtensionFinder, we need it to list up all the extension points as well List<ExtensionComponent<ExtensionFinder>> newFinders = Lists.newArrayList(delta.find(ExtensionFinder.class)); while (!newFinders.isEmpty()) { ExtensionFinder f = newFinders.remove(newFinders.size()-1).getInstance(); ExtensionComponentSet ecs = ExtensionComponentSet.allOf(f).filtered(); newFinders.addAll(ecs.find(ExtensionFinder.class)); delta = ExtensionComponentSet.union(delta, ecs); } for (ExtensionList el : extensionLists.values()) { el.refresh(delta); } for (ExtensionList el : descriptorLists.values()) { el.refresh(delta); } // TODO: we need some generalization here so that extension points can be notified when a refresh happens? for (ExtensionComponent<RootAction> ea : delta.find(RootAction.class)) { Action a = ea.getInstance(); if (!actions.contains(a)) actions.add(a); } } /** * Returns the root {@link ACL}. * * @see AuthorizationStrategy#getRootACL() */ @Override public ACL getACL() { return authorizationStrategy.getRootACL(); } /** * @return * never null. */ public AuthorizationStrategy getAuthorizationStrategy() { return authorizationStrategy; } /** * The strategy used to check the project names. * @return never <code>null</code> */ public ProjectNamingStrategy getProjectNamingStrategy() { return projectNamingStrategy == null ? ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY : projectNamingStrategy; } /** * Returns true if Jenkins is quieting down. * <p> * No further jobs will be executed unless it * can be finished while other current pending builds * are still in progress. */ @Exported public boolean isQuietingDown() { return isQuietingDown; } /** * Returns true if the container initiated the termination of the web application. */ public boolean isTerminating() { return terminating; } /** * Gets the initialization milestone that we've already reached. * * @return * {@link InitMilestone#STARTED} even if the initialization hasn't been started, so that this method * never returns null. */ public InitMilestone getInitLevel() { return initLevel; } public void setNumExecutors(int n) throws IOException { if (this.numExecutors != n) { this.numExecutors = n; updateComputerList(); save(); } } /** * {@inheritDoc}. * * Note that the look up is case-insensitive. */ @Override public TopLevelItem getItem(String name) throws AccessDeniedException { if (name==null) return null; TopLevelItem item = items.get(name); if (item==null) return null; if (!item.hasPermission(Item.READ)) { if (item.hasPermission(Item.DISCOVER)) { throw new AccessDeniedException("Please login to access job " + name); } return null; } return item; } /** * Gets the item by its path name from the given context * * <h2>Path Names</h2> * <p> * If the name starts from '/', like "/foo/bar/zot", then it's interpreted as absolute. * Otherwise, the name should be something like "foo/bar" and it's interpreted like * relative path name in the file system is, against the given context. * <p>For compatibility, as a fallback when nothing else matches, a simple path * like {@code foo/bar} can also be treated with {@link #getItemByFullName}. * @param context * null is interpreted as {@link Jenkins}. Base 'directory' of the interpretation. * @since 1.406 */ public Item getItem(String pathName, ItemGroup context) { if (context==null) context = this; if (pathName==null) return null; if (pathName.startsWith("/")) // absolute return getItemByFullName(pathName); Object/*Item|ItemGroup*/ ctx = context; StringTokenizer tokens = new StringTokenizer(pathName,"/"); while (tokens.hasMoreTokens()) { String s = tokens.nextToken(); if (s.equals("..")) { if (ctx instanceof Item) { ctx = ((Item)ctx).getParent(); continue; } ctx=null; // can't go up further break; } if (s.equals(".")) { continue; } if (ctx instanceof ItemGroup) { ItemGroup g = (ItemGroup) ctx; Item i = g.getItem(s); if (i==null || !i.hasPermission(Item.READ)) { // TODO consider DISCOVER ctx=null; // can't go up further break; } ctx=i; } else { return null; } } if (ctx instanceof Item) return (Item)ctx; // fall back to the classic interpretation return getItemByFullName(pathName); } public final Item getItem(String pathName, Item context) { return getItem(pathName,context!=null?context.getParent():null); } public final <T extends Item> T getItem(String pathName, ItemGroup context, @Nonnull Class<T> type) { Item r = getItem(pathName, context); if (type.isInstance(r)) return type.cast(r); return null; } public final <T extends Item> T getItem(String pathName, Item context, Class<T> type) { return getItem(pathName,context!=null?context.getParent():null,type); } public File getRootDirFor(TopLevelItem child) { return getRootDirFor(child.getName()); } private File getRootDirFor(String name) { return new File(new File(getRootDir(),"jobs"), name); } /** * Gets the {@link Item} object by its full name. * Full names are like path names, where each name of {@link Item} is * combined by '/'. * * @return * null if either such {@link Item} doesn't exist under the given full name, * or it exists but it's no an instance of the given type. * @throws AccessDeniedException as per {@link ItemGroup#getItem} */ public @CheckForNull <T extends Item> T getItemByFullName(String fullName, Class<T> type) throws AccessDeniedException { StringTokenizer tokens = new StringTokenizer(fullName,"/"); ItemGroup parent = this; if(!tokens.hasMoreTokens()) return null; // for example, empty full name. while(true) { Item item = parent.getItem(tokens.nextToken()); if(!tokens.hasMoreTokens()) { if(type.isInstance(item)) return type.cast(item); else return null; } if(!(item instanceof ItemGroup)) return null; // this item can't have any children if (!item.hasPermission(Item.READ)) return null; // TODO consider DISCOVER parent = (ItemGroup) item; } } public @CheckForNull Item getItemByFullName(String fullName) { return getItemByFullName(fullName,Item.class); } /** * Gets the user of the given name. * * @return the user of the given name (which may or may not be an id), if that person exists or the invoker {@link #hasPermission} on {@link #ADMINISTER}; else null * @see User#get(String,boolean), {@link User#getById(String, boolean)} */ public @CheckForNull User getUser(String name) { return User.get(name,hasPermission(ADMINISTER)); } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name ) throws IOException { return createProject(type, name, true); } public synchronized TopLevelItem createProject( TopLevelItemDescriptor type, String name, boolean notify ) throws IOException { return itemGroupMixIn.createProject(type,name,notify); } /** * Overwrites the existing item by new one. * * <p> * This is a short cut for deleting an existing job and adding a new one. */ public synchronized void putItem(TopLevelItem item) throws IOException, InterruptedException { String name = item.getName(); TopLevelItem old = items.get(name); if (old ==item) return; // noop checkPermission(Item.CREATE); if (old!=null) old.delete(); items.put(name,item); ItemListener.fireOnCreated(item); } /** * Creates a new job. * * <p> * This version infers the descriptor from the type of the top-level item. * * @throws IllegalArgumentException * if the project of the given name already exists. */ public synchronized <T extends TopLevelItem> T createProject( Class<T> type, String name ) throws IOException { return type.cast(createProject((TopLevelItemDescriptor)getDescriptor(type),name)); } /** * Called by {@link Job#renameTo(String)} to update relevant data structure. * assumed to be synchronized on Jenkins by the caller. */ public void onRenamed(TopLevelItem job, String oldName, String newName) throws IOException { items.remove(oldName); items.put(newName,job); // For compatibility with old views: for (View v : views) v.onJobRenamed(job, oldName, newName); } /** * Called in response to {@link Job#doDoDelete(StaplerRequest, StaplerResponse)} */ public void onDeleted(TopLevelItem item) throws IOException { ItemListener.fireOnDeleted(item); items.remove(item.getName()); // For compatibility with old views: for (View v : views) v.onJobRenamed(item, item.getName(), null); } @Override public boolean canAdd(TopLevelItem item) { return true; } @Override synchronized public <I extends TopLevelItem> I add(I item, String name) throws IOException, IllegalArgumentException { if (items.containsKey(name)) { throw new IllegalArgumentException("already an item '" + name + "'"); } items.put(name, item); return item; } @Override public void remove(TopLevelItem item) throws IOException, IllegalArgumentException { items.remove(item.getName()); } public FingerprintMap getFingerprintMap() { return fingerprintMap; } // if no finger print matches, display "not found page". public Object getFingerprint( String md5sum ) throws IOException { Fingerprint r = fingerprintMap.get(md5sum); if(r==null) return new NoFingerprintMatch(md5sum); else return r; } /** * Gets a {@link Fingerprint} object if it exists. * Otherwise null. */ public Fingerprint _getFingerprint( String md5sum ) throws IOException { return fingerprintMap.get(md5sum); } /** * The file we save our configuration. */ private XmlFile getConfigFile() { return new XmlFile(XSTREAM, new File(root,"config.xml")); } public int getNumExecutors() { return numExecutors; } public Mode getMode() { return mode; } public void setMode(Mode m) throws IOException { this.mode = m; save(); } public String getLabelString() { return fixNull(label).trim(); } @Override public void setLabelString(String label) throws IOException { this.label = label; save(); } @Override public LabelAtom getSelfLabel() { return getLabelAtom("master"); } public Computer createComputer() { return new Hudson.MasterComputer(); } private synchronized TaskBuilder loadTasks() throws IOException { File projectsDir = new File(root,"jobs"); if(!projectsDir.getCanonicalFile().isDirectory() && !projectsDir.mkdirs()) { if(projectsDir.exists()) throw new IOException(projectsDir+" is not a directory"); throw new IOException("Unable to create "+projectsDir+"\nPermission issue? Please create this directory manually."); } File[] subdirs = projectsDir.listFiles(); final Set<String> loadedNames = Collections.synchronizedSet(new HashSet<String>()); TaskGraphBuilder g = new TaskGraphBuilder(); Handle loadJenkins = g.requires(EXTENSIONS_AUGMENTED).attains(JOB_LOADED).add("Loading global config", new Executable() { public void run(Reactor session) throws Exception { XmlFile cfg = getConfigFile(); if (cfg.exists()) { // reset some data that may not exist in the disk file // so that we can take a proper compensation action later. primaryView = null; views.clear(); // load from disk cfg.unmarshal(Jenkins.this); } // if we are loading old data that doesn't have this field if (slaves != null && !slaves.isEmpty() && nodes.isLegacy()) { nodes.setNodes(slaves); slaves = null; } else { nodes.load(); } clouds.setOwner(Jenkins.this); } }); for (final File subdir : subdirs) { g.requires(loadJenkins).attains(JOB_LOADED).notFatal().add("Loading job "+subdir.getName(),new Executable() { public void run(Reactor session) throws Exception { if(!Items.getConfigFile(subdir).exists()) { //Does not have job config file, so it is not a jenkins job hence skip it return; } TopLevelItem item = (TopLevelItem) Items.load(Jenkins.this, subdir); items.put(item.getName(), item); loadedNames.add(item.getName()); } }); } g.requires(JOB_LOADED).add("Cleaning up old builds",new Executable() { public void run(Reactor reactor) throws Exception { // anything we didn't load from disk, throw them away. // doing this after loading from disk allows newly loaded items // to inspect what already existed in memory (in case of reloading) // retainAll doesn't work well because of CopyOnWriteMap implementation, so remove one by one // hopefully there shouldn't be too many of them. for (String name : items.keySet()) { if (!loadedNames.contains(name)) items.remove(name); } } }); g.requires(JOB_LOADED).add("Finalizing set up",new Executable() { public void run(Reactor session) throws Exception { rebuildDependencyGraph(); {// recompute label objects - populates the labels mapping. for (Node slave : nodes.getNodes()) // Note that not all labels are visible until the slaves have connected. slave.getAssignedLabels(); getAssignedLabels(); } // initialize views by inserting the default view if necessary // this is both for clean Jenkins and for backward compatibility. if(views.size()==0 || primaryView==null) { View v = new AllView(Messages.Hudson_ViewName()); setViewOwner(v); views.add(0,v); primaryView = v.getViewName(); } if (useSecurity!=null && !useSecurity) { // forced reset to the unsecure mode. // this works as an escape hatch for people who locked themselves out. authorizationStrategy = AuthorizationStrategy.UNSECURED; setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); } else { // read in old data that doesn't have the security field set if(authorizationStrategy==null) { if(useSecurity==null) authorizationStrategy = AuthorizationStrategy.UNSECURED; else authorizationStrategy = new LegacyAuthorizationStrategy(); } if(securityRealm==null) { if(useSecurity==null) setSecurityRealm(SecurityRealm.NO_AUTHENTICATION); else setSecurityRealm(new LegacySecurityRealm()); } else { // force the set to proxy setSecurityRealm(securityRealm); } } // Initialize the filter with the crumb issuer setCrumbIssuer(crumbIssuer); // auto register root actions for (Action a : getExtensionList(RootAction.class)) if (!actions.contains(a)) actions.add(a); } }); return g; } /** * Save the settings to a file. */ public synchronized void save() throws IOException { if(BulkChange.contains(this)) return; getConfigFile().write(this); SaveableListener.fireOnChange(this, getConfigFile()); } /** * Called to shut down the system. */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") public void cleanUp() { for (ItemListener l : ItemListener.all()) l.onBeforeShutdown(); try { final TerminatorFinder tf = new TerminatorFinder( pluginManager != null ? pluginManager.uberClassLoader : Thread.currentThread().getContextClassLoader()); new Reactor(tf).execute(new Executor() { @Override public void execute(Runnable command) { command.run(); } }); } catch (InterruptedException e) { LOGGER.log(SEVERE, "Failed to execute termination",e); e.printStackTrace(); } catch (ReactorException e) { LOGGER.log(SEVERE, "Failed to execute termination",e); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to execute termination",e); } final Set<Future<?>> pending = new HashSet<Future<?>>(); terminating = true; // JENKINS-28840 we know we will be interrupting all the Computers so get the Queue lock once for all Queue.withLock(new Runnable() { @Override public void run() { for( Computer c : computers.values() ) { c.interrupt(); killComputer(c); pending.add(c.disconnect(null)); } } }); if(udpBroadcastThread!=null) udpBroadcastThread.shutdown(); if(dnsMultiCast!=null) dnsMultiCast.close(); interruptReloadThread(); java.util.Timer timer = Trigger.timer; if (timer != null) { timer.cancel(); } // TODO: how to wait for the completion of the last job? Trigger.timer = null; Timer.shutdown(); if(tcpSlaveAgentListener!=null) tcpSlaveAgentListener.shutdown(); if(pluginManager!=null) // be defensive. there could be some ugly timing related issues pluginManager.stop(); if(getRootDir().exists()) // if we are aborting because we failed to create JENKINS_HOME, // don't try to save. Issue #536 getQueue().save(); threadPoolForLoad.shutdown(); for (Future<?> f : pending) try { f.get(10, TimeUnit.SECONDS); // if clean up operation didn't complete in time, we fail the test } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; // someone wants us to die now. quick! } catch (ExecutionException e) { LOGGER.log(Level.WARNING, "Failed to shut down properly",e); } catch (TimeoutException e) { LOGGER.log(Level.WARNING, "Failed to shut down properly",e); } LogFactory.releaseAll(); theInstance = null; } public Object getDynamic(String token) { for (Action a : getActions()) { String url = a.getUrlName(); if (url==null) continue; if (url.equals(token) || url.equals('/' + token)) return a; } for (Action a : getManagementLinks()) if(a.getUrlName().equals(token)) return a; return null; } // // // actions // // /** * Accepts submission from the configuration page. */ public synchronized void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { BulkChange bc = new BulkChange(this); try { checkPermission(ADMINISTER); JSONObject json = req.getSubmittedForm(); workspaceDir = json.getString("rawWorkspaceDir"); buildsDir = json.getString("rawBuildsDir"); systemMessage = Util.nullify(req.getParameter("system_message")); setJDKs(req.bindJSONToList(JDK.class, json.get("jdks"))); boolean result = true; for (Descriptor<?> d : Functions.getSortedDescriptorsForGlobalConfigUnclassified()) result &= configureDescriptor(req,json,d); version = VERSION; save(); updateComputerList(); if(result) FormApply.success(req.getContextPath()+'/').generateResponse(req, rsp, null); else FormApply.success("configure").generateResponse(req, rsp, null); // back to config } finally { bc.commit(); } } /** * Gets the {@link CrumbIssuer} currently in use. * * @return null if none is in use. */ public CrumbIssuer getCrumbIssuer() { return crumbIssuer; } public void setCrumbIssuer(CrumbIssuer issuer) { crumbIssuer = issuer; } public synchronized void doTestPost( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { rsp.sendRedirect("foo"); } private boolean configureDescriptor(StaplerRequest req, JSONObject json, Descriptor<?> d) throws FormException { // collapse the structure to remain backward compatible with the JSON structure before 1. String name = d.getJsonSafeClassName(); JSONObject js = json.has(name) ? json.getJSONObject(name) : new JSONObject(); // if it doesn't have the property, the method returns invalid null object. json.putAll(js); return d.configure(req, js); } /** * Accepts submission from the node configuration page. */ @RequirePOST public synchronized void doConfigExecutorsSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(ADMINISTER); BulkChange bc = new BulkChange(this); try { JSONObject json = req.getSubmittedForm(); MasterBuildConfiguration mbc = MasterBuildConfiguration.all().get(MasterBuildConfiguration.class); if (mbc!=null) mbc.configure(req,json); getNodeProperties().rebuild(req, json.optJSONObject("nodeProperties"), NodeProperty.all()); } finally { bc.commit(); } updateComputerList(); rsp.sendRedirect(req.getContextPath()+'/'+toComputer().getUrl()); // back to the computer page } /** * Accepts the new description. */ @RequirePOST public synchronized void doSubmitDescription( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { getPrimaryView().doSubmitDescription(req, rsp); } @RequirePOST // TODO does not seem to work on _either_ overload! public synchronized HttpRedirect doQuietDown() throws IOException { try { return doQuietDown(false,0); } catch (InterruptedException e) { throw new AssertionError(); // impossible } } @CLIMethod(name="quiet-down") @RequirePOST public HttpRedirect doQuietDown( @Option(name="-block",usage="Block until the system really quiets down and no builds are running") @QueryParameter boolean block, @Option(name="-timeout",usage="If non-zero, only block up to the specified number of milliseconds") @QueryParameter int timeout) throws InterruptedException, IOException { synchronized (this) { checkPermission(ADMINISTER); isQuietingDown = true; } if (block) { long waitUntil = timeout; if (timeout > 0) waitUntil += System.currentTimeMillis(); while (isQuietingDown && (timeout <= 0 || System.currentTimeMillis() < waitUntil) && !RestartListener.isAllReady()) { Thread.sleep(1000); } } return new HttpRedirect("."); } @CLIMethod(name="cancel-quiet-down") @RequirePOST // TODO the cancel link needs to be updated accordingly public synchronized HttpRedirect doCancelQuietDown() { checkPermission(ADMINISTER); isQuietingDown = false; getQueue().scheduleMaintenance(); return new HttpRedirect("."); } public HttpResponse doToggleCollapse() throws ServletException, IOException { final StaplerRequest request = Stapler.getCurrentRequest(); final String paneId = request.getParameter("paneId"); PaneStatusProperties.forCurrentUser().toggleCollapsed(paneId); return HttpResponses.forwardToPreviousPage(); } /** * Backward compatibility. Redirect to the thread dump. */ public void doClassicThreadDump(StaplerResponse rsp) throws IOException, ServletException { rsp.sendRedirect2("threadDump"); } /** * Obtains the thread dump of all slaves (including the master.) * * <p> * Since this is for diagnostics, it has a built-in precautionary measure against hang slaves. */ public Map<String,Map<String,String>> getAllThreadDumps() throws IOException, InterruptedException { checkPermission(ADMINISTER); // issue the requests all at once Map<String,Future<Map<String,String>>> future = new HashMap<String, Future<Map<String, String>>>(); for (Computer c : getComputers()) { try { future.put(c.getName(), RemotingDiagnostics.getThreadDumpAsync(c.getChannel())); } catch(Exception e) { LOGGER.info("Failed to get thread dump for node " + c.getName() + ": " + e.getMessage()); } } if (toComputer() == null) { future.put("master", RemotingDiagnostics.getThreadDumpAsync(FilePath.localChannel)); } // if the result isn't available in 5 sec, ignore that. // this is a precaution against hang nodes long endTime = System.currentTimeMillis() + 5000; Map<String,Map<String,String>> r = new HashMap<String, Map<String, String>>(); for (Entry<String, Future<Map<String, String>>> e : future.entrySet()) { try { r.put(e.getKey(), e.getValue().get(endTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS)); } catch (Exception x) { StringWriter sw = new StringWriter(); x.printStackTrace(new PrintWriter(sw,true)); r.put(e.getKey(), Collections.singletonMap("Failed to retrieve thread dump",sw.toString())); } } return Collections.unmodifiableSortedMap(new TreeMap<String, Map<String, String>>(r)); } @RequirePOST public synchronized TopLevelItem doCreateItem( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { return itemGroupMixIn.createTopLevelItem(req, rsp); } /** * @since 1.319 */ public TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { return itemGroupMixIn.createProjectFromXML(name, xml); } @SuppressWarnings({"unchecked"}) public <T extends TopLevelItem> T copy(T src, String name) throws IOException { return itemGroupMixIn.copy(src, name); } // a little more convenient overloading that assumes the caller gives us the right type // (or else it will fail with ClassCastException) public <T extends AbstractProject<?,?>> T copy(T src, String name) throws IOException { return (T)copy((TopLevelItem)src,name); } @RequirePOST public synchronized void doCreateView( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { checkPermission(View.CREATE); addView(View.create(req,rsp, this)); } /** * Check if the given name is suitable as a name * for job, view, etc. * * @throws Failure * if the given name is not good */ public static void checkGoodName(String name) throws Failure { if(name==null || name.length()==0) throw new Failure(Messages.Hudson_NoName()); if(".".equals(name.trim())) throw new Failure(Messages.Jenkins_NotAllowedName(".")); if("..".equals(name.trim())) throw new Failure(Messages.Jenkins_NotAllowedName("..")); for( int i=0; i<name.length(); i++ ) { char ch = name.charAt(i); if(Character.isISOControl(ch)) { throw new Failure(Messages.Hudson_ControlCodeNotAllowed(toPrintableName(name))); } if("?*/\\%!@#$^&|<>[]:;".indexOf(ch)!=-1) throw new Failure(Messages.Hudson_UnsafeChar(ch)); } // looks good } /** * Makes sure that the given name is good as a job name. * @return trimmed name if valid; throws Failure if not */ private String checkJobName(String name) throws Failure { checkGoodName(name); name = name.trim(); projectNamingStrategy.checkName(name); if(getItem(name)!=null) throw new Failure(Messages.Hudson_JobAlreadyExists(name)); // looks good return name; } private static String toPrintableName(String name) { StringBuilder printableName = new StringBuilder(); for( int i=0; i<name.length(); i++ ) { char ch = name.charAt(i); if(Character.isISOControl(ch)) printableName.append("\\u").append((int)ch).append(';'); else printableName.append(ch); } return printableName.toString(); } /** * Checks if the user was successfully authenticated. * * @see BasicAuthenticationFilter */ public void doSecured( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { // TODO fire something in SecurityListener? (seems to be used only for REST calls when LegacySecurityRealm is active) if(req.getUserPrincipal()==null) { // authentication must have failed rsp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } // the user is now authenticated, so send him back to the target String path = req.getContextPath()+req.getOriginalRestOfPath(); String q = req.getQueryString(); if(q!=null) path += '?'+q; rsp.sendRedirect2(path); } /** * Called once the user logs in. Just forward to the top page. * Used only by {@link LegacySecurityRealm}. */ public void doLoginEntry( StaplerRequest req, StaplerResponse rsp ) throws IOException { if(req.getUserPrincipal()==null) { rsp.sendRedirect2("noPrincipal"); return; } // TODO fire something in SecurityListener? String from = req.getParameter("from"); if(from!=null && from.startsWith("/") && !from.equals("/loginError")) { rsp.sendRedirect2(from); // I'm bit uncomfortable letting users redircted to other sites, make sure the URL falls into this domain return; } String url = AbstractProcessingFilter.obtainFullRequestUrl(req); if(url!=null) { // if the login redirect is initiated by Acegi // this should send the user back to where s/he was from. rsp.sendRedirect2(url); return; } rsp.sendRedirect2("."); } /** * Logs out the user. */ public void doLogout( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { String user = getAuthentication().getName(); securityRealm.doLogout(req, rsp); SecurityListener.fireLoggedOut(user); } /** * Serves jar files for JNLP slave agents. */ public Slave.JnlpJar getJnlpJars(String fileName) { return new Slave.JnlpJar(fileName); } public Slave.JnlpJar doJnlpJars(StaplerRequest req) { return new Slave.JnlpJar(req.getRestOfPath().substring(1)); } /** * Reloads the configuration. */ @CLIMethod(name="reload-configuration") @RequirePOST public synchronized HttpResponse doReload() throws IOException { checkPermission(ADMINISTER); // engage "loading ..." UI and then run the actual task in a separate thread servletContext.setAttribute("app", new HudsonIsLoading()); new Thread("Jenkins config reload thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); reload(); } catch (Exception e) { LOGGER.log(SEVERE,"Failed to reload Jenkins config",e); new JenkinsReloadFailed(e).publish(servletContext,root); } } }.start(); return HttpResponses.redirectViaContextPath("/"); } /** * Reloads the configuration synchronously. */ public void reload() throws IOException, InterruptedException, ReactorException { executeReactor(null, loadTasks()); User.reload(); servletContext.setAttribute("app", this); } /** * Do a finger-print check. */ public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { // Parse the request MultipartFormDataParser p = new MultipartFormDataParser(req); if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found"); } try { rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+ Util.getDigestOf(p.getFileItem("name").getInputStream())+'/'); } finally { p.cleanUp(); } } /** * For debugging. Expose URL to perform GC. */ @edu.umd.cs.findbugs.annotations.SuppressWarnings("DM_GC") @RequirePOST public void doGc(StaplerResponse rsp) throws IOException { checkPermission(Jenkins.ADMINISTER); System.gc(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("GCed"); } /** * End point that intentionally throws an exception to test the error behaviour. * @since 1.467 */ public void doException() { throw new RuntimeException(); } public ContextMenu doContextMenu(StaplerRequest request, StaplerResponse response) throws IOException, JellyException { ContextMenu menu = new ContextMenu().from(this, request, response); for (MenuItem i : menu.items) { if (i.url.equals(request.getContextPath() + "/manage")) { // add "Manage Jenkins" subitems i.subMenu = new ContextMenu().from(this, request, response, "manage"); } } return menu; } public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception { ContextMenu menu = new ContextMenu(); for (View view : getViews()) { menu.add(view.getViewUrl(),view.getDisplayName()); } return menu; } /** * Obtains the heap dump. */ public HeapDump getHeapDump() throws IOException { return new HeapDump(this,FilePath.localChannel); } /** * Simulates OutOfMemoryError. * Useful to make sure OutOfMemoryHeapDump setting. */ @RequirePOST public void doSimulateOutOfMemory() throws IOException { checkPermission(ADMINISTER); System.out.println("Creating artificial OutOfMemoryError situation"); List<Object> args = new ArrayList<Object>(); while (true) args.add(new byte[1024*1024]); } /** * Binds /userContent/... to $JENKINS_HOME/userContent. */ public DirectoryBrowserSupport doUserContent() { return new DirectoryBrowserSupport(this,getRootPath().child("userContent"),"User content","folder.png",true); } /** * Perform a restart of Jenkins, if we can. * * This first replaces "app" to {@link HudsonIsRestarting} */ @CLIMethod(name="restart") public void doRestart(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, RestartNotSupportedException { checkPermission(ADMINISTER); if (req != null && req.getMethod().equals("GET")) { req.getView(this,"_restart.jelly").forward(req,rsp); return; } restart(); if (rsp != null) // null for CLI rsp.sendRedirect2("."); } /** * Queues up a restart of Jenkins for when there are no builds running, if we can. * * This first replaces "app" to {@link HudsonIsRestarting} * * @since 1.332 */ @CLIMethod(name="safe-restart") public HttpResponse doSafeRestart(StaplerRequest req) throws IOException, ServletException, RestartNotSupportedException { checkPermission(ADMINISTER); if (req != null && req.getMethod().equals("GET")) return HttpResponses.forwardToView(this,"_safeRestart.jelly"); safeRestart(); return HttpResponses.redirectToDot(); } /** * Performs a restart. */ public void restart() throws RestartNotSupportedException { final Lifecycle lifecycle = Lifecycle.get(); lifecycle.verifyRestartable(); // verify that Jenkins is restartable servletContext.setAttribute("app", new HudsonIsRestarting()); new Thread("restart thread") { final String exitUser = getAuthentication().getName(); @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); // give some time for the browser to load the "reloading" page Thread.sleep(5000); LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser)); for (RestartListener listener : RestartListener.all()) listener.onRestart(); lifecycle.restart(); } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e); } } }.start(); } /** * Queues up a restart to be performed once there are no builds currently running. * @since 1.332 */ public void safeRestart() throws RestartNotSupportedException { final Lifecycle lifecycle = Lifecycle.get(); lifecycle.verifyRestartable(); // verify that Jenkins is restartable // Quiet down so that we won't launch new builds. isQuietingDown = true; new Thread("safe-restart thread") { final String exitUser = getAuthentication().getName(); @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); // Wait 'til we have no active executors. doQuietDown(true, 0); // Make sure isQuietingDown is still true. if (isQuietingDown) { servletContext.setAttribute("app",new HudsonIsRestarting()); // give some time for the browser to load the "reloading" page LOGGER.info("Restart in 10 seconds"); Thread.sleep(10000); LOGGER.severe(String.format("Restarting VM as requested by %s",exitUser)); for (RestartListener listener : RestartListener.all()) listener.onRestart(); lifecycle.restart(); } else { LOGGER.info("Safe-restart mode cancelled"); } } catch (Throwable e) { LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e); } } }.start(); } @Extension @Restricted(NoExternalUse.class) public static class MasterRestartNotifyier extends RestartListener { @Override public void onRestart() { Computer computer = Jenkins.getInstance().toComputer(); if (computer == null) return; RestartCause cause = new RestartCause(); for (ComputerListener listener: ComputerListener.all()) { listener.onOffline(computer, cause); } } @Override public boolean isReadyToRestart() throws IOException, InterruptedException { return true; } private static class RestartCause extends OfflineCause.SimpleOfflineCause { protected RestartCause() { super(Messages._Jenkins_IsRestarting()); } } } /** * Shutdown the system. * @since 1.161 */ @CLIMethod(name="shutdown") @RequirePOST public void doExit( StaplerRequest req, StaplerResponse rsp ) throws IOException { checkPermission(ADMINISTER); LOGGER.severe(String.format("Shutting down VM as requested by %s from %s", getAuthentication().getName(), req!=null?req.getRemoteAddr():"???")); if (rsp!=null) { rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); PrintWriter w = rsp.getWriter(); w.println("Shutting down"); w.close(); } System.exit(0); } /** * Shutdown the system safely. * @since 1.332 */ @CLIMethod(name="safe-shutdown") @RequirePOST public HttpResponse doSafeExit(StaplerRequest req) throws IOException { checkPermission(ADMINISTER); isQuietingDown = true; final String exitUser = getAuthentication().getName(); final String exitAddr = req!=null ? req.getRemoteAddr() : "unknown"; new Thread("safe-exit thread") { @Override public void run() { try { ACL.impersonate(ACL.SYSTEM); LOGGER.severe(String.format("Shutting down VM as requested by %s from %s", exitUser, exitAddr)); // Wait 'til we have no active executors. doQuietDown(true, 0); // Make sure isQuietingDown is still true. if (isQuietingDown) { cleanUp(); System.exit(0); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e); } } }.start(); return HttpResponses.plainText("Shutting down as soon as all jobs are complete"); } /** * Gets the {@link Authentication} object that represents the user * associated with the current request. */ public static @Nonnull Authentication getAuthentication() { Authentication a = SecurityContextHolder.getContext().getAuthentication(); // on Tomcat while serving the login page, this is null despite the fact // that we have filters. Looking at the stack trace, Tomcat doesn't seem to // run the request through filters when this is the login request. // see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html if(a==null) a = ANONYMOUS; return a; } /** * For system diagnostics. * Run arbitrary Groovy script. */ public void doScript(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { _doScript(req, rsp, req.getView(this, "_script.jelly"), FilePath.localChannel, getACL()); } /** * Run arbitrary Groovy script and return result as plain text. */ public void doScriptText(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { _doScript(req, rsp, req.getView(this, "_scriptText.jelly"), FilePath.localChannel, getACL()); } /** * @since 1.509.1 */ public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view, VirtualChannel channel, ACL acl) throws IOException, ServletException { // ability to run arbitrary script is dangerous acl.checkPermission(RUN_SCRIPTS); String text = req.getParameter("script"); if (text != null) { if (!"POST".equals(req.getMethod())) { throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST"); } if (channel == null) { throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline"); } try { req.setAttribute("output", RemotingDiagnostics.executeGroovy(text, channel)); } catch (InterruptedException e) { throw new ServletException(e); } } view.forward(req, rsp); } /** * Evaluates the Jelly script submitted by the client. * * This is useful for system administration as well as unit testing. */ @RequirePOST public void doEval(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { checkPermission(RUN_SCRIPTS); try { MetaClass mc = WebApp.getCurrent().getMetaClass(getClass()); Script script = mc.classLoader.loadTearOff(JellyClassLoaderTearOff.class).createContext().compileScript(new InputSource(req.getReader())); new JellyRequestDispatcher(this,script).forward(req,rsp); } catch (JellyException e) { throw new ServletException(e); } } /** * Sign up for the user account. */ public void doSignup( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { if (getSecurityRealm().allowsSignup()) { req.getView(getSecurityRealm(), "signup.jelly").forward(req, rsp); return; } req.getView(SecurityRealm.class, "signup.jelly").forward(req, rsp); } /** * Changes the icon size by changing the cookie */ public void doIconSize( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { String qs = req.getQueryString(); if(qs==null) throw new ServletException(); Cookie cookie = new Cookie("iconSize", Functions.validateIconSize(qs)); cookie.setMaxAge(/* ~4 mo. */9999999); // #762 rsp.addCookie(cookie); String ref = req.getHeader("Referer"); if(ref==null) ref="."; rsp.sendRedirect2(ref); } @RequirePOST public void doFingerprintCleanup(StaplerResponse rsp) throws IOException { FingerprintCleanupThread.invoke(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("Invoked"); } @RequirePOST public void doWorkspaceCleanup(StaplerResponse rsp) throws IOException { WorkspaceCleanupThread.invoke(); rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); rsp.getWriter().println("Invoked"); } /** * If the user chose the default JDK, make sure we got 'java' in PATH. */ public FormValidation doDefaultJDKCheck(StaplerRequest request, @QueryParameter String value) { if(!value.equals(JDK.DEFAULT_NAME)) // assume the user configured named ones properly in system config --- // or else system config should have reported form field validation errors. return FormValidation.ok(); // default JDK selected. Does such java really exist? if(JDK.isDefaultJDKValid(Jenkins.this)) return FormValidation.ok(); else return FormValidation.errorWithMarkup(Messages.Hudson_NoJavaInPath(request.getContextPath())); } /** * Makes sure that the given name is good as a job name. */ public FormValidation doCheckJobName(@QueryParameter String value) { // this method can be used to check if a file exists anywhere in the file system, // so it should be protected. checkPermission(Item.CREATE); if(fixEmpty(value)==null) return FormValidation.ok(); try { checkJobName(value); return FormValidation.ok(); } catch (Failure e) { return FormValidation.error(e.getMessage()); } } /** * Checks if a top-level view with the given name exists and * make sure that the name is good as a view name. */ public FormValidation doCheckViewName(@QueryParameter String value) { checkPermission(View.CREATE); String name = fixEmpty(value); if (name == null) return FormValidation.ok(); // already exists? if (getView(name) != null) return FormValidation.error(Messages.Hudson_ViewAlreadyExists(name)); // good view name? try { checkGoodName(name); } catch (Failure e) { return FormValidation.error(e.getMessage()); } return FormValidation.ok(); } /** * Checks if a top-level view with the given name exists. * @deprecated 1.512 */ @Deprecated public FormValidation doViewExistsCheck(@QueryParameter String value) { checkPermission(View.CREATE); String view = fixEmpty(value); if(view==null) return FormValidation.ok(); if(getView(view)==null) return FormValidation.ok(); else return FormValidation.error(Messages.Hudson_ViewAlreadyExists(view)); } /** * Serves static resources placed along with Jelly view files. * <p> * This method can serve a lot of files, so care needs to be taken * to make this method secure. It's not clear to me what's the best * strategy here, though the current implementation is based on * file extensions. */ public void doResources(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { String path = req.getRestOfPath(); // cut off the "..." portion of /resources/.../path/to/file // as this is only used to make path unique (which in turn // allows us to set a long expiration date path = path.substring(path.indexOf('/',1)+1); int idx = path.lastIndexOf('.'); String extension = path.substring(idx+1); if(ALLOWED_RESOURCE_EXTENSIONS.contains(extension)) { URL url = pluginManager.uberClassLoader.getResource(path); if(url!=null) { long expires = MetaClass.NO_CACHE ? 0 : 365L * 24 * 60 * 60 * 1000; /*1 year*/ rsp.serveFile(req,url,expires); return; } } rsp.sendError(HttpServletResponse.SC_NOT_FOUND); } /** * Extension list that {@link #doResources(StaplerRequest, StaplerResponse)} can serve. * This set is mutable to allow plugins to add additional extensions. */ public static final Set<String> ALLOWED_RESOURCE_EXTENSIONS = new HashSet<String>(Arrays.asList( "js|css|jpeg|jpg|png|gif|html|htm".split("\\|") )); /** * Checks if container uses UTF-8 to decode URLs. See * http://wiki.jenkins-ci.org/display/JENKINS/Tomcat#Tomcat-i18n */ public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException { // expected is non-ASCII String final String expected = "\u57f7\u4e8b"; final String value = fixEmpty(request.getParameter("value")); if (!expected.equals(value)) return FormValidation.warningWithMarkup(Messages.Hudson_NotUsesUTF8ToDecodeURL()); return FormValidation.ok(); } /** * Does not check when system default encoding is "ISO-8859-1". */ public static boolean isCheckURIEncodingEnabled() { return !"ISO-8859-1".equalsIgnoreCase(System.getProperty("file.encoding")); } /** * Rebuilds the dependency map. */ public void rebuildDependencyGraph() { DependencyGraph graph = new DependencyGraph(); graph.build(); // volatile acts a as a memory barrier here and therefore guarantees // that graph is fully build, before it's visible to other threads dependencyGraph = graph; dependencyGraphDirty.set(false); } /** * Rebuilds the dependency map asynchronously. * * <p> * This would keep the UI thread more responsive and helps avoid the deadlocks, * as dependency graph recomputation tends to touch a lot of other things. * * @since 1.522 */ public Future<DependencyGraph> rebuildDependencyGraphAsync() { dependencyGraphDirty.set(true); return Timer.get().schedule(new java.util.concurrent.Callable<DependencyGraph>() { @Override public DependencyGraph call() throws Exception { if (dependencyGraphDirty.get()) { rebuildDependencyGraph(); } return dependencyGraph; } }, 500, TimeUnit.MILLISECONDS); } public DependencyGraph getDependencyGraph() { return dependencyGraph; } // for Jelly public List<ManagementLink> getManagementLinks() { return ManagementLink.all(); } /** * Exposes the current user to <tt>/me</tt> URL. */ public User getMe() { User u = User.current(); if (u == null) throw new AccessDeniedException("/me is not available when not logged in"); return u; } /** * Gets the {@link Widget}s registered on this object. * * <p> * Plugins who wish to contribute boxes on the side panel can add widgets * by {@code getWidgets().add(new MyWidget())} from {@link Plugin#start()}. */ public List<Widget> getWidgets() { return widgets; } public Object getTarget() { try { checkPermission(READ); } catch (AccessDeniedException e) { String rest = Stapler.getCurrentRequest().getRestOfPath(); if(rest.startsWith("/login") || rest.startsWith("/logout") || rest.startsWith("/accessDenied") || rest.startsWith("/adjuncts/") || rest.startsWith("/error") || rest.startsWith("/oops") || rest.startsWith("/signup") || rest.startsWith("/tcpSlaveAgentListener") // TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access || rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt")) || rest.startsWith("/federatedLoginService/") || rest.startsWith("/securityRealm")) return this; // URLs that are always visible without READ permission for (String name : getUnprotectedRootActions()) { if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) { return this; } } throw e; } return this; } /** * Gets a list of unprotected root actions. * These URL prefixes should be exempted from access control checks by container-managed security. * Ideally would be synchronized with {@link #getTarget}. * @return a list of {@linkplain Action#getUrlName URL names} * @since 1.495 */ public Collection<String> getUnprotectedRootActions() { Set<String> names = new TreeSet<String>(); names.add("jnlpJars"); // TODO cleaner to refactor doJnlpJars into a URA // TODO consider caching (expiring cache when actions changes) for (Action a : getActions()) { if (a instanceof UnprotectedRootAction) { names.add(a.getUrlName()); } } return names; } /** * Fallback to the primary view. */ public View getStaplerFallback() { return getPrimaryView(); } /** * This method checks all existing jobs to see if displayName is * unique. It does not check the displayName against the displayName of the * job that the user is configuring though to prevent a validation warning * if the user sets the displayName to what it currently is. * @param displayName * @param currentJobName */ boolean isDisplayNameUnique(String displayName, String currentJobName) { Collection<TopLevelItem> itemCollection = items.values(); // if there are a lot of projects, we'll have to store their // display names in a HashSet or something for a quick check for(TopLevelItem item : itemCollection) { if(item.getName().equals(currentJobName)) { // we won't compare the candidate displayName against the current // item. This is to prevent an validation warning if the user // sets the displayName to what the existing display name is continue; } else if(displayName.equals(item.getDisplayName())) { return false; } } return true; } /** * True if there is no item in Jenkins that has this name * @param name The name to test * @param currentJobName The name of the job that the user is configuring */ boolean isNameUnique(String name, String currentJobName) { Item item = getItem(name); if(null==item) { // the candidate name didn't return any items so the name is unique return true; } else if(item.getName().equals(currentJobName)) { // the candidate name returned an item, but the item is the item // that the user is configuring so this is ok return true; } else { // the candidate name returned an item, so it is not unique return false; } } /** * Checks to see if the candidate displayName collides with any * existing display names or project names * @param displayName The display name to test * @param jobName The name of the job the user is configuring */ public FormValidation doCheckDisplayName(@QueryParameter String displayName, @QueryParameter String jobName) { displayName = displayName.trim(); if(LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Current job name is " + jobName); } if(!isNameUnique(displayName, jobName)) { return FormValidation.warning(Messages.Jenkins_CheckDisplayName_NameNotUniqueWarning(displayName)); } else if(!isDisplayNameUnique(displayName, jobName)){ return FormValidation.warning(Messages.Jenkins_CheckDisplayName_DisplayNameNotUniqueWarning(displayName)); } else { return FormValidation.ok(); } } public static class MasterComputer extends Computer { protected MasterComputer() { super(Jenkins.getInstance()); } /** * Returns "" to match with {@link Jenkins#getNodeName()}. */ @Override public String getName() { return ""; } @Override public boolean isConnecting() { return false; } @Override public String getDisplayName() { return Messages.Hudson_Computer_DisplayName(); } @Override public String getCaption() { return Messages.Hudson_Computer_Caption(); } @Override public String getUrl() { return "computer/(master)/"; } public RetentionStrategy getRetentionStrategy() { return RetentionStrategy.NOOP; } /** * Will always keep this guy alive so that it can function as a fallback to * execute {@link FlyweightTask}s. See JENKINS-7291. */ @Override protected boolean isAlive() { return true; } @Override public Boolean isUnix() { return !Functions.isWindows(); } /** * Report an error. */ @Override public HttpResponse doDoDelete() throws IOException { throw HttpResponses.status(SC_BAD_REQUEST); } @Override public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { Jenkins.getInstance().doConfigExecutorsSubmit(req, rsp); } @WebMethod(name="config.xml") @Override public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { throw HttpResponses.status(SC_BAD_REQUEST); } @Override public boolean hasPermission(Permission permission) { // no one should be allowed to delete the master. // this hides the "delete" link from the /computer/(master) page. if(permission==Computer.DELETE) return false; // Configuration of master node requires ADMINISTER permission return super.hasPermission(permission==Computer.CONFIGURE ? Jenkins.ADMINISTER : permission); } @Override public VirtualChannel getChannel() { return FilePath.localChannel; } @Override public Charset getDefaultCharset() { return Charset.defaultCharset(); } public List<LogRecord> getLogRecords() throws IOException, InterruptedException { return logRecords; } @RequirePOST public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { // this computer never returns null from channel, so // this method shall never be invoked. rsp.sendError(SC_NOT_FOUND); } protected Future<?> _connect(boolean forceReconnect) { return Futures.precomputed(null); } /** * {@link LocalChannel} instance that can be used to execute programs locally. * * @deprecated as of 1.558 * Use {@link FilePath#localChannel} */ @Deprecated public static final LocalChannel localChannel = FilePath.localChannel; } /** * Shortcut for {@code Jenkins.getInstance().lookup.get(type)} */ public static @CheckForNull <T> T lookup(Class<T> type) { Jenkins j = Jenkins.getInstance(); return j != null ? j.lookup.get(type) : null; } /** * Live view of recent {@link LogRecord}s produced by Jenkins. */ public static List<LogRecord> logRecords = Collections.emptyList(); // initialized to dummy value to avoid NPE /** * Thread-safe reusable {@link XStream}. */ public static final XStream XSTREAM; /** * Alias to {@link #XSTREAM} so that one can access additional methods on {@link XStream2} more easily. */ public static final XStream2 XSTREAM2; private static final int TWICE_CPU_NUM = Math.max(4, Runtime.getRuntime().availableProcessors() * 2); /** * Thread pool used to load configuration in parallel, to improve the start up time. * <p> * The idea here is to overlap the CPU and I/O, so we want more threads than CPU numbers. */ /*package*/ transient final ExecutorService threadPoolForLoad = new ThreadPoolExecutor( TWICE_CPU_NUM, TWICE_CPU_NUM, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamingThreadFactory(new DaemonThreadFactory(), "Jenkins load")); private static void computeVersion(ServletContext context) { // set the version Properties props = new Properties(); InputStream is = null; try { is = Jenkins.class.getResourceAsStream("jenkins-version.properties"); if(is!=null) props.load(is); } catch (IOException e) { e.printStackTrace(); // if the version properties is missing, that's OK. } finally { IOUtils.closeQuietly(is); } String ver = props.getProperty("version"); if(ver==null) ver="?"; VERSION = ver; context.setAttribute("version",ver); VERSION_HASH = Util.getDigestOf(ver).substring(0, 8); SESSION_HASH = Util.getDigestOf(ver+System.currentTimeMillis()).substring(0, 8); if(ver.equals("?") || Boolean.getBoolean("hudson.script.noCache")) RESOURCE_PATH = ""; else RESOURCE_PATH = "/static/"+SESSION_HASH; VIEW_RESOURCE_PATH = "/resources/"+ SESSION_HASH; } /** * Version number of this Jenkins. */ public static String VERSION="?"; /** * Parses {@link #VERSION} into {@link VersionNumber}, or null if it's not parseable as a version number * (such as when Jenkins is run with "mvn hudson-dev:run") */ public static VersionNumber getVersion() { try { return new VersionNumber(VERSION); } catch (NumberFormatException e) { try { // for non-released version of Jenkins, this looks like "1.345 (private-foobar), so try to approximate. int idx = VERSION.indexOf(' '); if (idx>0) return new VersionNumber(VERSION.substring(0,idx)); } catch (NumberFormatException _) { // fall through } // totally unparseable return null; } catch (IllegalArgumentException e) { // totally unparseable return null; } } /** * Hash of {@link #VERSION}. */ public static String VERSION_HASH; /** * Unique random token that identifies the current session. * Used to make {@link #RESOURCE_PATH} unique so that we can set long "Expires" header. * * We used to use {@link #VERSION_HASH}, but making this session local allows us to * reuse the same {@link #RESOURCE_PATH} for static resources in plugins. */ public static String SESSION_HASH; /** * Prefix to static resources like images and javascripts in the war file. * Either "" or strings like "/static/VERSION", which avoids Jenkins to pick up * stale cache when the user upgrades to a different version. * <p> * Value computed in {@link WebAppMain}. */ public static String RESOURCE_PATH = ""; /** * Prefix to resources alongside view scripts. * Strings like "/resources/VERSION", which avoids Jenkins to pick up * stale cache when the user upgrades to a different version. * <p> * Value computed in {@link WebAppMain}. */ public static String VIEW_RESOURCE_PATH = "/resources/TBD"; public static boolean PARALLEL_LOAD = Configuration.getBooleanConfigParameter("parallelLoad", true); public static boolean KILL_AFTER_LOAD = Configuration.getBooleanConfigParameter("killAfterLoad", false); /** * @deprecated No longer used. */ @Deprecated public static boolean FLYWEIGHT_SUPPORT = true; /** * Tentative switch to activate the concurrent build behavior. * When we merge this back to the trunk, this allows us to keep * this feature hidden for a while until we iron out the kinks. * @see AbstractProject#isConcurrentBuild() * @deprecated as of 1.464 * This flag will have no effect. */ @Restricted(NoExternalUse.class) @Deprecated public static boolean CONCURRENT_BUILD = true; /** * Switch to enable people to use a shorter workspace name. */ private static final String WORKSPACE_DIRNAME = Configuration.getStringConfigParameter("workspaceDirName", "workspace"); /** * Automatically try to launch a slave when Jenkins is initialized or a new slave is created. */ public static boolean AUTOMATIC_SLAVE_LAUNCH = true; private static final Logger LOGGER = Logger.getLogger(Jenkins.class.getName()); public static final PermissionGroup PERMISSIONS = Permission.HUDSON_PERMISSIONS; public static final Permission ADMINISTER = Permission.HUDSON_ADMINISTER; public static final Permission READ = new Permission(PERMISSIONS,"Read",Messages._Hudson_ReadPermission_Description(),Permission.READ,PermissionScope.JENKINS); public static final Permission RUN_SCRIPTS = new Permission(PERMISSIONS, "RunScripts", Messages._Hudson_RunScriptsPermission_Description(),ADMINISTER,PermissionScope.JENKINS); /** * {@link Authentication} object that represents the anonymous user. * Because Acegi creates its own {@link AnonymousAuthenticationToken} instances, the code must not * expect the singleton semantics. This is just a convenient instance. * * @since 1.343 */ public static final Authentication ANONYMOUS; static { try { ANONYMOUS = new AnonymousAuthenticationToken( "anonymous", "anonymous", new GrantedAuthority[]{new GrantedAuthorityImpl("anonymous")}); XSTREAM = XSTREAM2 = new XStream2(); XSTREAM.alias("jenkins", Jenkins.class); XSTREAM.alias("slave", DumbSlave.class); XSTREAM.alias("jdk", JDK.class); // for backward compatibility with <1.75, recognize the tag name "view" as well. XSTREAM.alias("view", ListView.class); XSTREAM.alias("listView", ListView.class); XSTREAM2.addCriticalField(Jenkins.class, "securityRealm"); XSTREAM2.addCriticalField(Jenkins.class, "authorizationStrategy"); // this seems to be necessary to force registration of converter early enough Mode.class.getEnumConstants(); // double check that initialization order didn't do any harm assert PERMISSIONS != null; assert ADMINISTER != null; } catch (RuntimeException e) { // when loaded on a slave and this fails, subsequent NoClassDefFoundError will fail to chain the cause. // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8051847 // As we don't know where the first exception will go, let's also send this to logging so that // we have a known place to look at. LOGGER.log(SEVERE, "Failed to load Jenkins.class", e); throw e; } catch (Error e) { LOGGER.log(SEVERE, "Failed to load Jenkins.class", e); throw e; } } }
./CrossVul/dataset_final_sorted/CWE-269/java/bad_3057_0
crossvul-java_data_bad_1947_3
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.search.impl.persistence; import static org.opencastproject.security.api.Permissions.Action.CONTRIBUTE; import static org.opencastproject.security.api.Permissions.Action.READ; import static org.opencastproject.security.api.Permissions.Action.WRITE; import org.opencastproject.mediapackage.MediaPackage; import org.opencastproject.mediapackage.MediaPackageParser; import org.opencastproject.security.api.AccessControlList; import org.opencastproject.security.api.AccessControlParser; import org.opencastproject.security.api.AccessControlUtil; import org.opencastproject.security.api.Organization; import org.opencastproject.security.api.SecurityService; import org.opencastproject.security.api.UnauthorizedException; import org.opencastproject.security.api.User; import org.opencastproject.util.NotFoundException; import org.opencastproject.util.data.Tuple; import org.apache.commons.lang3.StringUtils; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.NoResultException; import javax.persistence.Query; import javax.persistence.TypedQuery; /** * Implements {@link SearchServiceDatabase}. Defines permanent storage for series. */ public class SearchServiceDatabaseImpl implements SearchServiceDatabase { /** JPA persistence unit name */ public static final String PERSISTENCE_UNIT = "org.opencastproject.search.impl.persistence"; /** Logging utilities */ private static final Logger logger = LoggerFactory.getLogger(SearchServiceDatabaseImpl.class); /** Factory used to create {@link EntityManager}s for transactions */ protected EntityManagerFactory emf; /** The security service */ protected SecurityService securityService; /** OSGi DI */ public void setEntityManagerFactory(EntityManagerFactory emf) { this.emf = emf; } /** * Creates {@link EntityManagerFactory} using persistence provider and properties passed via OSGi. * * @param cc * @throws SearchServiceDatabaseException */ public void activate(ComponentContext cc) throws SearchServiceDatabaseException { logger.info("Activating persistence manager for search service"); this.populateSeriesData(); } /** * OSGi callback to set the security service. * * @param securityService * the securityService to set */ public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } private void populateSeriesData() throws SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); TypedQuery<SearchEntity> q = (TypedQuery<SearchEntity>) em.createNamedQuery("Search.getNoSeries"); List<SearchEntity> seriesList = q.getResultList(); for (SearchEntity series : seriesList) { String mpSeriesId = MediaPackageParser.getFromXml(series.getMediaPackageXML()).getSeries(); if (StringUtils.isNotBlank(mpSeriesId) && !mpSeriesId.equals(series.getSeriesId())) { logger.info("Fixing missing series ID for episode {}, series is {}", series.getMediaPackageId(), mpSeriesId); series.setSeriesId(mpSeriesId); em.merge(series); } } tx.commit(); } catch (Exception e) { logger.error("Could not update media package: {}", e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#deleteMediaPackage(String, Date) */ @Override public void deleteMediaPackage(String mediaPackageId, Date deletionDate) throws SearchServiceDatabaseException, NotFoundException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to delete this episode String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, WRITE.toString())) throw new UnauthorizedException(currentUser + " is not authorized to delete media package " + mediaPackageId); searchEntity.setDeletionDate(deletionDate); em.merge(searchEntity); } tx.commit(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not delete episode {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#countMediaPackages() */ @Override public int countMediaPackages() throws SearchServiceDatabaseException { EntityManager em = emf.createEntityManager(); Query query = em.createNamedQuery("Search.getCount"); try { Long total = (Long) query.getSingleResult(); return total.intValue(); } catch (Exception e) { logger.error("Could not find number of mediapackages", e); throw new SearchServiceDatabaseException(e); } finally { em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getAllMediaPackages() */ @Override @SuppressWarnings("unchecked") public Iterator<Tuple<MediaPackage, String>> getAllMediaPackages() throws SearchServiceDatabaseException { List<SearchEntity> searchEntities = null; EntityManager em = null; try { em = emf.createEntityManager(); Query query = em.createNamedQuery("Search.findAll"); searchEntities = (List<SearchEntity>) query.getResultList(); } catch (Exception e) { logger.error("Could not retrieve all episodes: {}", e.getMessage()); throw new SearchServiceDatabaseException(e); } finally { em.close(); } List<Tuple<MediaPackage, String>> mediaPackageList = new LinkedList<Tuple<MediaPackage, String>>(); try { for (SearchEntity entity : searchEntities) { MediaPackage mediaPackage = MediaPackageParser.getFromXml(entity.getMediaPackageXML()); mediaPackageList.add(Tuple.tuple(mediaPackage, entity.getOrganization().getId())); } } catch (Exception e) { logger.error("Could not parse series entity: {}", e.getMessage()); throw new SearchServiceDatabaseException(e); } return mediaPackageList.iterator(); } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getAccessControlList(String) */ @Override public AccessControlList getAccessControlList(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; try { em = emf.createEntityManager(); SearchEntity entity = getSearchEntity(mediaPackageId, em); if (entity == null) { throw new NotFoundException("Could not found media package with ID " + mediaPackageId); } if (entity.getAccessControl() == null) { return null; } else { return AccessControlParser.parseAcl(entity.getAccessControl()); } } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not retrieve ACL {}: {}", mediaPackageId, e.getMessage()); throw new SearchServiceDatabaseException(e); } finally { em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#storeMediaPackage(MediaPackage, * AccessControlList, Date) */ @Override public void storeMediaPackage(MediaPackage mediaPackage, AccessControlList acl, Date now) throws SearchServiceDatabaseException, UnauthorizedException { String mediaPackageXML = MediaPackageParser.getAsXml(mediaPackage); String mediaPackageId = mediaPackage.getIdentifier().toString(); EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity entity = getSearchEntity(mediaPackageId, em); if (entity == null) { // Create new search entity SearchEntity searchEntity = new SearchEntity(); searchEntity.setOrganization(securityService.getOrganization()); searchEntity.setMediaPackageId(mediaPackageId); searchEntity.setMediaPackageXML(mediaPackageXML); searchEntity.setAccessControl(AccessControlParser.toXml(acl)); searchEntity.setModificationDate(now); searchEntity.setSeriesId(mediaPackage.getSeries()); em.persist(searchEntity); } else { // Ensure this user is allowed to update this media package String accessControlXml = entity.getAccessControl(); if (accessControlXml != null) { AccessControlList accessList = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(accessList, currentUser, currentOrg, WRITE.toString())) { throw new UnauthorizedException(currentUser + " is not authorized to update media package " + mediaPackageId); } } entity.setOrganization(securityService.getOrganization()); entity.setMediaPackageId(mediaPackageId); entity.setMediaPackageXML(mediaPackageXML); entity.setAccessControl(AccessControlParser.toXml(acl)); entity.setModificationDate(now); entity.setDeletionDate(null); entity.setSeriesId(mediaPackage.getSeries()); em.merge(entity); } tx.commit(); } catch (Exception e) { logger.error("Could not update media package: {}", e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getMediaPackage(String) */ @Override public MediaPackage getMediaPackage(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity episodeEntity = getSearchEntity(mediaPackageId, em); if (episodeEntity == null) throw new NotFoundException("No episode with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to read this episode String accessControlXml = episodeEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); // There are several reasons a user may need to load a episode: to read content, to edit it, or add content if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString()) && !AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, CONTRIBUTE.toString()) && !AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, WRITE.toString())) { throw new UnauthorizedException(currentUser + " is not authorized to see episode " + mediaPackageId); } } return MediaPackageParser.getFromXml(episodeEntity.getMediaPackageXML()); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get episode {} from database: {} ", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getModificationDate(String) */ @Override public Date getModificationDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to read this media package String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString())) throw new UnauthorizedException(currentUser + " is not authorized to read media package " + mediaPackageId); } return searchEntity.getModificationDate(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get modification date {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getDeletionDate(String) */ @Override public Date getDeletionDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) { throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); } // Ensure this user is allowed to read this media package String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString())) throw new UnauthorizedException(currentUser + " is not authorized to read media package " + mediaPackageId); } return searchEntity.getDeletionDate(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get deletion date {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getOrganizationId(String) */ @Override public String getOrganizationId(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to read this media package String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString())) throw new UnauthorizedException(currentUser + " is not authorized to read media package " + mediaPackageId); } return searchEntity.getOrganization().getId(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get deletion date {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * Gets a search entity by it's id, using the current organizational context. * * @param id * the media package identifier * @param em * an open entity manager * @return the search entity, or null if not found */ private SearchEntity getSearchEntity(String id, EntityManager em) { Query q = em.createNamedQuery("Search.findById").setParameter("mediaPackageId", id); try { return (SearchEntity) q.getSingleResult(); } catch (NoResultException e) { return null; } } }
./CrossVul/dataset_final_sorted/CWE-863/java/bad_1947_3
crossvul-java_data_bad_4545_2
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.exec.internal; import static org.openhab.binding.exec.internal.ExecBindingConstants.THING_COMMAND; import java.util.Collections; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.binding.BaseThingHandlerFactory; import org.eclipse.smarthome.core.thing.binding.ThingHandler; import org.eclipse.smarthome.core.thing.binding.ThingHandlerFactory; import org.openhab.binding.exec.internal.handler.ExecHandler; import org.osgi.service.component.annotations.Component; /** * The {@link ExecHandlerFactory} is responsible for creating things and thing * handlers. * * @author Karel Goderis - Initial contribution */ @NonNullByDefault @Component(service = ThingHandlerFactory.class, configurationPid = "binding.exec") public class ExecHandlerFactory extends BaseThingHandlerFactory { private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_COMMAND); @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { return SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID); } @Override protected @Nullable ThingHandler createHandler(Thing thing) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (thingTypeUID.equals(THING_COMMAND)) { return new ExecHandler(thing); } return null; } }
./CrossVul/dataset_final_sorted/CWE-863/java/bad_4545_2
crossvul-java_data_good_1947_3
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.search.impl.persistence; import static org.opencastproject.security.api.Permissions.Action.CONTRIBUTE; import static org.opencastproject.security.api.Permissions.Action.READ; import static org.opencastproject.security.api.Permissions.Action.WRITE; import org.opencastproject.mediapackage.MediaPackage; import org.opencastproject.mediapackage.MediaPackageException; import org.opencastproject.mediapackage.MediaPackageParser; import org.opencastproject.security.api.AccessControlList; import org.opencastproject.security.api.AccessControlParser; import org.opencastproject.security.api.AccessControlParsingException; import org.opencastproject.security.api.AccessControlUtil; import org.opencastproject.security.api.Organization; import org.opencastproject.security.api.SecurityService; import org.opencastproject.security.api.UnauthorizedException; import org.opencastproject.security.api.User; import org.opencastproject.util.NotFoundException; import org.opencastproject.util.data.Tuple; import org.apache.commons.lang3.StringUtils; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.NoResultException; import javax.persistence.Query; import javax.persistence.TypedQuery; /** * Implements {@link SearchServiceDatabase}. Defines permanent storage for series. */ public class SearchServiceDatabaseImpl implements SearchServiceDatabase { /** JPA persistence unit name */ public static final String PERSISTENCE_UNIT = "org.opencastproject.search.impl.persistence"; /** Logging utilities */ private static final Logger logger = LoggerFactory.getLogger(SearchServiceDatabaseImpl.class); /** Factory used to create {@link EntityManager}s for transactions */ protected EntityManagerFactory emf; /** The security service */ protected SecurityService securityService; /** OSGi DI */ public void setEntityManagerFactory(EntityManagerFactory emf) { this.emf = emf; } /** * Creates {@link EntityManagerFactory} using persistence provider and properties passed via OSGi. * * @param cc * @throws SearchServiceDatabaseException */ public void activate(ComponentContext cc) throws SearchServiceDatabaseException { logger.info("Activating persistence manager for search service"); this.populateSeriesData(); } /** * OSGi callback to set the security service. * * @param securityService * the securityService to set */ public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } private void populateSeriesData() throws SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); TypedQuery<SearchEntity> q = (TypedQuery<SearchEntity>) em.createNamedQuery("Search.getNoSeries"); List<SearchEntity> seriesList = q.getResultList(); for (SearchEntity series : seriesList) { String mpSeriesId = MediaPackageParser.getFromXml(series.getMediaPackageXML()).getSeries(); if (StringUtils.isNotBlank(mpSeriesId) && !mpSeriesId.equals(series.getSeriesId())) { logger.info("Fixing missing series ID for episode {}, series is {}", series.getMediaPackageId(), mpSeriesId); series.setSeriesId(mpSeriesId); em.merge(series); } } tx.commit(); } catch (Exception e) { logger.error("Could not update media package: {}", e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#deleteMediaPackage(String, Date) */ @Override public void deleteMediaPackage(String mediaPackageId, Date deletionDate) throws SearchServiceDatabaseException, NotFoundException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to delete this episode String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, WRITE.toString())) throw new UnauthorizedException(currentUser + " is not authorized to delete media package " + mediaPackageId); searchEntity.setDeletionDate(deletionDate); em.merge(searchEntity); } tx.commit(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not delete episode {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#countMediaPackages() */ @Override public int countMediaPackages() throws SearchServiceDatabaseException { EntityManager em = emf.createEntityManager(); Query query = em.createNamedQuery("Search.getCount"); try { Long total = (Long) query.getSingleResult(); return total.intValue(); } catch (Exception e) { logger.error("Could not find number of mediapackages", e); throw new SearchServiceDatabaseException(e); } finally { em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getAllMediaPackages() */ @Override @SuppressWarnings("unchecked") public Iterator<Tuple<MediaPackage, String>> getAllMediaPackages() throws SearchServiceDatabaseException { List<SearchEntity> searchEntities = null; EntityManager em = null; try { em = emf.createEntityManager(); Query query = em.createNamedQuery("Search.findAll"); searchEntities = (List<SearchEntity>) query.getResultList(); } catch (Exception e) { logger.error("Could not retrieve all episodes: {}", e.getMessage()); throw new SearchServiceDatabaseException(e); } finally { em.close(); } List<Tuple<MediaPackage, String>> mediaPackageList = new LinkedList<Tuple<MediaPackage, String>>(); try { for (SearchEntity entity : searchEntities) { MediaPackage mediaPackage = MediaPackageParser.getFromXml(entity.getMediaPackageXML()); mediaPackageList.add(Tuple.tuple(mediaPackage, entity.getOrganization().getId())); } } catch (Exception e) { logger.error("Could not parse series entity: {}", e.getMessage()); throw new SearchServiceDatabaseException(e); } return mediaPackageList.iterator(); } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getAccessControlList(String) */ @Override public AccessControlList getAccessControlList(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; try { em = emf.createEntityManager(); SearchEntity entity = getSearchEntity(mediaPackageId, em); if (entity == null) { throw new NotFoundException("Could not found media package with ID " + mediaPackageId); } if (entity.getAccessControl() == null) { return null; } else { return AccessControlParser.parseAcl(entity.getAccessControl()); } } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not retrieve ACL {}", mediaPackageId, e); throw new SearchServiceDatabaseException(e); } finally { em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getAccessControlLists(String, String...) */ @Override public Collection<AccessControlList> getAccessControlLists(final String seriesId, String ... excludeIds) throws SearchServiceDatabaseException { List<String> excludes = Arrays.asList(excludeIds); List<AccessControlList> accessControlLists = new ArrayList<>(); EntityManager em = emf.createEntityManager(); TypedQuery<SearchEntity> q = em.createNamedQuery("Search.findBySeriesId", SearchEntity.class) .setParameter("seriesId", seriesId); try { for (SearchEntity entity: q.getResultList()) { if (entity.getAccessControl() != null && !excludes.contains(entity.getMediaPackageId())) { accessControlLists.add(AccessControlParser.parseAcl(entity.getAccessControl())); } } } catch (IOException | AccessControlParsingException e) { throw new SearchServiceDatabaseException(e); } finally { em.close(); } return accessControlLists; } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getMediaPackages(String) */ @Override public Collection<MediaPackage> getMediaPackages(final String seriesId) throws SearchServiceDatabaseException { List<MediaPackage> episodes = new ArrayList<>(); EntityManager em = emf.createEntityManager(); TypedQuery<SearchEntity> q = em.createNamedQuery("Search.findBySeriesId", SearchEntity.class) .setParameter("seriesId", seriesId); try { for (SearchEntity entity: q.getResultList()) { if (entity.getMediaPackageXML() != null) { episodes.add(MediaPackageParser.getFromXml(entity.getMediaPackageXML())); } } } catch (MediaPackageException e) { throw new SearchServiceDatabaseException(e); } finally { em.close(); } return episodes; } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#storeMediaPackage(MediaPackage, * AccessControlList, Date) */ @Override public void storeMediaPackage(MediaPackage mediaPackage, AccessControlList acl, Date now) throws SearchServiceDatabaseException, UnauthorizedException { String mediaPackageXML = MediaPackageParser.getAsXml(mediaPackage); String mediaPackageId = mediaPackage.getIdentifier().toString(); EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity entity = getSearchEntity(mediaPackageId, em); if (entity == null) { // Create new search entity SearchEntity searchEntity = new SearchEntity(); searchEntity.setOrganization(securityService.getOrganization()); searchEntity.setMediaPackageId(mediaPackageId); searchEntity.setMediaPackageXML(mediaPackageXML); searchEntity.setAccessControl(AccessControlParser.toXml(acl)); searchEntity.setModificationDate(now); searchEntity.setSeriesId(mediaPackage.getSeries()); em.persist(searchEntity); } else { // Ensure this user is allowed to update this media package String accessControlXml = entity.getAccessControl(); if (accessControlXml != null) { AccessControlList accessList = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(accessList, currentUser, currentOrg, WRITE.toString())) { throw new UnauthorizedException(currentUser + " is not authorized to update media package " + mediaPackageId); } } entity.setOrganization(securityService.getOrganization()); entity.setMediaPackageId(mediaPackageId); entity.setMediaPackageXML(mediaPackageXML); entity.setAccessControl(AccessControlParser.toXml(acl)); entity.setModificationDate(now); entity.setDeletionDate(null); entity.setSeriesId(mediaPackage.getSeries()); em.merge(entity); } tx.commit(); } catch (Exception e) { logger.error("Could not update media package: {}", e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getMediaPackage(String) */ @Override public MediaPackage getMediaPackage(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity episodeEntity = getSearchEntity(mediaPackageId, em); if (episodeEntity == null) throw new NotFoundException("No episode with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to read this episode String accessControlXml = episodeEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); // There are several reasons a user may need to load a episode: to read content, to edit it, or add content if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString()) && !AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, CONTRIBUTE.toString()) && !AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, WRITE.toString())) { throw new UnauthorizedException(currentUser + " is not authorized to see episode " + mediaPackageId); } } return MediaPackageParser.getFromXml(episodeEntity.getMediaPackageXML()); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get episode {} from database: {} ", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getModificationDate(String) */ @Override public Date getModificationDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to read this media package String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString())) throw new UnauthorizedException(currentUser + " is not authorized to read media package " + mediaPackageId); } return searchEntity.getModificationDate(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get modification date {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getDeletionDate(String) */ @Override public Date getDeletionDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) { throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); } // Ensure this user is allowed to read this media package String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString())) throw new UnauthorizedException(currentUser + " is not authorized to read media package " + mediaPackageId); } return searchEntity.getDeletionDate(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get deletion date {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * {@inheritDoc} * * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getOrganizationId(String) */ @Override public String getOrganizationId(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); SearchEntity searchEntity = getSearchEntity(mediaPackageId, em); if (searchEntity == null) throw new NotFoundException("No media package with id=" + mediaPackageId + " exists"); // Ensure this user is allowed to read this media package String accessControlXml = searchEntity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString())) throw new UnauthorizedException(currentUser + " is not authorized to read media package " + mediaPackageId); } return searchEntity.getOrganization().getId(); } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not get deletion date {}: {}", mediaPackageId, e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SearchServiceDatabaseException(e); } finally { if (em != null) em.close(); } } /** * Gets a search entity by it's id, using the current organizational context. * * @param id * the media package identifier * @param em * an open entity manager * @return the search entity, or null if not found */ private SearchEntity getSearchEntity(String id, EntityManager em) { Query q = em.createNamedQuery("Search.findById").setParameter("mediaPackageId", id); try { return (SearchEntity) q.getSingleResult(); } catch (NoResultException e) { return null; } } }
./CrossVul/dataset_final_sorted/CWE-863/java/good_1947_3
crossvul-java_data_good_4545_3
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.exec.internal; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.config.core.ConfigConstants; import org.eclipse.smarthome.core.service.AbstractWatchService; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.WatchEvent; import java.util.HashSet; import java.util.Set; import static java.nio.file.StandardWatchEventKinds.*; /** * The {@link ExecWhitelistWatchService} provides a whitelist check for exec commands * * @author Jan N. Klug - Initial contribution */ @Component(service = ExecWhitelistWatchService.class) @NonNullByDefault public class ExecWhitelistWatchService extends AbstractWatchService { private static final String COMMAND_WHITELIST_PATH = ConfigConstants.getConfigFolder() + File.separator + "misc"; private static final String COMMAND_WHITELIST_FILE = "exec.whitelist"; private final Set<String> commandWhitelist = new HashSet<>(); @Activate public ExecWhitelistWatchService() { super(COMMAND_WHITELIST_PATH); } @Override protected boolean watchSubDirectories() { return false; } @Override protected WatchEvent.Kind<?>[] getWatchEventKinds(@Nullable Path directory) { return new WatchEvent.Kind<?>[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY }; } @Override protected void processWatchEvent(@Nullable WatchEvent<?> event, WatchEvent.@Nullable Kind<?> kind, @Nullable Path path) { if (path.endsWith(COMMAND_WHITELIST_FILE)) { commandWhitelist.clear(); try { Files.lines(path).forEach(commandWhitelist::add); logger.debug("Updated command whitelist: {}", commandWhitelist); } catch (IOException e) { logger.warn("Cannot read whitelist file, exec binding commands won't be processed: {}", e.getMessage()); } } } /** * Check if a command is whitelisted * * @param command the command to check alias * @return true if whitelisted, false if not */ public boolean isWhitelisted(String command) { return commandWhitelist.contains(command); } }
./CrossVul/dataset_final_sorted/CWE-863/java/good_4545_3
crossvul-java_data_bad_3865_0
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2013, 2014, 2016 Synacor, Inc. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software Foundation, * version 2 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. * ***** END LICENSE BLOCK ***** */ package com.zimbra.cs.service.account; import java.util.Map; import com.zimbra.common.service.ServiceException; import com.zimbra.common.soap.AccountConstants; import com.zimbra.common.soap.Element; import com.zimbra.cs.account.Account; import com.zimbra.cs.account.Provisioning; import com.zimbra.cs.gal.GalSearchControl; import com.zimbra.cs.gal.GalSearchParams; import com.zimbra.soap.ZimbraSoapContext; import com.zimbra.soap.type.GalSearchType; /** * @since May 26, 2004 * @author schemers */ public class AutoCompleteGal extends GalDocumentHandler { @Override public Element handle(Element request, Map<String, Object> context) throws ServiceException { ZimbraSoapContext zsc = getZimbraSoapContext(context); Account account = getRequestedAccount(getZimbraSoapContext(context)); if (!canAccessAccount(zsc, account)) throw ServiceException.PERM_DENIED("can not access account"); String name = request.getAttribute(AccountConstants.E_NAME); String typeStr = request.getAttribute(AccountConstants.A_TYPE, "account"); GalSearchType type = GalSearchType.fromString(typeStr); boolean needCanExpand = request.getAttributeBool(AccountConstants.A_NEED_EXP, false); String galAcctId = request.getAttribute(AccountConstants.A_GAL_ACCOUNT_ID, null); GalSearchParams params = new GalSearchParams(account, zsc); params.setType(type); params.setRequest(request); params.setQuery(name); params.setLimit(account.getContactAutoCompleteMaxResults()); params.setNeedCanExpand(needCanExpand); params.setResponseName(AccountConstants.AUTO_COMPLETE_GAL_RESPONSE); if (galAcctId != null) params.setGalSyncAccount(Provisioning.getInstance().getAccountById(galAcctId)); GalSearchControl gal = new GalSearchControl(params); gal.autocomplete(); return params.getResultCallback().getResponse(); } @Override public boolean needsAuth(Map<String, Object> context) { return true; } }
./CrossVul/dataset_final_sorted/CWE-863/java/bad_3865_0
crossvul-java_data_good_1947_1
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.search.impl.persistence; import org.opencastproject.security.api.Organization; import org.opencastproject.security.impl.jpa.JpaOrganization; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * Entity object for storing search in persistence storage. Media package id is stored as primary key. */ @Entity(name = "SearchEntity") @Table(name = "oc_search", indexes = { @Index(name = "IX_oc_search_series", columnList = ("series_id")), @Index(name = "IX_oc_search_organization", columnList = ("organization")) }) @NamedQueries({ @NamedQuery(name = "Search.findAll", query = "SELECT s FROM SearchEntity s"), @NamedQuery(name = "Search.getCount", query = "SELECT COUNT(s) FROM SearchEntity s"), @NamedQuery(name = "Search.findById", query = "SELECT s FROM SearchEntity s WHERE s.mediaPackageId=:mediaPackageId"), @NamedQuery(name = "Search.findBySeriesId", query = "SELECT s FROM SearchEntity s WHERE s.seriesId=:seriesId and " + "s.deletionDate is null"), @NamedQuery(name = "Search.getNoSeries", query = "SELECT s FROM SearchEntity s WHERE s.seriesId IS NULL")}) public class SearchEntity { /** media package id, primary key */ @Id @Column(name = "id", length = 128) private String mediaPackageId; @Column(name = "series_id", length = 128) protected String seriesId; /** Organization id */ @OneToOne(targetEntity = JpaOrganization.class) @JoinColumn(name = "organization", referencedColumnName = "id") protected JpaOrganization organization; /** The media package deleted */ @Column(name = "deletion_date") @Temporal(TemporalType.TIMESTAMP) private Date deletionDate; /** The media package deleted */ @Column(name = "modification_date") @Temporal(TemporalType.TIMESTAMP) private Date modificationDate; /** Serialized media package */ @Lob @Column(name = "mediapackage_xml", length = 65535) private String mediaPackageXML; /** Serialized access control */ @Lob @Column(name = "access_control", length = 65535) protected String accessControl; /** * Default constructor without any import. */ public SearchEntity() { } /** * Returns media package id. * * @return media package id */ public String getMediaPackageId() { return mediaPackageId; } /** * Sets media package id. Id length limit is 128 charachters. * * @param mediaPackageId */ public void setMediaPackageId(String mediaPackageId) { this.mediaPackageId = mediaPackageId; } /** * Returns serialized media package. * * @return serialized media package */ public String getMediaPackageXML() { return mediaPackageXML; } /** * Sets serialized media package * * @param mediaPackageXML */ public void setMediaPackageXML(String mediaPackageXML) { this.mediaPackageXML = mediaPackageXML; } /** * Returns serialized access control * * @return serialized access control */ public String getAccessControl() { return accessControl; } /** * Sets serialized access control. * * @param accessControl * serialized access control */ public void setAccessControl(String accessControl) { this.accessControl = accessControl; } /** * @return the organization */ public JpaOrganization getOrganization() { return organization; } /** * @param organization * the organization to set */ public void setOrganization(Organization organization) { if (organization instanceof JpaOrganization) { this.organization = (JpaOrganization) organization; } else { this.organization = new JpaOrganization(organization.getId(), organization.getName(), organization.getServers(), organization.getAdminRole(), organization.getAnonymousRole(), organization.getProperties()); } } /** * @return the deletion date */ public Date getDeletionDate() { return deletionDate; } /** * Sets the deletion date * * @param deletionDate * the deletion date */ public void setDeletionDate(Date deletionDate) { this.deletionDate = deletionDate; } /** * @return the modification date */ public Date getModificationDate() { return modificationDate; } /** * Sets the modification date * * @param modificationDate * the modification date */ public void setModificationDate(Date modificationDate) { this.modificationDate = modificationDate; } /** * @return the series Id for this search entry */ public String getSeriesId() { return seriesId; } /** * Sets the series ID * * @param seriesId * the series ID */ public void setSeriesId(String seriesId) { this.seriesId = seriesId; } }
./CrossVul/dataset_final_sorted/CWE-863/java/good_1947_1
crossvul-java_data_good_1947_0
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.search.impl; import static org.opencastproject.security.api.SecurityConstants.GLOBAL_ADMIN_ROLE; import org.opencastproject.job.api.AbstractJobProducer; import org.opencastproject.job.api.Job; import org.opencastproject.mediapackage.MediaPackage; import org.opencastproject.mediapackage.MediaPackageException; import org.opencastproject.mediapackage.MediaPackageParser; import org.opencastproject.mediapackage.MediaPackageSerializer; import org.opencastproject.metadata.api.StaticMetadataService; import org.opencastproject.metadata.mpeg7.Mpeg7CatalogService; import org.opencastproject.search.api.SearchException; import org.opencastproject.search.api.SearchQuery; import org.opencastproject.search.api.SearchResult; import org.opencastproject.search.api.SearchService; import org.opencastproject.search.impl.persistence.SearchServiceDatabase; import org.opencastproject.search.impl.persistence.SearchServiceDatabaseException; import org.opencastproject.search.impl.solr.SolrIndexManager; import org.opencastproject.search.impl.solr.SolrRequester; import org.opencastproject.security.api.AccessControlList; import org.opencastproject.security.api.AuthorizationService; import org.opencastproject.security.api.Organization; import org.opencastproject.security.api.OrganizationDirectoryService; import org.opencastproject.security.api.SecurityService; import org.opencastproject.security.api.StaticFileAuthorization; import org.opencastproject.security.api.UnauthorizedException; import org.opencastproject.security.api.User; import org.opencastproject.security.api.UserDirectoryService; import org.opencastproject.security.util.SecurityUtil; import org.opencastproject.series.api.SeriesService; import org.opencastproject.serviceregistry.api.ServiceRegistry; import org.opencastproject.serviceregistry.api.ServiceRegistryException; import org.opencastproject.solr.SolrServerFactory; import org.opencastproject.util.LoadUtil; import org.opencastproject.util.NotFoundException; import org.opencastproject.util.data.Tuple; import org.opencastproject.workspace.api.Workspace; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.osgi.framework.ServiceException; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Dictionary; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A Solr-based {@link SearchService} implementation. */ public final class SearchServiceImpl extends AbstractJobProducer implements SearchService, ManagedService, StaticFileAuthorization { /** Log facility */ private static final Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class); /** Configuration key for a remote solr server */ public static final String CONFIG_SOLR_URL = "org.opencastproject.search.solr.url"; /** Configuration key for an embedded solr configuration and data directory */ public static final String CONFIG_SOLR_ROOT = "org.opencastproject.search.solr.dir"; /** The job type */ public static final String JOB_TYPE = "org.opencastproject.search"; /** The load introduced on the system by creating an add job */ public static final float DEFAULT_ADD_JOB_LOAD = 0.1f; /** The load introduced on the system by creating a delete job */ public static final float DEFAULT_DELETE_JOB_LOAD = 0.1f; /** The key to look for in the service configuration file to override the {@link DEFAULT_ADD_JOB_LOAD} */ public static final String ADD_JOB_LOAD_KEY = "job.load.add"; /** The key to look for in the service configuration file to override the {@link DEFAULT_DELETE_JOB_LOAD} */ public static final String DELETE_JOB_LOAD_KEY = "job.load.delete"; /** The load introduced on the system by creating an add job */ private float addJobLoad = DEFAULT_ADD_JOB_LOAD; /** The load introduced on the system by creating a delete job */ private float deleteJobLoad = DEFAULT_DELETE_JOB_LOAD; /** counter how often the index has already been tried to populate */ private int retriesToPopulateIndex = 0; /** List of available operations on jobs */ private enum Operation { Add, Delete }; /** Solr server */ private SolrServer solrServer; private SolrRequester solrRequester; private SolrIndexManager indexManager; private List<StaticMetadataService> mdServices = new ArrayList<StaticMetadataService>(); private Mpeg7CatalogService mpeg7CatalogService; private SeriesService seriesService; /** The local workspace */ private Workspace workspace; /** The security service */ private SecurityService securityService; /** The authorization service */ private AuthorizationService authorizationService; /** The service registry */ private ServiceRegistry serviceRegistry; /** Persistent storage */ private SearchServiceDatabase persistence; /** The user directory service */ protected UserDirectoryService userDirectoryService = null; /** The organization directory service */ protected OrganizationDirectoryService organizationDirectory = null; /** The optional Mediapackage serializer */ protected MediaPackageSerializer serializer = null; private LoadingCache<Tuple<User, String>, Boolean> cache = null; private static final Pattern staticFilePattern = Pattern.compile("^/([^/]+)/engage-player/([^/]+)/.*$"); /** * Creates a new instance of the search service. */ public SearchServiceImpl() { super(JOB_TYPE); cache = CacheBuilder.newBuilder() .maximumSize(2048) .expireAfterWrite(1, TimeUnit.MINUTES) .build(new CacheLoader<Tuple<User, String>, Boolean>() { @Override public Boolean load(Tuple<User, String> key) { return loadUrlAccess(key.getB()); } }); } /** * Return the solr index manager * * @return indexManager */ public SolrIndexManager getSolrIndexManager() { return indexManager; } /** * Service activator, called via declarative services configuration. If the solr server url is configured, we try to * connect to it. If not, the solr data directory with an embedded Solr server is used. * * @param cc * the component context */ @Override public void activate(final ComponentContext cc) throws IllegalStateException { super.activate(cc); final String solrServerUrlConfig = StringUtils.trimToNull(cc.getBundleContext().getProperty(CONFIG_SOLR_URL)); logger.info("Setting up solr server"); solrServer = new Object() { SolrServer create() { if (solrServerUrlConfig != null) { /* Use external SOLR server */ try { logger.info("Setting up solr server at {}", solrServerUrlConfig); URL solrServerUrl = new URL(solrServerUrlConfig); return setupSolr(solrServerUrl); } catch (MalformedURLException e) { throw connectError(solrServerUrlConfig, e); } } else { /* Set-up embedded SOLR */ String solrRoot = SolrServerFactory.getEmbeddedDir(cc, CONFIG_SOLR_ROOT, "search"); try { logger.debug("Setting up solr server at {}", solrRoot); return setupSolr(new File(solrRoot)); } catch (IOException e) { throw connectError(solrServerUrlConfig, e); } catch (SolrServerException e) { throw connectError(solrServerUrlConfig, e); } } } IllegalStateException connectError(String target, Exception e) { logger.error("Unable to connect to solr at {}: {}", target, e.getMessage()); return new IllegalStateException("Unable to connect to solr at " + target, e); } // CHECKSTYLE:OFF }.create(); // CHECKSTYLE:ON solrRequester = new SolrRequester(solrServer, securityService, serializer); indexManager = new SolrIndexManager(solrServer, workspace, mdServices, seriesService, mpeg7CatalogService, securityService); String systemUserName = cc.getBundleContext().getProperty(SecurityUtil.PROPERTY_KEY_SYS_USER); populateIndex(systemUserName); } /** * Service deactivator, called via declarative services configuration. */ public void deactivate() { SolrServerFactory.shutdown(solrServer); } /** * Prepares the embedded solr environment. * * @param solrRoot * the solr root directory */ static SolrServer setupSolr(File solrRoot) throws IOException, SolrServerException { logger.info("Setting up solr search index at {}", solrRoot); File solrConfigDir = new File(solrRoot, "conf"); // Create the config directory if (solrConfigDir.exists()) { logger.info("solr search index found at {}", solrConfigDir); } else { logger.info("solr config directory doesn't exist. Creating {}", solrConfigDir); FileUtils.forceMkdir(solrConfigDir); } // Make sure there is a configuration in place copyClasspathResourceToFile("/solr/conf/protwords.txt", solrConfigDir); copyClasspathResourceToFile("/solr/conf/schema.xml", solrConfigDir); copyClasspathResourceToFile("/solr/conf/scripts.conf", solrConfigDir); copyClasspathResourceToFile("/solr/conf/solrconfig.xml", solrConfigDir); copyClasspathResourceToFile("/solr/conf/stopwords.txt", solrConfigDir); copyClasspathResourceToFile("/solr/conf/synonyms.txt", solrConfigDir); // Test for the existence of a data directory File solrDataDir = new File(solrRoot, "data"); if (!solrDataDir.exists()) { FileUtils.forceMkdir(solrDataDir); } // Test for the existence of the index. Note that an empty index directory will prevent solr from // completing normal setup. File solrIndexDir = new File(solrDataDir, "index"); if (solrIndexDir.isDirectory() && solrIndexDir.list().length == 0) { FileUtils.deleteDirectory(solrIndexDir); } return SolrServerFactory.newEmbeddedInstance(solrRoot, solrDataDir); } /** * Prepares the embedded solr environment. * * @param url * the url of the remote solr server */ static SolrServer setupSolr(URL url) { logger.info("Connecting to solr search index at {}", url); return SolrServerFactory.newRemoteInstance(url); } // TODO: generalize this method static void copyClasspathResourceToFile(String classpath, File dir) { InputStream in = null; FileOutputStream fos = null; try { in = SearchServiceImpl.class.getResourceAsStream(classpath); File file = new File(dir, FilenameUtils.getName(classpath)); logger.debug("copying " + classpath + " to " + file); fos = new FileOutputStream(file); IOUtils.copy(in, fos); } catch (IOException e) { throw new RuntimeException("Error copying solr classpath resource to the filesystem", e); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(fos); } } /** * {@inheritDoc} * * @see org.opencastproject.search.api.SearchService#getByQuery(java.lang.String, int, int) */ public SearchResult getByQuery(String query, int limit, int offset) throws SearchException { try { logger.debug("Searching index using custom query '" + query + "'"); return solrRequester.getByQuery(query, limit, offset); } catch (SolrServerException e) { throw new SearchException(e); } } /** * {@inheritDoc} * * @see org.opencastproject.search.api.SearchService#add(org.opencastproject.mediapackage.MediaPackage) */ public Job add(MediaPackage mediaPackage) throws SearchException, MediaPackageException, IllegalArgumentException, UnauthorizedException, ServiceRegistryException { try { return serviceRegistry.createJob(JOB_TYPE, Operation.Add.toString(), Arrays.asList(MediaPackageParser.getAsXml(mediaPackage)), addJobLoad); } catch (ServiceRegistryException e) { throw new SearchException(e); } } /** * Immediately adds the mediapackage to the search index. * * @param mediaPackage * the media package * @throws SearchException * if the media package cannot be added to the search index * @throws IllegalArgumentException * if the mediapackage is <code>null</code> * @throws UnauthorizedException * if the user does not have the rights to add the mediapackage */ public void addSynchronously(MediaPackage mediaPackage) throws SearchException, IllegalArgumentException, UnauthorizedException, NotFoundException, SearchServiceDatabaseException { if (mediaPackage == null) { throw new IllegalArgumentException("Unable to add a null mediapackage"); } final String mediaPackageId = mediaPackage.getIdentifier().toString(); logger.debug("Attempting to add media package {} to search index", mediaPackageId); AccessControlList acl = authorizationService.getActiveAcl(mediaPackage).getA(); AccessControlList seriesAcl = persistence.getAccessControlLists(mediaPackage.getSeries(), mediaPackageId).stream() .reduce(new AccessControlList(acl.getEntries()), AccessControlList::mergeActions); logger.debug("Updating series with merged access control list: {}", seriesAcl); Date now = new Date(); try { if (indexManager.add(mediaPackage, acl, seriesAcl, now)) { logger.info("Added media package `{}` to the search index, using ACL `{}`", mediaPackageId, acl); } else { logger.warn("Failed to add media package {} to the search index", mediaPackageId); } } catch (SolrServerException e) { throw new SearchException(e); } try { persistence.storeMediaPackage(mediaPackage, acl, now); } catch (SearchServiceDatabaseException e) { throw new SearchException( String.format("Could not store media package to search database %s", mediaPackageId), e); } } /** * {@inheritDoc} * * @see org.opencastproject.search.api.SearchService#delete(java.lang.String) */ public Job delete(String mediaPackageId) throws SearchException, UnauthorizedException, NotFoundException { try { return serviceRegistry.createJob(JOB_TYPE, Operation.Delete.toString(), Arrays.asList(mediaPackageId), deleteJobLoad); } catch (ServiceRegistryException e) { throw new SearchException(e); } } /** * Immediately removes the given mediapackage from the search service. * * @param mediaPackageId * the mediapackage * @return <code>true</code> if the mediapackage was deleted * @throws SearchException * if deletion failed */ public boolean deleteSynchronously(final String mediaPackageId) throws SearchException { SearchResult result; try { result = solrRequester.getForWrite(new SearchQuery().withId(mediaPackageId)); if (result.getItems().length == 0) { logger.warn( "Can not delete mediapackage {}, which is not available for the current user to delete from the search index.", mediaPackageId); return false; } final String seriesId = result.getItems()[0].getDcIsPartOf(); logger.info("Removing media package {} from search index", mediaPackageId); Date now = new Date(); try { persistence.deleteMediaPackage(mediaPackageId, now); logger.info("Removed mediapackage {} from search persistence", mediaPackageId); } catch (NotFoundException e) { // even if mp not found in persistence, it might still exist in search index. logger.info("Could not find mediapackage with id {} in persistence, but will try remove it from index, anyway.", mediaPackageId); } catch (SearchServiceDatabaseException e) { logger.error("Could not delete media package with id {} from persistence storage", mediaPackageId); throw new SearchException(e); } final boolean success = indexManager.delete(mediaPackageId, now); // Update series if (seriesId != null) { if (persistence.getMediaPackages(seriesId).size() > 0) { // Update series acl if there are still episodes in the series final AccessControlList seriesAcl = persistence.getAccessControlLists(seriesId).stream() .reduce(new AccessControlList(), AccessControlList::mergeActions); indexManager.addSeries(seriesId, seriesAcl); } else { // Remove series if there are no episodes in the series any longer indexManager.delete(seriesId, now); } } return success; } catch (SolrServerException | SearchServiceDatabaseException e) { logger.info("Could not delete media package with id {} from search index", mediaPackageId); throw new SearchException(e); } } /** * Clears the complete solr index. * * @throws SearchException * if clearing the index fails */ public void clear() throws SearchException { try { logger.info("Clearing the search index"); indexManager.clear(); } catch (SolrServerException e) { throw new SearchException(e); } } /** * {@inheritDoc} * * @see org.opencastproject.search.api.SearchService#getByQuery(org.opencastproject.search.api.SearchQuery) */ public SearchResult getByQuery(SearchQuery q) throws SearchException { try { logger.debug("Searching index using query object '" + q + "'"); return solrRequester.getForRead(q); } catch (SolrServerException e) { throw new SearchException(e); } } /** * {@inheritDoc} * * @see org.opencastproject.search.api.SearchService#getForAdministrativeRead(org.opencastproject.search.api.SearchQuery) */ @Override public SearchResult getForAdministrativeRead(SearchQuery q) throws SearchException, UnauthorizedException { User user = securityService.getUser(); if (!user.hasRole(GLOBAL_ADMIN_ROLE) && !user.hasRole(user.getOrganization().getAdminRole())) throw new UnauthorizedException(user, getClass().getName() + ".getForAdministrativeRead"); try { return solrRequester.getForAdministrativeRead(q); } catch (SolrServerException e) { throw new SearchException(e); } } protected void populateIndex(String systemUserName) { long instancesInSolr = 0L; try { instancesInSolr = indexManager.count(); } catch (Exception e) { throw new IllegalStateException(e); } if (instancesInSolr > 0) { logger.debug("Search index found"); return; } if (instancesInSolr == 0L) { logger.info("No search index found"); Iterator<Tuple<MediaPackage, String>> mediaPackages; int total = 0; try { total = persistence.countMediaPackages(); logger.info("Starting population of search index from {} items in database", total); mediaPackages = persistence.getAllMediaPackages(); } catch (SearchServiceDatabaseException e) { logger.error("Unable to load the search entries: {}", e.getMessage()); throw new ServiceException(e.getMessage()); } int errors = 0; int current = 0; while (mediaPackages.hasNext()) { current++; try { Tuple<MediaPackage, String> mediaPackage = mediaPackages.next(); String mediaPackageId = mediaPackage.getA().getIdentifier().toString(); Organization organization = organizationDirectory.getOrganization(mediaPackage.getB()); securityService.setOrganization(organization); securityService.setUser(SecurityUtil.createSystemUser(systemUserName, organization)); AccessControlList acl = persistence.getAccessControlList(mediaPackageId); Date modificationDate = persistence.getModificationDate(mediaPackageId); Date deletionDate = persistence.getDeletionDate(mediaPackageId); indexManager.add(mediaPackage.getA(), acl, deletionDate, modificationDate); } catch (Exception e) { logger.error("Unable to index search instances:", e); if (retryToPopulateIndex(systemUserName)) { logger.warn("Trying to re-index search index later. Aborting for now."); return; } errors++; } finally { securityService.setOrganization(null); securityService.setUser(null); } // log progress if (current % 100 == 0) { logger.info("Indexing search {}/{} ({} percent done)", current, total, current * 100 / total); } } if (errors > 0) logger.error("Skipped {} erroneous search entries while populating the search index", errors); logger.info("Finished populating search index"); } } private boolean retryToPopulateIndex(final String systemUserName) { if (retriesToPopulateIndex > 0) { return false; } long instancesInSolr = 0L; try { instancesInSolr = indexManager.count(); } catch (Exception e) { throw new IllegalStateException(e); } if (instancesInSolr > 0) { logger.debug("Search index found, other files could be indexed. No retry needed."); return false; } retriesToPopulateIndex++; new Thread() { public void run() { try { Thread.sleep(30000); } catch (InterruptedException ex) { } populateIndex(systemUserName); } }.start(); return true; } /** * @see org.opencastproject.job.api.AbstractJobProducer#process(org.opencastproject.job.api.Job) */ @Override protected String process(Job job) throws Exception { Operation op = null; String operation = job.getOperation(); List<String> arguments = job.getArguments(); try { op = Operation.valueOf(operation); switch (op) { case Add: MediaPackage mediaPackage = MediaPackageParser.getFromXml(arguments.get(0)); addSynchronously(mediaPackage); return null; case Delete: String mediapackageId = arguments.get(0); boolean deleted = deleteSynchronously(mediapackageId); return Boolean.toString(deleted); default: throw new IllegalStateException("Don't know how to handle operation '" + operation + "'"); } } catch (IllegalArgumentException e) { throw new ServiceRegistryException("This service can't handle operations of type '" + op + "'", e); } catch (IndexOutOfBoundsException e) { throw new ServiceRegistryException("This argument list for operation '" + op + "' does not meet expectations", e); } catch (Exception e) { throw new ServiceRegistryException("Error handling operation '" + op + "'", e); } } /** For testing purposes only! */ void testSetup(SolrServer server, SolrRequester requester, SolrIndexManager manager) { this.solrServer = server; this.solrRequester = requester; this.indexManager = manager; } /** Dynamic reference. */ public void setStaticMetadataService(StaticMetadataService mdService) { this.mdServices.add(mdService); if (indexManager != null) indexManager.setStaticMetadataServices(mdServices); } public void unsetStaticMetadataService(StaticMetadataService mdService) { this.mdServices.remove(mdService); if (indexManager != null) indexManager.setStaticMetadataServices(mdServices); } public void setMpeg7CatalogService(Mpeg7CatalogService mpeg7CatalogService) { this.mpeg7CatalogService = mpeg7CatalogService; } public void setPersistence(SearchServiceDatabase persistence) { this.persistence = persistence; } public void setSeriesService(SeriesService seriesService) { this.seriesService = seriesService; } public void setWorkspace(Workspace workspace) { this.workspace = workspace; } public void setAuthorizationService(AuthorizationService authorizationService) { this.authorizationService = authorizationService; } public void setServiceRegistry(ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; } /** * Callback for setting the security service. * * @param securityService * the securityService to set */ public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } /** * Callback for setting the user directory service. * * @param userDirectoryService * the userDirectoryService to set */ public void setUserDirectoryService(UserDirectoryService userDirectoryService) { this.userDirectoryService = userDirectoryService; } /** * Sets a reference to the organization directory service. * * @param organizationDirectory * the organization directory */ public void setOrganizationDirectoryService(OrganizationDirectoryService organizationDirectory) { this.organizationDirectory = organizationDirectory; } /** * @see org.opencastproject.job.api.AbstractJobProducer#getOrganizationDirectoryService() */ @Override protected OrganizationDirectoryService getOrganizationDirectoryService() { return organizationDirectory; } /** * @see org.opencastproject.job.api.AbstractJobProducer#getSecurityService() */ @Override protected SecurityService getSecurityService() { return securityService; } /** * @see org.opencastproject.job.api.AbstractJobProducer#getServiceRegistry() */ @Override protected ServiceRegistry getServiceRegistry() { return serviceRegistry; } /** * @see org.opencastproject.job.api.AbstractJobProducer#getUserDirectoryService() */ @Override protected UserDirectoryService getUserDirectoryService() { return userDirectoryService; } /** * Sets the optional MediaPackage serializer. * * @param serializer * the serializer */ protected void setMediaPackageSerializer(MediaPackageSerializer serializer) { this.serializer = serializer; if (solrRequester != null) solrRequester.setMediaPackageSerializer(serializer); } @Override public void updated(@SuppressWarnings("rawtypes") Dictionary properties) throws ConfigurationException { addJobLoad = LoadUtil.getConfiguredLoadValue(properties, ADD_JOB_LOAD_KEY, DEFAULT_ADD_JOB_LOAD, serviceRegistry); deleteJobLoad = LoadUtil.getConfiguredLoadValue(properties, DELETE_JOB_LOAD_KEY, DEFAULT_DELETE_JOB_LOAD, serviceRegistry); } @Override public List<Pattern> getProtectedUrlPattern() { return Collections.singletonList(staticFilePattern); } private boolean loadUrlAccess(final String mediaPackageId) { logger.debug("Check if user `{}` has access to media package `{}`", securityService.getUser(), mediaPackageId); final SearchQuery query = new SearchQuery() .withId(mediaPackageId) .includeEpisodes(true) .includeSeries(false); return getByQuery(query).size() > 0; } @Override public boolean verifyUrlAccess(final String path) { // Always allow access for admin final User user = securityService.getUser(); if (user.hasRole(GLOBAL_ADMIN_ROLE)) { logger.debug("Allow access for admin `{}`", user); return true; } // Check pattern final Matcher m = staticFilePattern.matcher(path); if (!m.matches()) { logger.debug("Path does not match pattern. Preventing access."); return false; } // Check organization final String organizationId = m.group(1); if (!securityService.getOrganization().getId().equals(organizationId)) { logger.debug("The user's organization does not match. Preventing access."); return false; } // Check search index/cache final String mediaPackageId = m.group(2); final boolean access = cache.getUnchecked(Tuple.tuple(user, mediaPackageId)); logger.debug("Check if user `{}` has access to media package `{}` using cache: {}", user, mediaPackageId, access); return access; } }
./CrossVul/dataset_final_sorted/CWE-863/java/good_1947_0
crossvul-java_data_bad_4545_3
404: Not Found
./CrossVul/dataset_final_sorted/CWE-863/java/bad_4545_3
crossvul-java_data_bad_4254_2
package com.zrlog.service; import com.hibegin.common.util.http.HttpUtil; import com.hibegin.common.util.http.handle.HttpJsonArrayHandle; import com.zrlog.common.Constants; import com.zrlog.common.response.UploadFileResponse; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.List; import java.util.Map; public class UploadService { private static final Logger LOGGER = Logger.getLogger(UploadService.class); public UploadFileResponse getCloudUrl(String contextPath, String uri, String finalFilePath, HttpServletRequest request) { UploadFileResponse uploadFileResponse = new UploadFileResponse(); // try push to cloud Map<String, String[]> map = new HashMap<>(); map.put("fileInfo", new String[]{finalFilePath + "," + uri}); map.put("name", new String[]{"uploadService"}); String url; try { List<Map> urls = HttpUtil.getInstance().sendGetRequest(Constants.pluginServer + "/service", map , new HttpJsonArrayHandle<Map>(), PluginHelper.genHeaderMapByRequest(request)).getT(); if (urls != null && !urls.isEmpty()) { url = (String) urls.get(0).get("url"); if (!url.startsWith("https://") && !url.startsWith("http://")) { String tUrl = url; if (!url.startsWith("/")) { tUrl = "/" + url; } url = contextPath + tUrl; } } else { url = contextPath + uri; } } catch (Exception e) { url = contextPath + uri; LOGGER.error(e); } uploadFileResponse.setUrl(url); return uploadFileResponse; } }
./CrossVul/dataset_final_sorted/CWE-863/java/bad_4254_2
crossvul-java_data_bad_1947_0
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.search.impl; import static org.opencastproject.security.api.SecurityConstants.GLOBAL_ADMIN_ROLE; import org.opencastproject.job.api.AbstractJobProducer; import org.opencastproject.job.api.Job; import org.opencastproject.mediapackage.MediaPackage; import org.opencastproject.mediapackage.MediaPackageException; import org.opencastproject.mediapackage.MediaPackageParser; import org.opencastproject.mediapackage.MediaPackageSerializer; import org.opencastproject.metadata.api.StaticMetadataService; import org.opencastproject.metadata.mpeg7.Mpeg7CatalogService; import org.opencastproject.search.api.SearchException; import org.opencastproject.search.api.SearchQuery; import org.opencastproject.search.api.SearchResult; import org.opencastproject.search.api.SearchService; import org.opencastproject.search.impl.persistence.SearchServiceDatabase; import org.opencastproject.search.impl.persistence.SearchServiceDatabaseException; import org.opencastproject.search.impl.solr.SolrIndexManager; import org.opencastproject.search.impl.solr.SolrRequester; import org.opencastproject.security.api.AccessControlList; import org.opencastproject.security.api.AuthorizationService; import org.opencastproject.security.api.Organization; import org.opencastproject.security.api.OrganizationDirectoryService; import org.opencastproject.security.api.SecurityService; import org.opencastproject.security.api.StaticFileAuthorization; import org.opencastproject.security.api.UnauthorizedException; import org.opencastproject.security.api.User; import org.opencastproject.security.api.UserDirectoryService; import org.opencastproject.security.util.SecurityUtil; import org.opencastproject.series.api.SeriesService; import org.opencastproject.serviceregistry.api.ServiceRegistry; import org.opencastproject.serviceregistry.api.ServiceRegistryException; import org.opencastproject.solr.SolrServerFactory; import org.opencastproject.util.LoadUtil; import org.opencastproject.util.NotFoundException; import org.opencastproject.util.data.Tuple; import org.opencastproject.workspace.api.Workspace; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.osgi.framework.ServiceException; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Dictionary; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A Solr-based {@link SearchService} implementation. */ public final class SearchServiceImpl extends AbstractJobProducer implements SearchService, ManagedService, StaticFileAuthorization { /** Log facility */ private static final Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class); /** Configuration key for a remote solr server */ public static final String CONFIG_SOLR_URL = "org.opencastproject.search.solr.url"; /** Configuration key for an embedded solr configuration and data directory */ public static final String CONFIG_SOLR_ROOT = "org.opencastproject.search.solr.dir"; /** The job type */ public static final String JOB_TYPE = "org.opencastproject.search"; /** The load introduced on the system by creating an add job */ public static final float DEFAULT_ADD_JOB_LOAD = 0.1f; /** The load introduced on the system by creating a delete job */ public static final float DEFAULT_DELETE_JOB_LOAD = 0.1f; /** The key to look for in the service configuration file to override the {@link DEFAULT_ADD_JOB_LOAD} */ public static final String ADD_JOB_LOAD_KEY = "job.load.add"; /** The key to look for in the service configuration file to override the {@link DEFAULT_DELETE_JOB_LOAD} */ public static final String DELETE_JOB_LOAD_KEY = "job.load.delete"; /** The load introduced on the system by creating an add job */ private float addJobLoad = DEFAULT_ADD_JOB_LOAD; /** The load introduced on the system by creating a delete job */ private float deleteJobLoad = DEFAULT_DELETE_JOB_LOAD; /** counter how often the index has already been tried to populate */ private int retriesToPopulateIndex = 0; /** List of available operations on jobs */ private enum Operation { Add, Delete }; /** Solr server */ private SolrServer solrServer; private SolrRequester solrRequester; private SolrIndexManager indexManager; private List<StaticMetadataService> mdServices = new ArrayList<StaticMetadataService>(); private Mpeg7CatalogService mpeg7CatalogService; private SeriesService seriesService; /** The local workspace */ private Workspace workspace; /** The security service */ private SecurityService securityService; /** The authorization service */ private AuthorizationService authorizationService; /** The service registry */ private ServiceRegistry serviceRegistry; /** Persistent storage */ private SearchServiceDatabase persistence; /** The user directory service */ protected UserDirectoryService userDirectoryService = null; /** The organization directory service */ protected OrganizationDirectoryService organizationDirectory = null; /** The optional Mediapackage serializer */ protected MediaPackageSerializer serializer = null; private LoadingCache<Tuple<User, String>, Boolean> cache = null; private static final Pattern staticFilePattern = Pattern.compile("^/([^/]+)/engage-player/([^/]+)/.*$"); /** * Creates a new instance of the search service. */ public SearchServiceImpl() { super(JOB_TYPE); cache = CacheBuilder.newBuilder() .maximumSize(2048) .expireAfterWrite(1, TimeUnit.MINUTES) .build(new CacheLoader<Tuple<User, String>, Boolean>() { @Override public Boolean load(Tuple<User, String> key) { return loadUrlAccess(key.getB()); } }); } /** * Return the solr index manager * * @return indexManager */ public SolrIndexManager getSolrIndexManager() { return indexManager; } /** * Service activator, called via declarative services configuration. If the solr server url is configured, we try to * connect to it. If not, the solr data directory with an embedded Solr server is used. * * @param cc * the component context */ @Override public void activate(final ComponentContext cc) throws IllegalStateException { super.activate(cc); final String solrServerUrlConfig = StringUtils.trimToNull(cc.getBundleContext().getProperty(CONFIG_SOLR_URL)); logger.info("Setting up solr server"); solrServer = new Object() { SolrServer create() { if (solrServerUrlConfig != null) { /* Use external SOLR server */ try { logger.info("Setting up solr server at {}", solrServerUrlConfig); URL solrServerUrl = new URL(solrServerUrlConfig); return setupSolr(solrServerUrl); } catch (MalformedURLException e) { throw connectError(solrServerUrlConfig, e); } } else { /* Set-up embedded SOLR */ String solrRoot = SolrServerFactory.getEmbeddedDir(cc, CONFIG_SOLR_ROOT, "search"); try { logger.debug("Setting up solr server at {}", solrRoot); return setupSolr(new File(solrRoot)); } catch (IOException e) { throw connectError(solrServerUrlConfig, e); } catch (SolrServerException e) { throw connectError(solrServerUrlConfig, e); } } } IllegalStateException connectError(String target, Exception e) { logger.error("Unable to connect to solr at {}: {}", target, e.getMessage()); return new IllegalStateException("Unable to connect to solr at " + target, e); } // CHECKSTYLE:OFF }.create(); // CHECKSTYLE:ON solrRequester = new SolrRequester(solrServer, securityService, serializer); indexManager = new SolrIndexManager(solrServer, workspace, mdServices, seriesService, mpeg7CatalogService, securityService); String systemUserName = cc.getBundleContext().getProperty(SecurityUtil.PROPERTY_KEY_SYS_USER); populateIndex(systemUserName); } /** * Service deactivator, called via declarative services configuration. */ public void deactivate() { SolrServerFactory.shutdown(solrServer); } /** * Prepares the embedded solr environment. * * @param solrRoot * the solr root directory */ static SolrServer setupSolr(File solrRoot) throws IOException, SolrServerException { logger.info("Setting up solr search index at {}", solrRoot); File solrConfigDir = new File(solrRoot, "conf"); // Create the config directory if (solrConfigDir.exists()) { logger.info("solr search index found at {}", solrConfigDir); } else { logger.info("solr config directory doesn't exist. Creating {}", solrConfigDir); FileUtils.forceMkdir(solrConfigDir); } // Make sure there is a configuration in place copyClasspathResourceToFile("/solr/conf/protwords.txt", solrConfigDir); copyClasspathResourceToFile("/solr/conf/schema.xml", solrConfigDir); copyClasspathResourceToFile("/solr/conf/scripts.conf", solrConfigDir); copyClasspathResourceToFile("/solr/conf/solrconfig.xml", solrConfigDir); copyClasspathResourceToFile("/solr/conf/stopwords.txt", solrConfigDir); copyClasspathResourceToFile("/solr/conf/synonyms.txt", solrConfigDir); // Test for the existence of a data directory File solrDataDir = new File(solrRoot, "data"); if (!solrDataDir.exists()) { FileUtils.forceMkdir(solrDataDir); } // Test for the existence of the index. Note that an empty index directory will prevent solr from // completing normal setup. File solrIndexDir = new File(solrDataDir, "index"); if (solrIndexDir.isDirectory() && solrIndexDir.list().length == 0) { FileUtils.deleteDirectory(solrIndexDir); } return SolrServerFactory.newEmbeddedInstance(solrRoot, solrDataDir); } /** * Prepares the embedded solr environment. * * @param url * the url of the remote solr server */ static SolrServer setupSolr(URL url) { logger.info("Connecting to solr search index at {}", url); return SolrServerFactory.newRemoteInstance(url); } // TODO: generalize this method static void copyClasspathResourceToFile(String classpath, File dir) { InputStream in = null; FileOutputStream fos = null; try { in = SearchServiceImpl.class.getResourceAsStream(classpath); File file = new File(dir, FilenameUtils.getName(classpath)); logger.debug("copying " + classpath + " to " + file); fos = new FileOutputStream(file); IOUtils.copy(in, fos); } catch (IOException e) { throw new RuntimeException("Error copying solr classpath resource to the filesystem", e); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(fos); } } /** * {@inheritDoc} * * @see org.opencastproject.search.api.SearchService#getByQuery(java.lang.String, int, int) */ public SearchResult getByQuery(String query, int limit, int offset) throws SearchException { try { logger.debug("Searching index using custom query '" + query + "'"); return solrRequester.getByQuery(query, limit, offset); } catch (SolrServerException e) { throw new SearchException(e); } } /** * {@inheritDoc} * * @see org.opencastproject.search.api.SearchService#add(org.opencastproject.mediapackage.MediaPackage) */ public Job add(MediaPackage mediaPackage) throws SearchException, MediaPackageException, IllegalArgumentException, UnauthorizedException, ServiceRegistryException { try { return serviceRegistry.createJob(JOB_TYPE, Operation.Add.toString(), Arrays.asList(MediaPackageParser.getAsXml(mediaPackage)), addJobLoad); } catch (ServiceRegistryException e) { throw new SearchException(e); } } /** * Immediately adds the mediapackage to the search index. * * @param mediaPackage * the media package * @throws SearchException * if the media package cannot be added to the search index * @throws MediaPackageException * if the mediapckage is invalid * @throws IllegalArgumentException * if the mediapackage is <code>null</code> * @throws UnauthorizedException * if the user does not have the rights to add the mediapackage */ public void addSynchronously(MediaPackage mediaPackage) throws SearchException, MediaPackageException, IllegalArgumentException, UnauthorizedException { if (mediaPackage == null) { throw new IllegalArgumentException("Unable to add a null mediapackage"); } logger.debug("Attempting to add mediapackage {} to search index", mediaPackage.getIdentifier()); AccessControlList acl = authorizationService.getActiveAcl(mediaPackage).getA(); Date now = new Date(); try { if (indexManager.add(mediaPackage, acl, now)) { logger.info("Added mediapackage `{}` to the search index, using ACL `{}`", mediaPackage, acl); } else { logger.warn("Failed to add mediapackage {} to the search index", mediaPackage.getIdentifier()); } } catch (SolrServerException e) { throw new SearchException(e); } try { persistence.storeMediaPackage(mediaPackage, acl, now); } catch (SearchServiceDatabaseException e) { logger.error("Could not store media package to search database {}: {}", mediaPackage.getIdentifier(), e); throw new SearchException(e); } } /** * {@inheritDoc} * * @see org.opencastproject.search.api.SearchService#delete(java.lang.String) */ public Job delete(String mediaPackageId) throws SearchException, UnauthorizedException, NotFoundException { try { return serviceRegistry.createJob(JOB_TYPE, Operation.Delete.toString(), Arrays.asList(mediaPackageId), deleteJobLoad); } catch (ServiceRegistryException e) { throw new SearchException(e); } } /** * Immediately removes the given mediapackage from the search service. * * @param mediaPackageId * the mediapackage * @return <code>true</code> if the mediapackage was deleted * @throws SearchException * if deletion failed * @throws UnauthorizedException * if the user did not have access to the media package * @throws NotFoundException * if the mediapackage did not exist */ public boolean deleteSynchronously(String mediaPackageId) throws SearchException, UnauthorizedException, NotFoundException { SearchResult result; try { result = solrRequester.getForWrite(new SearchQuery().withId(mediaPackageId)); if (result.getItems().length == 0) { logger.warn( "Can not delete mediapackage {}, which is not available for the current user to delete from the search index.", mediaPackageId); return false; } logger.info("Removing mediapackage {} from search index", mediaPackageId); Date now = new Date(); try { persistence.deleteMediaPackage(mediaPackageId, now); logger.info("Removed mediapackage {} from search persistence", mediaPackageId); } catch (NotFoundException e) { // even if mp not found in persistence, it might still exist in search index. logger.info("Could not find mediapackage with id {} in persistence, but will try remove it from index, anyway.", mediaPackageId); } catch (SearchServiceDatabaseException e) { logger.error("Could not delete media package with id {} from persistence storage", mediaPackageId); throw new SearchException(e); } return indexManager.delete(mediaPackageId, now); } catch (SolrServerException e) { logger.info("Could not delete media package with id {} from search index", mediaPackageId); throw new SearchException(e); } } /** * Clears the complete solr index. * * @throws SearchException * if clearing the index fails */ public void clear() throws SearchException { try { logger.info("Clearing the search index"); indexManager.clear(); } catch (SolrServerException e) { throw new SearchException(e); } } /** * {@inheritDoc} * * @see org.opencastproject.search.api.SearchService#getByQuery(org.opencastproject.search.api.SearchQuery) */ public SearchResult getByQuery(SearchQuery q) throws SearchException { try { logger.debug("Searching index using query object '" + q + "'"); return solrRequester.getForRead(q); } catch (SolrServerException e) { throw new SearchException(e); } } /** * {@inheritDoc} * * @see org.opencastproject.search.api.SearchService#getForAdministrativeRead(org.opencastproject.search.api.SearchQuery) */ @Override public SearchResult getForAdministrativeRead(SearchQuery q) throws SearchException, UnauthorizedException { User user = securityService.getUser(); if (!user.hasRole(GLOBAL_ADMIN_ROLE) && !user.hasRole(user.getOrganization().getAdminRole())) throw new UnauthorizedException(user, getClass().getName() + ".getForAdministrativeRead"); try { return solrRequester.getForAdministrativeRead(q); } catch (SolrServerException e) { throw new SearchException(e); } } protected void populateIndex(String systemUserName) { long instancesInSolr = 0L; try { instancesInSolr = indexManager.count(); } catch (Exception e) { throw new IllegalStateException(e); } if (instancesInSolr > 0) { logger.debug("Search index found"); return; } if (instancesInSolr == 0L) { logger.info("No search index found"); Iterator<Tuple<MediaPackage, String>> mediaPackages; int total = 0; try { total = persistence.countMediaPackages(); logger.info("Starting population of search index from {} items in database", total); mediaPackages = persistence.getAllMediaPackages(); } catch (SearchServiceDatabaseException e) { logger.error("Unable to load the search entries: {}", e.getMessage()); throw new ServiceException(e.getMessage()); } int errors = 0; int current = 0; while (mediaPackages.hasNext()) { current++; try { Tuple<MediaPackage, String> mediaPackage = mediaPackages.next(); String mediaPackageId = mediaPackage.getA().getIdentifier().toString(); Organization organization = organizationDirectory.getOrganization(mediaPackage.getB()); securityService.setOrganization(organization); securityService.setUser(SecurityUtil.createSystemUser(systemUserName, organization)); AccessControlList acl = persistence.getAccessControlList(mediaPackageId); Date modificationDate = persistence.getModificationDate(mediaPackageId); Date deletionDate = persistence.getDeletionDate(mediaPackageId); indexManager.add(mediaPackage.getA(), acl, deletionDate, modificationDate); } catch (Exception e) { logger.error("Unable to index search instances:", e); if (retryToPopulateIndex(systemUserName)) { logger.warn("Trying to re-index search index later. Aborting for now."); return; } errors++; } finally { securityService.setOrganization(null); securityService.setUser(null); } // log progress if (current % 100 == 0) { logger.info("Indexing search {}/{} ({} percent done)", current, total, current * 100 / total); } } if (errors > 0) logger.error("Skipped {} erroneous search entries while populating the search index", errors); logger.info("Finished populating search index"); } } private boolean retryToPopulateIndex(final String systemUserName) { if (retriesToPopulateIndex > 0) { return false; } long instancesInSolr = 0L; try { instancesInSolr = indexManager.count(); } catch (Exception e) { throw new IllegalStateException(e); } if (instancesInSolr > 0) { logger.debug("Search index found, other files could be indexed. No retry needed."); return false; } retriesToPopulateIndex++; new Thread() { public void run() { try { Thread.sleep(30000); } catch (InterruptedException ex) { } populateIndex(systemUserName); } }.start(); return true; } /** * @see org.opencastproject.job.api.AbstractJobProducer#process(org.opencastproject.job.api.Job) */ @Override protected String process(Job job) throws Exception { Operation op = null; String operation = job.getOperation(); List<String> arguments = job.getArguments(); try { op = Operation.valueOf(operation); switch (op) { case Add: MediaPackage mediaPackage = MediaPackageParser.getFromXml(arguments.get(0)); addSynchronously(mediaPackage); return null; case Delete: String mediapackageId = arguments.get(0); boolean deleted = deleteSynchronously(mediapackageId); return Boolean.toString(deleted); default: throw new IllegalStateException("Don't know how to handle operation '" + operation + "'"); } } catch (IllegalArgumentException e) { throw new ServiceRegistryException("This service can't handle operations of type '" + op + "'", e); } catch (IndexOutOfBoundsException e) { throw new ServiceRegistryException("This argument list for operation '" + op + "' does not meet expectations", e); } catch (Exception e) { throw new ServiceRegistryException("Error handling operation '" + op + "'", e); } } /** For testing purposes only! */ void testSetup(SolrServer server, SolrRequester requester, SolrIndexManager manager) { this.solrServer = server; this.solrRequester = requester; this.indexManager = manager; } /** Dynamic reference. */ public void setStaticMetadataService(StaticMetadataService mdService) { this.mdServices.add(mdService); if (indexManager != null) indexManager.setStaticMetadataServices(mdServices); } public void unsetStaticMetadataService(StaticMetadataService mdService) { this.mdServices.remove(mdService); if (indexManager != null) indexManager.setStaticMetadataServices(mdServices); } public void setMpeg7CatalogService(Mpeg7CatalogService mpeg7CatalogService) { this.mpeg7CatalogService = mpeg7CatalogService; } public void setPersistence(SearchServiceDatabase persistence) { this.persistence = persistence; } public void setSeriesService(SeriesService seriesService) { this.seriesService = seriesService; } public void setWorkspace(Workspace workspace) { this.workspace = workspace; } public void setAuthorizationService(AuthorizationService authorizationService) { this.authorizationService = authorizationService; } public void setServiceRegistry(ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; } /** * Callback for setting the security service. * * @param securityService * the securityService to set */ public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } /** * Callback for setting the user directory service. * * @param userDirectoryService * the userDirectoryService to set */ public void setUserDirectoryService(UserDirectoryService userDirectoryService) { this.userDirectoryService = userDirectoryService; } /** * Sets a reference to the organization directory service. * * @param organizationDirectory * the organization directory */ public void setOrganizationDirectoryService(OrganizationDirectoryService organizationDirectory) { this.organizationDirectory = organizationDirectory; } /** * @see org.opencastproject.job.api.AbstractJobProducer#getOrganizationDirectoryService() */ @Override protected OrganizationDirectoryService getOrganizationDirectoryService() { return organizationDirectory; } /** * @see org.opencastproject.job.api.AbstractJobProducer#getSecurityService() */ @Override protected SecurityService getSecurityService() { return securityService; } /** * @see org.opencastproject.job.api.AbstractJobProducer#getServiceRegistry() */ @Override protected ServiceRegistry getServiceRegistry() { return serviceRegistry; } /** * @see org.opencastproject.job.api.AbstractJobProducer#getUserDirectoryService() */ @Override protected UserDirectoryService getUserDirectoryService() { return userDirectoryService; } /** * Sets the optional MediaPackage serializer. * * @param serializer * the serializer */ protected void setMediaPackageSerializer(MediaPackageSerializer serializer) { this.serializer = serializer; if (solrRequester != null) solrRequester.setMediaPackageSerializer(serializer); } @Override public void updated(@SuppressWarnings("rawtypes") Dictionary properties) throws ConfigurationException { addJobLoad = LoadUtil.getConfiguredLoadValue(properties, ADD_JOB_LOAD_KEY, DEFAULT_ADD_JOB_LOAD, serviceRegistry); deleteJobLoad = LoadUtil.getConfiguredLoadValue(properties, DELETE_JOB_LOAD_KEY, DEFAULT_DELETE_JOB_LOAD, serviceRegistry); } @Override public List<Pattern> getProtectedUrlPattern() { return Collections.singletonList(staticFilePattern); } private boolean loadUrlAccess(final String mediaPackageId) { logger.debug("Check if user `{}` has access to media package `{}`", securityService.getUser(), mediaPackageId); final SearchQuery query = new SearchQuery() .withId(mediaPackageId) .includeEpisodes(true) .includeSeries(false); return getByQuery(query).size() > 0; } @Override public boolean verifyUrlAccess(final String path) { // Always allow access for admin final User user = securityService.getUser(); if (user.hasRole(GLOBAL_ADMIN_ROLE)) { logger.debug("Allow access for admin `{}`", user); return true; } // Check pattern final Matcher m = staticFilePattern.matcher(path); if (!m.matches()) { logger.debug("Path does not match pattern. Preventing access."); return false; } // Check organization final String organizationId = m.group(1); if (!securityService.getOrganization().getId().equals(organizationId)) { logger.debug("The user's organization does not match. Preventing access."); return false; } // Check search index/cache final String mediaPackageId = m.group(2); final boolean access = cache.getUnchecked(Tuple.tuple(user, mediaPackageId)); logger.debug("Check if user `{}` has access to media package `{}` using cache: {}", user, mediaPackageId, access); return access; } }
./CrossVul/dataset_final_sorted/CWE-863/java/bad_1947_0
crossvul-java_data_good_3865_0
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2013, 2014, 2016, 2020 Synacor, Inc. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software Foundation, * version 2 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. * ***** END LICENSE BLOCK ***** */ package com.zimbra.cs.service.account; import java.util.Map; import com.zimbra.common.service.ServiceException; import com.zimbra.common.soap.AccountConstants; import com.zimbra.common.soap.Element; import com.zimbra.cs.account.Account; import com.zimbra.cs.account.Provisioning; import com.zimbra.cs.gal.GalSearchControl; import com.zimbra.cs.gal.GalSearchParams; import com.zimbra.soap.ZimbraSoapContext; import com.zimbra.soap.type.GalSearchType; /** * @since May 26, 2004 * @author schemers */ public class AutoCompleteGal extends GalDocumentHandler { @Override public Element handle(Element request, Map<String, Object> context) throws ServiceException { ZimbraSoapContext zsc = getZimbraSoapContext(context); Account account = getRequestedAccount(getZimbraSoapContext(context)); if (!canAccessAccount(zsc, account)) throw ServiceException.PERM_DENIED("can not access account"); String name = request.getAttribute(AccountConstants.E_NAME); String typeStr = request.getAttribute(AccountConstants.A_TYPE, "account"); GalSearchType type = GalSearchType.fromString(typeStr); boolean needCanExpand = request.getAttributeBool(AccountConstants.A_NEED_EXP, false); String galAcctId = request.getAttribute(AccountConstants.A_GAL_ACCOUNT_ID, null); GalSearchParams params = new GalSearchParams(account, zsc); params.setType(type); params.setRequest(request); params.setQuery(name); params.setLimit(account.getContactAutoCompleteMaxResults()); params.setNeedCanExpand(needCanExpand); params.setResponseName(AccountConstants.AUTO_COMPLETE_GAL_RESPONSE); if (galAcctId != null) { Account galAccount = Provisioning.getInstance().getAccountById(galAcctId); if (galAccount != null && (!account.getDomainId().equals(galAccount.getDomainId()))) { throw ServiceException .PERM_DENIED("can not access galsync account of different domain"); } params.setGalSyncAccount(galAccount); } GalSearchControl gal = new GalSearchControl(params); gal.autocomplete(); return params.getResultCallback().getResponse(); } @Override public boolean needsAuth(Map<String, Object> context) { return true; } }
./CrossVul/dataset_final_sorted/CWE-863/java/good_3865_0
crossvul-java_data_good_4254_0
package com.zrlog.web.util; import com.zrlog.common.vo.AdminTokenVO; import com.zrlog.util.BlogBuildInfoUtil; import com.zrlog.util.I18nUtil; import com.zrlog.util.ZrLogUtil; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; public class PluginHelper { public static Map<String, String> genHeaderMapByRequest(HttpServletRequest request, AdminTokenVO adminTokenVO) { Map<String, String> map = new HashMap<>(); if (adminTokenVO != null) { map.put("LoginUserId", adminTokenVO.getUserId() + ""); } map.put("IsLogin", (adminTokenVO != null) + ""); map.put("Current-Locale", I18nUtil.getCurrentLocale()); map.put("Blog-Version", BlogBuildInfoUtil.getVersion()); if (request != null) { String fullUrl = ZrLogUtil.getFullUrl(request); if (request.getQueryString() != null) { fullUrl = fullUrl + "?" + request.getQueryString(); } if (adminTokenVO != null) { fullUrl = adminTokenVO.getProtocol() + ":" + fullUrl; } map.put("Cookie", request.getHeader("Cookie")); map.put("AccessUrl", "http://127.0.0.1:" + request.getServerPort() + request.getContextPath()); if (request.getHeader("Content-Type") != null) { map.put("Content-Type", request.getHeader("Content-Type")); } map.put("Full-Url", fullUrl); } return map; } }
./CrossVul/dataset_final_sorted/CWE-863/java/good_4254_0
crossvul-java_data_good_4254_2
package com.zrlog.service; import com.hibegin.common.util.http.HttpUtil; import com.hibegin.common.util.http.handle.HttpJsonArrayHandle; import com.zrlog.common.Constants; import com.zrlog.common.response.UploadFileResponse; import com.zrlog.web.util.PluginHelper; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.List; import java.util.Map; public class UploadService { private static final Logger LOGGER = Logger.getLogger(UploadService.class); public UploadFileResponse getCloudUrl(String contextPath, String uri, String finalFilePath, HttpServletRequest request) { UploadFileResponse uploadFileResponse = new UploadFileResponse(); // try push to cloud Map<String, String[]> map = new HashMap<>(); map.put("fileInfo", new String[]{finalFilePath + "," + uri}); map.put("name", new String[]{"uploadService"}); String url; try { List<Map> urls = HttpUtil.getInstance().sendGetRequest(Constants.pluginServer + "/service", map , new HttpJsonArrayHandle<Map>(), PluginHelper.genHeaderMapByRequest(request, AdminTokenThreadLocal.getUser())).getT(); if (urls != null && !urls.isEmpty()) { url = (String) urls.get(0).get("url"); if (!url.startsWith("https://") && !url.startsWith("http://")) { String tUrl = url; if (!url.startsWith("/")) { tUrl = "/" + url; } url = contextPath + tUrl; } } else { url = contextPath + uri; } } catch (Exception e) { url = contextPath + uri; LOGGER.error(e); } uploadFileResponse.setUrl(url); return uploadFileResponse; } }
./CrossVul/dataset_final_sorted/CWE-863/java/good_4254_2
crossvul-java_data_good_4545_2
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.exec.internal; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.binding.BaseThingHandlerFactory; import org.eclipse.smarthome.core.thing.binding.ThingHandler; import org.eclipse.smarthome.core.thing.binding.ThingHandlerFactory; import org.openhab.binding.exec.internal.handler.ExecHandler; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.Set; import static org.openhab.binding.exec.internal.ExecBindingConstants.THING_COMMAND; /** * The {@link ExecHandlerFactory} is responsible for creating things and thing * handlers. * * @author Karel Goderis - Initial contribution */ @NonNullByDefault @Component(service = ThingHandlerFactory.class, configurationPid = "binding.exec") public class ExecHandlerFactory extends BaseThingHandlerFactory { private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_COMMAND); private final Logger logger = LoggerFactory.getLogger(ExecHandlerFactory.class); private final ExecWhitelistWatchService execWhitelistWatchService; @Activate public ExecHandlerFactory(@Reference ExecWhitelistWatchService execWhitelistWatchService) { this.execWhitelistWatchService = execWhitelistWatchService; } @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { return SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID); } @Override protected @Nullable ThingHandler createHandler(Thing thing) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (thingTypeUID.equals(THING_COMMAND)) { return new ExecHandler(thing, execWhitelistWatchService); } return null; } }
./CrossVul/dataset_final_sorted/CWE-863/java/good_4545_2
crossvul-java_data_bad_1947_2
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.search.impl.persistence; import org.opencastproject.mediapackage.MediaPackage; import org.opencastproject.security.api.AccessControlList; import org.opencastproject.security.api.UnauthorizedException; import org.opencastproject.util.NotFoundException; import org.opencastproject.util.data.Tuple; import java.util.Date; import java.util.Iterator; /** * API that defines persistent storage of series. * */ public interface SearchServiceDatabase { /** * Returns all search entries in persistent storage. * * @return {@link Tuple} array representing stored media packages * @throws SearchServiceDatabaseException * if exception occurs */ Iterator<Tuple<MediaPackage, String>> getAllMediaPackages() throws SearchServiceDatabaseException; /** * Returns the organization id of the selected media package * * @param mediaPackageId * the media package id to select * @return the organization id * @throws NotFoundException * if media package with specified id and version does not exist * @throws SearchServiceDatabaseException * if an error occurs */ String getOrganizationId(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException; /** * Returns the number of mediapackages in persistent storage, including deleted entries. * * @return the number of mediapackages in storage * @throws SearchServiceDatabaseException * if an error occurs */ int countMediaPackages() throws SearchServiceDatabaseException; /** * Gets a single media package by its identifier. * * @param mediaPackageId * the media package identifier * @return the media package * @throws NotFoundException * if there is no media package with this identifier * @throws SearchServiceDatabaseException * if there is a problem communicating with the underlying data store */ MediaPackage getMediaPackage(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException; /** * Retrieves ACL for series with given ID. * * @param mediaPackageId * media package for which ACL will be retrieved * @return {@link AccessControlList} of media package or null if media package does not have ACL associated with it * @throws NotFoundException * if media package with given ID does not exist * @throws SearchServiceDatabaseException * if exception occurred */ AccessControlList getAccessControlList(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException; /** * Returns the modification date from the selected media package. * * @param mediaPackageId * the media package id to select * @return the modification date * @throws NotFoundException * if media package with specified id and version does not exist * @throws SearchServiceDatabaseException * if an error occurs */ Date getModificationDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException; /** * Returns the deletion date from the selected media package. * * @param mediaPackageId * the media package id to select * @return the deletion date * @throws NotFoundException * if media package with specified id does not exist * @throws SearchServiceDatabaseException * if an error occurs */ Date getDeletionDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException; /** * Removes media package from persistent storage. * * @param mediaPackageId * id of the media package to be removed * @param deletionDate * the deletion date to set * @throws SearchServiceDatabaseException * if exception occurs * @throws NotFoundException * if media package with specified id is not found */ void deleteMediaPackage(String mediaPackageId, Date deletionDate) throws SearchServiceDatabaseException, NotFoundException; /** * Store (or update) media package. * * @param mediaPackage * {@link MediaPackage} to store * @param acl * the acl of the media package * @param now * the store date * @throws SearchServiceDatabaseException * if exception occurs * @throws UnauthorizedException * if the current user is not authorized to perform this action */ void storeMediaPackage(MediaPackage mediaPackage, AccessControlList acl, Date now) throws SearchServiceDatabaseException, UnauthorizedException; }
./CrossVul/dataset_final_sorted/CWE-863/java/bad_1947_2
crossvul-java_data_bad_4254_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-863/java/bad_4254_0
crossvul-java_data_bad_1947_4
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.search.impl.solr; import static org.opencastproject.security.api.Permissions.Action.READ; import static org.opencastproject.security.api.Permissions.Action.WRITE; import static org.opencastproject.util.RequireUtil.notNull; import static org.opencastproject.util.data.Collections.flatMap; import static org.opencastproject.util.data.Collections.head; import static org.opencastproject.util.data.Collections.map; import static org.opencastproject.util.data.Option.option; import org.opencastproject.mediapackage.Attachment; import org.opencastproject.mediapackage.Catalog; import org.opencastproject.mediapackage.MediaPackage; import org.opencastproject.mediapackage.MediaPackageElement; import org.opencastproject.mediapackage.MediaPackageElements; import org.opencastproject.mediapackage.MediaPackageException; import org.opencastproject.mediapackage.MediaPackageParser; import org.opencastproject.mediapackage.MediaPackageReference; import org.opencastproject.metadata.api.MetadataValue; import org.opencastproject.metadata.api.StaticMetadata; import org.opencastproject.metadata.api.StaticMetadataService; import org.opencastproject.metadata.api.util.Interval; import org.opencastproject.metadata.dublincore.DCMIPeriod; import org.opencastproject.metadata.dublincore.DublinCore; import org.opencastproject.metadata.dublincore.DublinCoreCatalog; import org.opencastproject.metadata.dublincore.DublinCoreValue; import org.opencastproject.metadata.dublincore.EncodingSchemeUtils; import org.opencastproject.metadata.dublincore.Temporal; import org.opencastproject.metadata.mpeg7.AudioVisual; import org.opencastproject.metadata.mpeg7.FreeTextAnnotation; import org.opencastproject.metadata.mpeg7.KeywordAnnotation; import org.opencastproject.metadata.mpeg7.MediaDuration; import org.opencastproject.metadata.mpeg7.MediaTime; import org.opencastproject.metadata.mpeg7.MediaTimePoint; import org.opencastproject.metadata.mpeg7.Mpeg7Catalog; import org.opencastproject.metadata.mpeg7.Mpeg7CatalogService; import org.opencastproject.metadata.mpeg7.MultimediaContent; import org.opencastproject.metadata.mpeg7.MultimediaContentType; import org.opencastproject.metadata.mpeg7.SpatioTemporalDecomposition; import org.opencastproject.metadata.mpeg7.TextAnnotation; import org.opencastproject.metadata.mpeg7.Video; import org.opencastproject.metadata.mpeg7.VideoSegment; import org.opencastproject.metadata.mpeg7.VideoText; import org.opencastproject.search.api.SearchResultItem.SearchResultItemType; import org.opencastproject.search.impl.persistence.SearchServiceDatabaseException; import org.opencastproject.security.api.AccessControlEntry; import org.opencastproject.security.api.AccessControlList; import org.opencastproject.security.api.SecurityService; import org.opencastproject.security.api.UnauthorizedException; import org.opencastproject.series.api.SeriesException; import org.opencastproject.series.api.SeriesService; import org.opencastproject.util.NotFoundException; import org.opencastproject.util.SolrUtils; import org.opencastproject.util.data.Function; import org.opencastproject.util.data.Option; import org.opencastproject.workspace.api.Workspace; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.SolrParams; import org.apache.solr.servlet.SolrRequestParsers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedSet; import java.util.TreeSet; /** * Utility class used to manage the search index. */ public class SolrIndexManager { /** Logging facility */ private static final Logger logger = LoggerFactory.getLogger(SolrIndexManager.class); /** Connection to the database */ private SolrServer solrServer = null; /** * Factor multiplied to fine tune relevance and confidence impact on important keyword decision. importance = * RELEVANCE_BOOST * relevance + confidence */ private static final double RELEVANCE_BOOST = 2.0; /** Number of characters an important should have at least. */ private static final int MAX_CHAR = 3; /** Maximum number of important keywords to detect. */ private static final int MAX_IMPORTANT_COUNT = 10; /** List of metadata services sorted by priority in reverse order. */ private List<StaticMetadataService> mdServices; private SeriesService seriesService; private Mpeg7CatalogService mpeg7CatalogService; private Workspace workspace; private SecurityService securityService; /** Convert a DublinCoreValue into a date. */ private static Function<DublinCoreValue, Option<Date>> toDateF = new Function<DublinCoreValue, Option<Date>>() { @Override public Option<Date> apply(DublinCoreValue v) { return EncodingSchemeUtils.decodeTemporal(v).fold(new Temporal.Match<Option<Date>>() { @Override public Option<Date> period(DCMIPeriod period) { return option(period.getStart()); } @Override public Option<Date> instant(Date instant) { return Option.some(instant); } @Override public Option<Date> duration(long duration) { return Option.none(); } }); } }; /** Convert a DublinCoreValue into a duration (long). */ private static Function<DublinCoreValue, Option<Long>> toDurationF = new Function<DublinCoreValue, Option<Long>>() { @Override public Option<Long> apply(DublinCoreValue dublinCoreValue) { return option(EncodingSchemeUtils.decodeDuration(dublinCoreValue)); } }; /** Dynamic reference. */ public void setStaticMetadataServices(List<StaticMetadataService> mdServices) { this.mdServices = new ArrayList<StaticMetadataService>(mdServices); Collections.sort(this.mdServices, new Comparator<StaticMetadataService>() { @Override public int compare(StaticMetadataService a, StaticMetadataService b) { return b.getPriority() - a.getPriority(); } }); } /** * Creates a new management instance for the search index. * * @param connection * connection to the database */ public SolrIndexManager(SolrServer connection, Workspace workspace, List<StaticMetadataService> mdServices, SeriesService seriesService, Mpeg7CatalogService mpeg7CatalogService, SecurityService securityService) { this.solrServer = notNull(connection, "solr connection"); this.workspace = notNull(workspace, "workspace"); this.seriesService = notNull(seriesService, "series service"); this.mpeg7CatalogService = notNull(mpeg7CatalogService, "mpeg7 service"); this.securityService = notNull(securityService, "security service"); setStaticMetadataServices(notNull(mdServices, "metadata service")); } /** * Clears the search index. Make sure you know what you are doing. * * @throws SolrServerException * if an errors occurs while talking to solr */ public void clear() throws SolrServerException { try { solrServer.deleteByQuery("*:*"); solrServer.commit(); } catch (IOException e) { throw new SolrServerException(e); } } /** * Removes the entry with the given <code>id</code> from the database. The entry can either be a series or an episode. * * @param id * identifier of the series or episode to delete * @param deletionDate * the deletion date * @throws SolrServerException * if an errors occurs while talking to solr */ public boolean delete(String id, Date deletionDate) throws SolrServerException { try { // Load the existing episode QueryResponse solrResponse = null; try { SolrQuery query = new SolrQuery(Schema.ID + ":" + ClientUtils.escapeQueryChars(id) + " AND -" + Schema.OC_DELETED + ":[* TO *]"); solrResponse = solrServer.query(query); } catch (Exception e1) { throw new SolrServerException(e1); } // Did we find the episode? if (solrResponse.getResults().size() == 0) { logger.warn("Trying to delete non-existing media package {} from the search index", id); return false; } // Use all existing fields SolrDocument doc = solrResponse.getResults().get(0); SolrInputDocument inputDocument = new SolrInputDocument(); for (String field : doc.getFieldNames()) { inputDocument.setField(field, doc.get(field)); } // Set the oc_deleted field to the current date, then update Schema.setOcDeleted(inputDocument, deletionDate); solrServer.add(inputDocument); solrServer.commit(); return true; } catch (IOException e) { throw new SolrServerException(e); } } /** * Posts the media package to solr. Depending on what is referenced in the media package, the method might create one * or two entries: one for the episode and one for the series that the episode belongs to. * * This implementation of the search service removes all references to non "engage/download" media tracks * * @param sourceMediaPackage * the media package to post * @param acl * the access control list for this mediapackage * @param now * current date * @throws SolrServerException * if an errors occurs while talking to solr */ public boolean add(MediaPackage sourceMediaPackage, AccessControlList acl, Date now) throws SolrServerException, UnauthorizedException { try { SolrInputDocument episodeDocument = createEpisodeInputDocument(sourceMediaPackage, acl); Schema.setOcModified(episodeDocument, now); SolrInputDocument seriesDocument = createSeriesInputDocument(sourceMediaPackage.getSeries(), acl); if (seriesDocument != null) Schema.enrich(episodeDocument, seriesDocument); // If neither an episode nor a series was contained, there is no point in trying to update if (episodeDocument == null && seriesDocument == null) { logger.warn("Neither episode nor series metadata found"); return false; } // Post everything to the search index if (episodeDocument != null) solrServer.add(episodeDocument); if (seriesDocument != null) solrServer.add(seriesDocument); solrServer.commit(); return true; } catch (Exception e) { logger.error("Unable to add mediapackage {} to index", sourceMediaPackage.getIdentifier()); throw new SolrServerException(e); } } /** * Posts the media package to solr. Depending on what is referenced in the media package, the method might create one * or two entries: one for the episode and one for the series that the episode belongs to. * * This implementation of the search service removes all references to non "engage/download" media tracks * * @param sourceMediaPackage * the media package to post * @param acl * the access control list for this mediapackage * @param deletionDate * the deletion date * @param modificationDate * the modification date * @return <code>true</code> if successfully added * @throws SolrServerException * if an errors occurs while talking to solr */ public boolean add(MediaPackage sourceMediaPackage, AccessControlList acl, Date deletionDate, Date modificationDate) throws SolrServerException { try { SolrInputDocument episodeDocument = createEpisodeInputDocument(sourceMediaPackage, acl); SolrInputDocument seriesDocument = createSeriesInputDocument(sourceMediaPackage.getSeries(), acl); if (seriesDocument != null) Schema.enrich(episodeDocument, seriesDocument); Schema.setOcModified(episodeDocument, modificationDate); if (deletionDate != null) Schema.setOcDeleted(episodeDocument, deletionDate); solrServer.add(episodeDocument); solrServer.add(seriesDocument); solrServer.commit(); return true; } catch (Exception e) { logger.error("Unable to add mediapackage {} to index", sourceMediaPackage.getIdentifier()); try { solrServer.rollback(); } catch (IOException e1) { throw new SolrServerException(e1); } throw new SolrServerException(e); } } /** * Creates a solr input document for the episode metadata of the media package. * * @param mediaPackage * the media package * @param acl * the access control list for this mediapackage * @return an input document ready to be posted to solr * @throws MediaPackageException * if serialization of the media package fails */ private SolrInputDocument createEpisodeInputDocument(MediaPackage mediaPackage, AccessControlList acl) throws MediaPackageException, IOException { SolrInputDocument doc = new SolrInputDocument(); String mediaPackageId = mediaPackage.getIdentifier().toString(); // Fill the input document Schema.setId(doc, mediaPackageId); // / // OC specific fields Schema.setOcMediatype(doc, SearchResultItemType.AudioVisual.toString()); Schema.setOrganization(doc, securityService.getOrganization().getId()); Schema.setOcMediapackage(doc, MediaPackageParser.getAsXml(mediaPackage)); Schema.setOcElementtags(doc, tags(mediaPackage)); Schema.setOcElementflavors(doc, flavors(mediaPackage)); // Add cover Attachment[] cover = mediaPackage.getAttachments(MediaPackageElements.MEDIAPACKAGE_COVER_FLAVOR); if (cover != null && cover.length > 0) { Schema.setOcCover(doc, cover[0].getURI().toString()); } // / // Add standard dublin core fields // naive approach. works as long as only setters, not adders are available in the schema for (StaticMetadata md : getMetadata(mdServices, mediaPackage)) addEpisodeMetadata(doc, md); // / // Add mpeg7 logger.debug("Looking for mpeg-7 catalogs containing segment texts"); Catalog[] mpeg7Catalogs = mediaPackage.getCatalogs(MediaPackageElements.TEXTS); if (mpeg7Catalogs.length == 0) { logger.debug("No text catalogs found, trying segments only"); mpeg7Catalogs = mediaPackage.getCatalogs(MediaPackageElements.SEGMENTS); } // TODO: merge the segments from each mpeg7 if there is more than one mpeg7 catalog if (mpeg7Catalogs.length > 0) { try { Mpeg7Catalog mpeg7Catalog = loadMpeg7Catalog(mpeg7Catalogs[0]); addMpeg7Metadata(doc, mediaPackage, mpeg7Catalog); } catch (IOException e) { logger.error("Error loading mpeg7 catalog. Skipping catalog", e); } } else { logger.debug("No segmentation catalog found"); } // / // Add authorization setAuthorization(doc, securityService, acl); return doc; } static void addEpisodeMetadata(final SolrInputDocument doc, final StaticMetadata md) { Schema.fill(doc, new Schema.FieldCollector() { @Override public Option<String> getId() { return Option.none(); } @Override public Option<String> getOrganization() { return Option.none(); } @Override public Option<Date> getDcCreated() { return md.getCreated(); } @Override public Option<Long> getDcExtent() { return md.getExtent(); } @Override public Option<String> getDcLanguage() { return md.getLanguage(); } @Override public Option<String> getDcIsPartOf() { return md.getIsPartOf(); } @Override public Option<String> getDcReplaces() { return md.getReplaces(); } @Override public Option<String> getDcType() { return md.getType(); } @Override public Option<Date> getDcAvailableFrom() { return md.getAvailable().flatMap(new Function<Interval, Option<Date>>() { @Override public Option<Date> apply(Interval interval) { return interval.fold(new Interval.Match<Option<Date>>() { @Override public Option<Date> bounded(Date leftBound, Date rightBound) { return Option.some(leftBound); } @Override public Option<Date> leftInfinite(Date rightBound) { return Option.none(); } @Override public Option<Date> rightInfinite(Date leftBound) { return Option.some(leftBound); } }); } }); } @Override public Option<Date> getDcAvailableTo() { return md.getAvailable().flatMap(new Function<Interval, Option<Date>>() { @Override public Option<Date> apply(Interval interval) { return interval.fold(new Interval.Match<Option<Date>>() { @Override public Option<Date> bounded(Date leftBound, Date rightBound) { return Option.some(rightBound); } @Override public Option<Date> leftInfinite(Date rightBound) { return Option.some(rightBound); } @Override public Option<Date> rightInfinite(Date leftBound) { return Option.none(); } }); } }); } @Override public List<DField<String>> getDcTitle() { return fromMValue(md.getTitles()); } @Override public List<DField<String>> getDcSubject() { return fromMValue(md.getSubjects()); } @Override public List<DField<String>> getDcCreator() { return fromMValue(md.getCreators()); } @Override public List<DField<String>> getDcPublisher() { return fromMValue(md.getPublishers()); } @Override public List<DField<String>> getDcContributor() { return fromMValue(md.getContributors()); } @Override public List<DField<String>> getDcDescription() { return fromMValue(md.getDescription()); } @Override public List<DField<String>> getDcRightsHolder() { return fromMValue(md.getRightsHolders()); } @Override public List<DField<String>> getDcSpatial() { return fromMValue(md.getSpatials()); } @Override public List<DField<String>> getDcAccessRights() { return fromMValue(md.getAccessRights()); } @Override public List<DField<String>> getDcLicense() { return fromMValue(md.getLicenses()); } @Override public Option<String> getOcMediatype() { return Option.none(); // set elsewhere } @Override public Option<String> getOcMediapackage() { return Option.none(); // set elsewhere } @Override public Option<String> getOcKeywords() { return Option.none(); // set elsewhere } @Override public Option<String> getOcCover() { return Option.none(); // set elsewhere } @Override public Option<Date> getOcModified() { return Option.none(); // set elsewhere } @Override public Option<Date> getOcDeleted() { return Option.none(); // set elsewhere } @Override public Option<String> getOcElementtags() { return Option.none(); // set elsewhere } @Override public Option<String> getOcElementflavors() { return Option.none(); // set elsewhere } @Override public List<DField<String>> getOcAcl() { return Collections.EMPTY_LIST; // set elsewhere } @Override public List<DField<String>> getSegmentText() { return Collections.EMPTY_LIST; // set elsewhere } @Override public List<DField<String>> getSegmentHint() { return Collections.EMPTY_LIST; // set elsewhere } }); } static List<DField<String>> fromMValue(List<MetadataValue<String>> as) { return map(as, new ArrayList<DField<String>>(), new Function<MetadataValue<String>, DField<String>>() { @Override public DField<String> apply(MetadataValue<String> v) { return new DField<String>(v.getValue(), v.getLanguage()); } }); } static List<DField<String>> fromDCValue(List<DublinCoreValue> as) { return map(as, new ArrayList<DField<String>>(), new Function<DublinCoreValue, DField<String>>() { @Override public DField<String> apply(DublinCoreValue v) { return new DField<String>(v.getValue(), v.getLanguage()); } }); } /** * Adds authorization fields to the solr document. * * @param doc * the solr document * @param acl * the access control list */ static void setAuthorization(SolrInputDocument doc, SecurityService securityService, AccessControlList acl) { Map<String, List<String>> permissions = new HashMap<String, List<String>>(); // Define containers for common permissions List<String> reads = new ArrayList<String>(); permissions.put(READ.toString(), reads); List<String> writes = new ArrayList<String>(); permissions.put(WRITE.toString(), writes); String adminRole = securityService.getOrganization().getAdminRole(); // The admin user can read and write if (adminRole != null) { reads.add(adminRole); writes.add(adminRole); } for (AccessControlEntry entry : acl.getEntries()) { if (!entry.isAllow()) { logger.warn("Search service does not support denial via ACL, ignoring {}", entry); continue; } List<String> actionPermissions = permissions.get(entry.getAction()); /* * MH-8353 a series could have a permission defined we don't know how to handle -DH */ if (actionPermissions == null) { logger.warn("Search service doesn't know how to handle action: " + entry.getAction()); continue; } if (acl == null) { actionPermissions = new ArrayList<String>(); permissions.put(entry.getAction(), actionPermissions); } actionPermissions.add(entry.getRole()); } // Write the permissions to the solr document for (Map.Entry<String, List<String>> entry : permissions.entrySet()) { Schema.setOcAcl(doc, new DField<String>(mkString(entry.getValue(), " "), entry.getKey())); } } static String mkString(Collection<?> as, String sep) { StringBuffer b = new StringBuffer(); for (Object a : as) { b.append(a).append(sep); } return b.substring(0, b.length() - sep.length()); } private Mpeg7Catalog loadMpeg7Catalog(Catalog catalog) throws IOException { try (InputStream in = workspace.read(catalog.getURI())) { return mpeg7CatalogService.load(in); } catch (NotFoundException e) { throw new IOException("Unable to load metadata from mpeg7 catalog " + catalog); } } /** * Creates a solr input document for the series metadata of the media package. * * @param seriesId * the id of the series * @param acl * the access control list for this mediapackage * @return an input document ready to be posted to solr or null */ private SolrInputDocument createSeriesInputDocument(String seriesId, AccessControlList acl) throws IOException, UnauthorizedException { if (seriesId == null) return null; DublinCoreCatalog dc = null; try { dc = seriesService.getSeries(seriesId); } catch (SeriesException e) { logger.debug("No series dublincore found for series id " + seriesId); return null; } catch (NotFoundException e) { logger.debug("No series dublincore found for series id " + seriesId); return null; } SolrInputDocument doc = new SolrInputDocument(); // Populate document with existing data try { StringBuffer query = new StringBuffer("q="); query = query.append(Schema.ID).append(":").append(SolrUtils.clean(seriesId)); SolrParams params = SolrRequestParsers.parseQueryString(query.toString()); QueryResponse solrResponse = solrServer.query(params); if (solrResponse.getResults().size() > 0) { SolrDocument existingSolrDocument = solrResponse.getResults().get(0); for (String fieldName : existingSolrDocument.getFieldNames()) { doc.addField(fieldName, existingSolrDocument.getFieldValue(fieldName)); } } } catch (Exception e) { logger.error("Error trying to load series " + seriesId, e); } // Fill document Schema.setId(doc, seriesId); // OC specific fields Schema.setOrganization(doc, securityService.getOrganization().getId()); Schema.setOcMediatype(doc, SearchResultItemType.Series.toString()); Schema.setOcModified(doc, new Date()); // DC fields addSeriesMetadata(doc, dc); // Authorization setAuthorization(doc, securityService, acl); return doc; } /** * Add the standard dublin core fields to a series document. * * @param doc * the solr document to fill * @param dc * the dublin core catalog to get the data from */ static void addSeriesMetadata(final SolrInputDocument doc, final DublinCoreCatalog dc) throws IOException { Schema.fill(doc, new Schema.FieldCollector() { @Override public Option<String> getId() { return Option.some(dc.getFirst(DublinCore.PROPERTY_IDENTIFIER)); } @Override public Option<String> getOrganization() { return Option.none(); } @Override public Option<Date> getDcCreated() { return head(dc.get(DublinCore.PROPERTY_CREATED)).flatMap(toDateF); } @Override public Option<Long> getDcExtent() { return head(dc.get(DublinCore.PROPERTY_EXTENT)).flatMap(toDurationF); } @Override public Option<String> getDcLanguage() { return option(dc.getFirst(DublinCore.PROPERTY_LANGUAGE)); } @Override public Option<String> getDcIsPartOf() { return option(dc.getFirst(DublinCore.PROPERTY_IS_PART_OF)); } @Override public Option<String> getDcReplaces() { return option(dc.getFirst(DublinCore.PROPERTY_REPLACES)); } @Override public Option<String> getDcType() { return option(dc.getFirst(DublinCore.PROPERTY_TYPE)); } @Override public Option<Date> getDcAvailableFrom() { return option(dc.getFirst(DublinCore.PROPERTY_AVAILABLE)).flatMap(new Function<String, Option<Date>>() { @Override public Option<Date> apply(String s) { return option(EncodingSchemeUtils.decodePeriod(s).getStart()); } }); } @Override public Option<Date> getDcAvailableTo() { return option(dc.getFirst(DublinCore.PROPERTY_AVAILABLE)).flatMap(new Function<String, Option<Date>>() { @Override public Option<Date> apply(String s) { return option(EncodingSchemeUtils.decodePeriod(s).getEnd()); } }); } @Override public List<DField<String>> getDcTitle() { return fromDCValue(dc.get(DublinCore.PROPERTY_TITLE)); } @Override public List<DField<String>> getDcSubject() { return fromDCValue(dc.get(DublinCore.PROPERTY_SUBJECT)); } @Override public List<DField<String>> getDcCreator() { return fromDCValue(dc.get(DublinCore.PROPERTY_CREATOR)); } @Override public List<DField<String>> getDcPublisher() { return fromDCValue(dc.get(DublinCore.PROPERTY_PUBLISHER)); } @Override public List<DField<String>> getDcContributor() { return fromDCValue(dc.get(DublinCore.PROPERTY_CONTRIBUTOR)); } @Override public List<DField<String>> getDcDescription() { return fromDCValue(dc.get(DublinCore.PROPERTY_DESCRIPTION)); } @Override public List<DField<String>> getDcRightsHolder() { return fromDCValue(dc.get(DublinCore.PROPERTY_RIGHTS_HOLDER)); } @Override public List<DField<String>> getDcSpatial() { return fromDCValue(dc.get(DublinCore.PROPERTY_SPATIAL)); } @Override public List<DField<String>> getDcAccessRights() { return fromDCValue(dc.get(DublinCore.PROPERTY_ACCESS_RIGHTS)); } @Override public List<DField<String>> getDcLicense() { return fromDCValue(dc.get(DublinCore.PROPERTY_LICENSE)); } @Override public Option<String> getOcMediatype() { return Option.none(); } @Override public Option<String> getOcMediapackage() { return Option.none(); } @Override public Option<String> getOcKeywords() { return Option.none(); } @Override public Option<String> getOcCover() { return Option.none(); } @Override public Option<Date> getOcModified() { return Option.none(); } @Override public Option<Date> getOcDeleted() { return Option.none(); } @Override public Option<String> getOcElementtags() { return Option.none(); } @Override public Option<String> getOcElementflavors() { return Option.none(); } @Override public List<DField<String>> getOcAcl() { return Collections.EMPTY_LIST; } @Override public List<DField<String>> getSegmentText() { return Collections.EMPTY_LIST; } @Override public List<DField<String>> getSegmentHint() { return Collections.EMPTY_LIST; } }); } /** * Add the mpeg 7 catalog data to the solr document. * * @param doc * the input document to the solr index * @param mpeg7 * the mpeg7 catalog */ @SuppressWarnings("unchecked") static void addMpeg7Metadata(SolrInputDocument doc, MediaPackage mediaPackage, Mpeg7Catalog mpeg7) { // Check for multimedia content if (!mpeg7.multimediaContent().hasNext()) { logger.warn("Mpeg-7 doesn't contain multimedia content"); return; } // Get the content duration by looking at the first content track. This // of course assumes that all tracks are equally long. MultimediaContent<? extends MultimediaContentType> mc = mpeg7.multimediaContent().next(); MultimediaContentType mct = mc.elements().next(); MediaTime mediaTime = mct.getMediaTime(); Schema.setDcExtent(doc, mediaTime.getMediaDuration().getDurationInMilliseconds()); // Check if the keywords have been filled by (manually) added dublin // core data. If not, look for the most relevant fields in mpeg-7. SortedSet<TextAnnotation> sortedAnnotations = null; if (!"".equals(Schema.getOcKeywords(doc))) { sortedAnnotations = new TreeSet<TextAnnotation>(new Comparator<TextAnnotation>() { @Override public int compare(TextAnnotation a1, TextAnnotation a2) { if ((RELEVANCE_BOOST * a1.getRelevance() + a1.getConfidence()) > (RELEVANCE_BOOST * a2.getRelevance() + a2 .getConfidence())) return -1; else if ((RELEVANCE_BOOST * a1.getRelevance() + a1.getConfidence()) < (RELEVANCE_BOOST * a2.getRelevance() + a2 .getConfidence())) return 1; return 0; } }); } // Iterate over the tracks and extract keywords and hints Iterator<MultimediaContent<? extends MultimediaContentType>> mmIter = mpeg7.multimediaContent(); int segmentCount = 0; while (mmIter.hasNext()) { MultimediaContent<?> multimediaContent = mmIter.next(); // We need to process visual segments first, due to the way they are handled in the ui. for (Iterator<?> iterator = multimediaContent.elements(); iterator.hasNext();) { MultimediaContentType type = (MultimediaContentType) iterator.next(); if (!(type instanceof Video) && !(type instanceof AudioVisual)) continue; // for every segment in the current multimedia content track Video video = (Video) type; Iterator<VideoSegment> vsegments = (Iterator<VideoSegment>) video.getTemporalDecomposition().segments(); while (vsegments.hasNext()) { VideoSegment segment = vsegments.next(); StringBuffer segmentText = new StringBuffer(); StringBuffer hintField = new StringBuffer(); // Collect the video text elements to a segment text SpatioTemporalDecomposition spt = segment.getSpatioTemporalDecomposition(); if (spt != null) { for (VideoText videoText : spt.getVideoText()) { if (segmentText.length() > 0) segmentText.append(" "); segmentText.append(videoText.getText().getText()); // TODO: Add hint on bounding box } } // Add keyword annotations Iterator<TextAnnotation> textAnnotations = segment.textAnnotations(); while (textAnnotations.hasNext()) { TextAnnotation textAnnotation = textAnnotations.next(); Iterator<?> kwIter = textAnnotation.keywordAnnotations(); while (kwIter.hasNext()) { KeywordAnnotation keywordAnnotation = (KeywordAnnotation) kwIter.next(); if (segmentText.length() > 0) segmentText.append(" "); segmentText.append(keywordAnnotation.getKeyword()); } } // Add free text annotations Iterator<TextAnnotation> freeIter = segment.textAnnotations(); if (freeIter.hasNext()) { Iterator<FreeTextAnnotation> freeTextIter = freeIter.next().freeTextAnnotations(); while (freeTextIter.hasNext()) { FreeTextAnnotation freeTextAnnotation = freeTextIter.next(); if (segmentText.length() > 0) segmentText.append(" "); segmentText.append(freeTextAnnotation.getText()); } } // add segment text to solr document Schema.setSegmentText(doc, new DField<String>(segmentText.toString(), Integer.toString(segmentCount))); // get the segments time properties MediaTimePoint timepoint = segment.getMediaTime().getMediaTimePoint(); MediaDuration duration = segment.getMediaTime().getMediaDuration(); // TODO: define a class with hint field constants hintField.append("time=" + timepoint.getTimeInMilliseconds() + "\n"); hintField.append("duration=" + duration.getDurationInMilliseconds() + "\n"); // Look for preview images. Their characteristics are that they are // attached as attachments with a flavor of preview/<something>. String time = timepoint.toString(); for (Attachment slide : mediaPackage.getAttachments(MediaPackageElements.PRESENTATION_SEGMENT_PREVIEW)) { MediaPackageReference ref = slide.getReference(); if (ref != null && time.equals(ref.getProperty("time"))) { hintField.append("preview"); hintField.append("."); hintField.append(ref.getIdentifier()); hintField.append("="); hintField.append(slide.getURI().toString()); hintField.append("\n"); } } logger.trace("Adding segment: " + timepoint.toString()); Schema.setSegmentHint(doc, new DField<String>(hintField.toString(), Integer.toString(segmentCount))); // increase segment counter segmentCount++; } } } // Put the most important keywords into a special solr field if (sortedAnnotations != null) { Schema.setOcKeywords(doc, importantKeywordsString(sortedAnnotations).toString()); } } /** * Generates a string with the most important kewords from the text annotation. * * @param sortedAnnotations * @return The keyword string. */ static StringBuffer importantKeywordsString(SortedSet<TextAnnotation> sortedAnnotations) { // important keyword: // - high relevance // - high confidence // - occur often // - more than MAX_CHAR chars // calculate keyword occurences (histogram) and importance ArrayList<String> list = new ArrayList<String>(); Iterator<TextAnnotation> textAnnotations = sortedAnnotations.iterator(); TextAnnotation textAnnotation = null; String keyword = null; HashMap<String, Integer> histogram = new HashMap<String, Integer>(); HashMap<String, Double> importance = new HashMap<String, Double>(); int occ = 0; double imp; while (textAnnotations.hasNext()) { textAnnotation = textAnnotations.next(); Iterator<KeywordAnnotation> keywordAnnotations = textAnnotation.keywordAnnotations(); while (keywordAnnotations.hasNext()) { KeywordAnnotation annotation = keywordAnnotations.next(); keyword = annotation.getKeyword().toLowerCase(); if (keyword.length() > MAX_CHAR) { occ = 0; if (histogram.keySet().contains(keyword)) { occ = histogram.get(keyword); } histogram.put(keyword, occ + 1); // here the importance value is calculated // from relevance, confidence and frequency of occurence. imp = (RELEVANCE_BOOST * getMaxRelevance(keyword, sortedAnnotations) + getMaxConfidence(keyword, sortedAnnotations)) * (occ + 1); importance.put(keyword, imp); } } } // get the MAX_IMPORTANT_COUNT most important keywords StringBuffer buf = new StringBuffer(); while (list.size() < MAX_IMPORTANT_COUNT && importance.size() > 0) { double max = 0.0; String maxKeyword = null; // get maximum from importance list for (Entry<String, Double> entry : importance.entrySet()) { keyword = entry.getKey(); if (max < entry.getValue()) { max = entry.getValue(); maxKeyword = keyword; } } // pop maximum importance.remove(maxKeyword); // append keyword to string if (buf.length() > 0) buf.append(" "); buf.append(maxKeyword); } return buf; } /** * Gets the maximum confidence for a given keyword in the text annotation. * * @param keyword * @param sortedAnnotations * @return The maximum confidence value. */ static double getMaxConfidence(String keyword, SortedSet<TextAnnotation> sortedAnnotations) { double max = 0.0; String needle = null; TextAnnotation textAnnotation = null; Iterator<TextAnnotation> textAnnotations = sortedAnnotations.iterator(); while (textAnnotations.hasNext()) { textAnnotation = textAnnotations.next(); Iterator<KeywordAnnotation> keywordAnnotations = textAnnotation.keywordAnnotations(); while (keywordAnnotations.hasNext()) { KeywordAnnotation ann = keywordAnnotations.next(); needle = ann.getKeyword().toLowerCase(); if (keyword.equals(needle)) { if (max < textAnnotation.getConfidence()) { max = textAnnotation.getConfidence(); } } } } return max; } /** * Gets the maximum relevance for a given keyword in the text annotation. * * @param keyword * @param sortedAnnotations * @return The maximum relevance value. */ static double getMaxRelevance(String keyword, SortedSet<TextAnnotation> sortedAnnotations) { double max = 0.0; String needle = null; TextAnnotation textAnnotation = null; Iterator<TextAnnotation> textAnnotations = sortedAnnotations.iterator(); while (textAnnotations.hasNext()) { textAnnotation = textAnnotations.next(); Iterator<KeywordAnnotation> keywordAnnotations = textAnnotation.keywordAnnotations(); while (keywordAnnotations.hasNext()) { KeywordAnnotation ann = keywordAnnotations.next(); needle = ann.getKeyword().toLowerCase(); if (keyword.equals(needle)) { if (max < textAnnotation.getRelevance()) { max = textAnnotation.getRelevance(); } } } } return max; } /** * Get metadata from all registered metadata services. */ static List<StaticMetadata> getMetadata(final List<StaticMetadataService> mdServices, final MediaPackage mp) { return flatMap(mdServices, new ArrayList<StaticMetadata>(), new Function<StaticMetadataService, Collection<StaticMetadata>>() { @Override public Collection<StaticMetadata> apply(StaticMetadataService s) { StaticMetadata md = s.getMetadata(mp); return md != null ? Arrays.asList(md) : Collections.<StaticMetadata> emptyList(); } }); } /** * Return all media package tags as a space separated string. */ static String tags(MediaPackage mp) { StringBuilder sb = new StringBuilder(); for (MediaPackageElement element : mp.getElements()) { for (String tag : element.getTags()) { sb.append(tag); sb.append(" "); } } return sb.toString(); } /** * Return all media package flavors as a space separated string. */ static String flavors(MediaPackage mp) { StringBuilder sb = new StringBuilder(); for (MediaPackageElement element : mp.getElements()) { if (element.getFlavor() != null) { sb.append(element.getFlavor().toString()); sb.append(" "); } } return sb.toString(); } /** * Returns number of entries in search index, across all organizations. * * @return number of entries in search index * @throws SearchServiceDatabaseException * if count cannot be retrieved */ public long count() throws SearchServiceDatabaseException { try { QueryResponse response = solrServer.query(new SolrQuery("*:*")); return response.getResults().getNumFound(); } catch (SolrServerException e) { throw new SearchServiceDatabaseException(e); } } }
./CrossVul/dataset_final_sorted/CWE-863/java/bad_1947_4
crossvul-java_data_good_1947_2
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.search.impl.persistence; import org.opencastproject.mediapackage.MediaPackage; import org.opencastproject.security.api.AccessControlList; import org.opencastproject.security.api.UnauthorizedException; import org.opencastproject.util.NotFoundException; import org.opencastproject.util.data.Tuple; import java.util.Collection; import java.util.Date; import java.util.Iterator; /** * API that defines persistent storage of series. * */ public interface SearchServiceDatabase { /** * Returns all search entries in persistent storage. * * @return {@link Tuple} array representing stored media packages * @throws SearchServiceDatabaseException * if exception occurs */ Iterator<Tuple<MediaPackage, String>> getAllMediaPackages() throws SearchServiceDatabaseException; /** * Returns the organization id of the selected media package * * @param mediaPackageId * the media package id to select * @return the organization id * @throws NotFoundException * if media package with specified id and version does not exist * @throws SearchServiceDatabaseException * if an error occurs */ String getOrganizationId(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException; /** * Returns the number of mediapackages in persistent storage, including deleted entries. * * @return the number of mediapackages in storage * @throws SearchServiceDatabaseException * if an error occurs */ int countMediaPackages() throws SearchServiceDatabaseException; /** * Gets a single media package by its identifier. * * @param mediaPackageId * the media package identifier * @return the media package * @throws NotFoundException * if there is no media package with this identifier * @throws SearchServiceDatabaseException * if there is a problem communicating with the underlying data store */ MediaPackage getMediaPackage(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException; /** * Gets media packages from a specific series * * @param seriesId * the series identifier * @return collection of media packages * @throws SearchServiceDatabaseException * if there is a problem communicating with the underlying data store */ Collection<MediaPackage> getMediaPackages(String seriesId) throws SearchServiceDatabaseException; /** * Retrieves ACL for episode with given ID. * * @param mediaPackageId * media package for which ACL will be retrieved * @return {@link AccessControlList} of media package or null if media package does not have ACL associated with it * @throws NotFoundException * if media package with given ID does not exist * @throws SearchServiceDatabaseException * if exception occurred */ AccessControlList getAccessControlList(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException; /** * Retrieves ACLs for series with given ID. * * @param seriesId * series identifier for which ACL will be retrieved * @param excludeIds * list of media package identifier to exclude from the list * @return Collection of {@link AccessControlList} of media packages from the series * @throws SearchServiceDatabaseException * if exception occurred */ Collection<AccessControlList> getAccessControlLists(String seriesId, String ... excludeIds) throws SearchServiceDatabaseException; /** * Returns the modification date from the selected media package. * * @param mediaPackageId * the media package id to select * @return the modification date * @throws NotFoundException * if media package with specified id and version does not exist * @throws SearchServiceDatabaseException * if an error occurs */ Date getModificationDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException; /** * Returns the deletion date from the selected media package. * * @param mediaPackageId * the media package id to select * @return the deletion date * @throws NotFoundException * if media package with specified id does not exist * @throws SearchServiceDatabaseException * if an error occurs */ Date getDeletionDate(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException; /** * Removes media package from persistent storage. * * @param mediaPackageId * id of the media package to be removed * @param deletionDate * the deletion date to set * @throws SearchServiceDatabaseException * if exception occurs * @throws NotFoundException * if media package with specified id is not found */ void deleteMediaPackage(String mediaPackageId, Date deletionDate) throws SearchServiceDatabaseException, NotFoundException; /** * Store (or update) media package. * * @param mediaPackage * {@link MediaPackage} to store * @param acl * the acl of the media package * @param now * the store date * @throws SearchServiceDatabaseException * if exception occurs * @throws UnauthorizedException * if the current user is not authorized to perform this action */ void storeMediaPackage(MediaPackage mediaPackage, AccessControlList acl, Date now) throws SearchServiceDatabaseException, UnauthorizedException; }
./CrossVul/dataset_final_sorted/CWE-863/java/good_1947_2
crossvul-java_data_bad_4254_3
package com.zrlog.web.handler; import com.hibegin.common.util.IOUtil; import com.hibegin.common.util.http.HttpUtil; import com.hibegin.common.util.http.handle.CloseResponseHandle; import com.jfinal.core.JFinal; import com.jfinal.handler.Handler; import com.zrlog.common.Constants; import com.zrlog.common.vo.AdminTokenVO; import com.zrlog.model.User; import com.zrlog.service.AdminTokenService; import com.zrlog.service.AdminTokenThreadLocal; import com.zrlog.service.PluginHelper; import com.zrlog.util.BlogBuildInfoUtil; import org.apache.http.Header; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 这个类负责了对所有的插件路由的代理中转给插件服务(及plugin-core.jar这个进程),使用的是Handler而非Interception也是由于Interception * 不处理静态请求。 * 目前插件服务拦截了 * 1./admin/plugins/* (进行权限检查) * 2./plugin/* /p/* (是plugin的短路由,代码逻辑上是不区分的,不检查权限) * <p> * 如果想了解更多关于插件的实现可以浏览这篇文章 http://blog.zrlog.com/post/zrlog-plugin-dev */ public class PluginHandler extends Handler { private static final Logger LOGGER = Logger.getLogger(PluginHandler.class); private AdminTokenService adminTokenService = new AdminTokenService(); private List<String> pluginHandlerPaths = Arrays.asList("/admin/plugins/", "/plugin/", "/p/"); @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) { //便于Wappalyzer读取 response.addHeader("X-ZrLog", BlogBuildInfoUtil.getVersion()); boolean isPluginPath = false; for (String path : pluginHandlerPaths) { if (target.startsWith(path)) { isPluginPath = true; } } if (isPluginPath) { try { Map.Entry<AdminTokenVO, User> entry = adminTokenService.getAdminTokenVOUserEntry(request); if (entry != null) { adminTokenService.setAdminToken(entry.getValue(), entry.getKey().getSessionId(), entry.getKey().getProtocol(), request, response); } if (target.startsWith("/admin/plugins/")) { try { adminPermission(target, request, response); } catch (IOException | InstantiationException e) { LOGGER.error(e); } } else if (target.startsWith("/plugin/") || target.startsWith("/p/")) { try { visitorPermission(target, request, response); } catch (IOException | InstantiationException e) { LOGGER.error(e); } } } finally { isHandled[0] = true; } } else { this.next.handle(target, request, response, isHandled); } } /** * 检查是否登陆,未登陆的请求直接放回403的错误页面 * * @param target * @param request * @param response * @throws IOException * @throws InstantiationException */ private void adminPermission(String target, HttpServletRequest request, HttpServletResponse response) throws IOException, InstantiationException { if (AdminTokenThreadLocal.getUser() != null) { accessPlugin(target.replace("/admin/plugins", ""), request, response); } else { response.sendRedirect(request.getContextPath() + "/admin/login?redirectFrom=" + request.getRequestURL() + (request.getQueryString() != null ? "?" + request.getQueryString() : "")); } } /** * 不检查是否登陆,错误请求直接直接转化为403 * * @param target * @param request * @param response * @throws IOException * @throws InstantiationException */ private void visitorPermission(String target, HttpServletRequest request, HttpServletResponse response) throws IOException, InstantiationException { if (!accessPlugin(target.replace("/plugin", "").replace("/p", ""), request, response)) { response.sendError(403); } } /** * 代理中转HTTP请求,目前仅支持,GET,POST 请求方式的中转。 * * @param uri * @param request * @param response * @return true 表示请求正常执行,false 代表遇到了一些问题 * @throws IOException * @throws InstantiationException */ private boolean accessPlugin(String uri, HttpServletRequest request, HttpServletResponse response) throws IOException, InstantiationException { CloseResponseHandle handle = getContext(uri, request.getMethod(), request, true); try { if (handle.getT() != null && handle.getT().getEntity() != null) { response.setStatus(handle.getT().getStatusLine().getStatusCode()); //防止多次被Transfer-Encoding handle.getT().removeHeaders("Transfer-Encoding"); for (Header header : handle.getT().getAllHeaders()) { response.addHeader(header.getName(), header.getValue()); } //将插件服务的HTTP的body返回给调用者 byte[] bytes = IOUtil.getByteByInputStream(handle.getT().getEntity().getContent()); response.addHeader("Content-Length", Integer.valueOf(bytes.length).toString()); response.getOutputStream().write(bytes); response.getOutputStream().close(); return true; } else { return false; } } finally { handle.close(); } } public static CloseResponseHandle getContext(String uri, String method, HttpServletRequest request, boolean disableRedirect) throws IOException, InstantiationException { String pluginServerHttp = Constants.pluginServer; CloseableHttpResponse httpResponse; CloseResponseHandle handle = new CloseResponseHandle(); HttpUtil httpUtil = disableRedirect ? HttpUtil.getDisableRedirectInstance() : HttpUtil.getInstance(); //GET请求不关心request.getInputStream() 的数据 if (method.equals(request.getMethod()) && "GET".equalsIgnoreCase(method)) { httpResponse = httpUtil.sendGetRequest(pluginServerHttp + uri, request.getParameterMap(), handle, PluginHelper.genHeaderMapByRequest(request)).getT(); } else { //如果是表单数据提交不关心请求头,反之将所有请求头都发到插件服务 if ("application/x-www-form-urlencoded".equals(request.getContentType())) { httpResponse = httpUtil.sendPostRequest(pluginServerHttp + uri, request.getParameterMap(), handle, PluginHelper.genHeaderMapByRequest(request)).getT(); } else { httpResponse = httpUtil.sendPostRequest(pluginServerHttp + uri + "?" + request.getQueryString(), IOUtil.getByteByInputStream(request.getInputStream()), handle, PluginHelper.genHeaderMapByRequest(request)).getT(); } } //添加插件服务的HTTP响应头到调用者响应头里面 if (httpResponse != null) { Map<String, String> headerMap = new HashMap<>(); Header[] headers = httpResponse.getAllHeaders(); for (Header header : headers) { headerMap.put(header.getName(), header.getValue()); } if (JFinal.me().getConstants().getDevMode()) { LOGGER.info(uri + " --------------------------------- response"); } for (Map.Entry<String, String> t : headerMap.entrySet()) { if (JFinal.me().getConstants().getDevMode()) { LOGGER.info("key " + t.getKey() + " value-> " + t.getValue()); } } } return handle; } }
./CrossVul/dataset_final_sorted/CWE-863/java/bad_4254_3
crossvul-java_data_good_1947_4
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.search.impl.solr; import static org.opencastproject.security.api.Permissions.Action.READ; import static org.opencastproject.security.api.Permissions.Action.WRITE; import static org.opencastproject.util.RequireUtil.notNull; import static org.opencastproject.util.data.Collections.flatMap; import static org.opencastproject.util.data.Collections.head; import static org.opencastproject.util.data.Collections.map; import static org.opencastproject.util.data.Option.option; import org.opencastproject.mediapackage.Attachment; import org.opencastproject.mediapackage.Catalog; import org.opencastproject.mediapackage.MediaPackage; import org.opencastproject.mediapackage.MediaPackageElement; import org.opencastproject.mediapackage.MediaPackageElements; import org.opencastproject.mediapackage.MediaPackageException; import org.opencastproject.mediapackage.MediaPackageParser; import org.opencastproject.mediapackage.MediaPackageReference; import org.opencastproject.metadata.api.MetadataValue; import org.opencastproject.metadata.api.StaticMetadata; import org.opencastproject.metadata.api.StaticMetadataService; import org.opencastproject.metadata.api.util.Interval; import org.opencastproject.metadata.dublincore.DCMIPeriod; import org.opencastproject.metadata.dublincore.DublinCore; import org.opencastproject.metadata.dublincore.DublinCoreCatalog; import org.opencastproject.metadata.dublincore.DublinCoreValue; import org.opencastproject.metadata.dublincore.EncodingSchemeUtils; import org.opencastproject.metadata.dublincore.Temporal; import org.opencastproject.metadata.mpeg7.AudioVisual; import org.opencastproject.metadata.mpeg7.FreeTextAnnotation; import org.opencastproject.metadata.mpeg7.KeywordAnnotation; import org.opencastproject.metadata.mpeg7.MediaDuration; import org.opencastproject.metadata.mpeg7.MediaTime; import org.opencastproject.metadata.mpeg7.MediaTimePoint; import org.opencastproject.metadata.mpeg7.Mpeg7Catalog; import org.opencastproject.metadata.mpeg7.Mpeg7CatalogService; import org.opencastproject.metadata.mpeg7.MultimediaContent; import org.opencastproject.metadata.mpeg7.MultimediaContentType; import org.opencastproject.metadata.mpeg7.SpatioTemporalDecomposition; import org.opencastproject.metadata.mpeg7.TextAnnotation; import org.opencastproject.metadata.mpeg7.Video; import org.opencastproject.metadata.mpeg7.VideoSegment; import org.opencastproject.metadata.mpeg7.VideoText; import org.opencastproject.search.api.SearchResultItem.SearchResultItemType; import org.opencastproject.search.impl.persistence.SearchServiceDatabaseException; import org.opencastproject.security.api.AccessControlEntry; import org.opencastproject.security.api.AccessControlList; import org.opencastproject.security.api.SecurityService; import org.opencastproject.security.api.UnauthorizedException; import org.opencastproject.series.api.SeriesException; import org.opencastproject.series.api.SeriesService; import org.opencastproject.util.NotFoundException; import org.opencastproject.util.SolrUtils; import org.opencastproject.util.data.Function; import org.opencastproject.util.data.Option; import org.opencastproject.workspace.api.Workspace; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.SolrParams; import org.apache.solr.servlet.SolrRequestParsers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedSet; import java.util.TreeSet; /** * Utility class used to manage the search index. */ public class SolrIndexManager { /** Logging facility */ private static final Logger logger = LoggerFactory.getLogger(SolrIndexManager.class); /** Connection to the database */ private SolrServer solrServer = null; /** * Factor multiplied to fine tune relevance and confidence impact on important keyword decision. importance = * RELEVANCE_BOOST * relevance + confidence */ private static final double RELEVANCE_BOOST = 2.0; /** Number of characters an important should have at least. */ private static final int MAX_CHAR = 3; /** Maximum number of important keywords to detect. */ private static final int MAX_IMPORTANT_COUNT = 10; /** List of metadata services sorted by priority in reverse order. */ private List<StaticMetadataService> mdServices; private SeriesService seriesService; private Mpeg7CatalogService mpeg7CatalogService; private Workspace workspace; private SecurityService securityService; /** Convert a DublinCoreValue into a date. */ private static Function<DublinCoreValue, Option<Date>> toDateF = new Function<DublinCoreValue, Option<Date>>() { @Override public Option<Date> apply(DublinCoreValue v) { return EncodingSchemeUtils.decodeTemporal(v).fold(new Temporal.Match<Option<Date>>() { @Override public Option<Date> period(DCMIPeriod period) { return option(period.getStart()); } @Override public Option<Date> instant(Date instant) { return Option.some(instant); } @Override public Option<Date> duration(long duration) { return Option.none(); } }); } }; /** Convert a DublinCoreValue into a duration (long). */ private static Function<DublinCoreValue, Option<Long>> toDurationF = new Function<DublinCoreValue, Option<Long>>() { @Override public Option<Long> apply(DublinCoreValue dublinCoreValue) { return option(EncodingSchemeUtils.decodeDuration(dublinCoreValue)); } }; /** Dynamic reference. */ public void setStaticMetadataServices(List<StaticMetadataService> mdServices) { this.mdServices = new ArrayList<StaticMetadataService>(mdServices); Collections.sort(this.mdServices, new Comparator<StaticMetadataService>() { @Override public int compare(StaticMetadataService a, StaticMetadataService b) { return b.getPriority() - a.getPriority(); } }); } /** * Creates a new management instance for the search index. * * @param connection * connection to the database */ public SolrIndexManager(SolrServer connection, Workspace workspace, List<StaticMetadataService> mdServices, SeriesService seriesService, Mpeg7CatalogService mpeg7CatalogService, SecurityService securityService) { this.solrServer = notNull(connection, "solr connection"); this.workspace = notNull(workspace, "workspace"); this.seriesService = notNull(seriesService, "series service"); this.mpeg7CatalogService = notNull(mpeg7CatalogService, "mpeg7 service"); this.securityService = notNull(securityService, "security service"); setStaticMetadataServices(notNull(mdServices, "metadata service")); } /** * Clears the search index. Make sure you know what you are doing. * * @throws SolrServerException * if an errors occurs while talking to solr */ public void clear() throws SolrServerException { try { solrServer.deleteByQuery("*:*"); solrServer.commit(); } catch (IOException e) { throw new SolrServerException(e); } } /** * Removes the entry with the given <code>id</code> from the database. The entry can either be a series or an episode. * * @param id * identifier of the series or episode to delete * @param deletionDate * the deletion date * @throws SolrServerException * if an errors occurs while talking to solr */ public boolean delete(String id, Date deletionDate) throws SolrServerException { try { // Load the existing episode QueryResponse solrResponse = null; try { SolrQuery query = new SolrQuery(Schema.ID + ":" + ClientUtils.escapeQueryChars(id) + " AND -" + Schema.OC_DELETED + ":[* TO *]"); solrResponse = solrServer.query(query); } catch (Exception e1) { throw new SolrServerException(e1); } // Did we find the episode? if (solrResponse.getResults().size() == 0) { logger.warn("Trying to delete non-existing media package {} from the search index", id); return false; } // Use all existing fields SolrDocument doc = solrResponse.getResults().get(0); SolrInputDocument inputDocument = new SolrInputDocument(); for (String field : doc.getFieldNames()) { inputDocument.setField(field, doc.get(field)); } // Set the oc_deleted field to the current date, then update Schema.setOcDeleted(inputDocument, deletionDate); solrServer.add(inputDocument); solrServer.commit(); return true; } catch (IOException e) { throw new SolrServerException(e); } } /** * Posts the media package to solr. Depending on what is referenced in the media package, the method might create one * or two entries: one for the episode and one for the series that the episode belongs to. * * This implementation of the search service removes all references to non "engage/download" media tracks * * @param sourceMediaPackage * the media package to post * @param acl * the access control list for this mediapackage * @param now * current date * @throws SolrServerException * if an errors occurs while talking to solr */ public boolean add(MediaPackage sourceMediaPackage, AccessControlList acl, AccessControlList seriesAcl, Date now) throws SolrServerException, UnauthorizedException { try { SolrInputDocument episodeDocument = createEpisodeInputDocument(sourceMediaPackage, acl); Schema.setOcModified(episodeDocument, now); SolrInputDocument seriesDocument = createSeriesInputDocument(sourceMediaPackage.getSeries(), seriesAcl); if (seriesDocument != null) Schema.enrich(episodeDocument, seriesDocument); // Post everything to the search index solrServer.add(episodeDocument); if (seriesDocument != null) solrServer.add(seriesDocument); solrServer.commit(); return true; } catch (Exception e) { throw new SolrServerException( String.format("Unable to add media package %s to index", sourceMediaPackage.getIdentifier()), e); } } /** * Posts a series to Solr. If the entry already exists, this will update the series. * * @param seriesId * the series to post * @param acl * the access control list for this series * @throws SolrServerException * if an errors occurs while talking to solr */ public void addSeries(final String seriesId, final AccessControlList acl) throws SolrServerException { try { SolrInputDocument seriesDocument = createSeriesInputDocument(seriesId, acl); if (seriesDocument != null) { solrServer.add(seriesDocument); solrServer.commit(); } } catch (Exception e) { throw new SolrServerException(String.format("Unable to add series %s to index", seriesId), e); } } /** * Posts the media package to solr. Depending on what is referenced in the media package, the method might create one * or two entries: one for the episode and one for the series that the episode belongs to. * * This implementation of the search service removes all references to non "engage/download" media tracks * * @param sourceMediaPackage * the media package to post * @param acl * the access control list for this mediapackage * @param deletionDate * the deletion date * @param modificationDate * the modification date * @return <code>true</code> if successfully added * @throws SolrServerException * if an errors occurs while talking to solr */ public boolean add(MediaPackage sourceMediaPackage, AccessControlList acl, Date deletionDate, Date modificationDate) throws SolrServerException { try { SolrInputDocument episodeDocument = createEpisodeInputDocument(sourceMediaPackage, acl); SolrInputDocument seriesDocument = createSeriesInputDocument(sourceMediaPackage.getSeries(), acl); if (seriesDocument != null) Schema.enrich(episodeDocument, seriesDocument); Schema.setOcModified(episodeDocument, modificationDate); if (deletionDate != null) Schema.setOcDeleted(episodeDocument, deletionDate); solrServer.add(episodeDocument); solrServer.add(seriesDocument); solrServer.commit(); return true; } catch (Exception e) { logger.error("Unable to add mediapackage {} to index", sourceMediaPackage.getIdentifier()); try { solrServer.rollback(); } catch (IOException e1) { throw new SolrServerException(e1); } throw new SolrServerException(e); } } /** * Creates a solr input document for the episode metadata of the media package. * * @param mediaPackage * the media package * @param acl * the access control list for this mediapackage * @return an input document ready to be posted to solr * @throws MediaPackageException * if serialization of the media package fails */ private SolrInputDocument createEpisodeInputDocument(MediaPackage mediaPackage, AccessControlList acl) throws MediaPackageException, IOException { SolrInputDocument doc = new SolrInputDocument(); String mediaPackageId = mediaPackage.getIdentifier().toString(); // Fill the input document Schema.setId(doc, mediaPackageId); // / // OC specific fields Schema.setOcMediatype(doc, SearchResultItemType.AudioVisual.toString()); Schema.setOrganization(doc, securityService.getOrganization().getId()); Schema.setOcMediapackage(doc, MediaPackageParser.getAsXml(mediaPackage)); Schema.setOcElementtags(doc, tags(mediaPackage)); Schema.setOcElementflavors(doc, flavors(mediaPackage)); // Add cover Attachment[] cover = mediaPackage.getAttachments(MediaPackageElements.MEDIAPACKAGE_COVER_FLAVOR); if (cover != null && cover.length > 0) { Schema.setOcCover(doc, cover[0].getURI().toString()); } // / // Add standard dublin core fields // naive approach. works as long as only setters, not adders are available in the schema for (StaticMetadata md : getMetadata(mdServices, mediaPackage)) addEpisodeMetadata(doc, md); // / // Add mpeg7 logger.debug("Looking for mpeg-7 catalogs containing segment texts"); Catalog[] mpeg7Catalogs = mediaPackage.getCatalogs(MediaPackageElements.TEXTS); if (mpeg7Catalogs.length == 0) { logger.debug("No text catalogs found, trying segments only"); mpeg7Catalogs = mediaPackage.getCatalogs(MediaPackageElements.SEGMENTS); } // TODO: merge the segments from each mpeg7 if there is more than one mpeg7 catalog if (mpeg7Catalogs.length > 0) { try { Mpeg7Catalog mpeg7Catalog = loadMpeg7Catalog(mpeg7Catalogs[0]); addMpeg7Metadata(doc, mediaPackage, mpeg7Catalog); } catch (IOException e) { logger.error("Error loading mpeg7 catalog. Skipping catalog", e); } } else { logger.debug("No segmentation catalog found"); } // / // Add authorization setAuthorization(doc, securityService, acl); return doc; } static void addEpisodeMetadata(final SolrInputDocument doc, final StaticMetadata md) { Schema.fill(doc, new Schema.FieldCollector() { @Override public Option<String> getId() { return Option.none(); } @Override public Option<String> getOrganization() { return Option.none(); } @Override public Option<Date> getDcCreated() { return md.getCreated(); } @Override public Option<Long> getDcExtent() { return md.getExtent(); } @Override public Option<String> getDcLanguage() { return md.getLanguage(); } @Override public Option<String> getDcIsPartOf() { return md.getIsPartOf(); } @Override public Option<String> getDcReplaces() { return md.getReplaces(); } @Override public Option<String> getDcType() { return md.getType(); } @Override public Option<Date> getDcAvailableFrom() { return md.getAvailable().flatMap(new Function<Interval, Option<Date>>() { @Override public Option<Date> apply(Interval interval) { return interval.fold(new Interval.Match<Option<Date>>() { @Override public Option<Date> bounded(Date leftBound, Date rightBound) { return Option.some(leftBound); } @Override public Option<Date> leftInfinite(Date rightBound) { return Option.none(); } @Override public Option<Date> rightInfinite(Date leftBound) { return Option.some(leftBound); } }); } }); } @Override public Option<Date> getDcAvailableTo() { return md.getAvailable().flatMap(new Function<Interval, Option<Date>>() { @Override public Option<Date> apply(Interval interval) { return interval.fold(new Interval.Match<Option<Date>>() { @Override public Option<Date> bounded(Date leftBound, Date rightBound) { return Option.some(rightBound); } @Override public Option<Date> leftInfinite(Date rightBound) { return Option.some(rightBound); } @Override public Option<Date> rightInfinite(Date leftBound) { return Option.none(); } }); } }); } @Override public List<DField<String>> getDcTitle() { return fromMValue(md.getTitles()); } @Override public List<DField<String>> getDcSubject() { return fromMValue(md.getSubjects()); } @Override public List<DField<String>> getDcCreator() { return fromMValue(md.getCreators()); } @Override public List<DField<String>> getDcPublisher() { return fromMValue(md.getPublishers()); } @Override public List<DField<String>> getDcContributor() { return fromMValue(md.getContributors()); } @Override public List<DField<String>> getDcDescription() { return fromMValue(md.getDescription()); } @Override public List<DField<String>> getDcRightsHolder() { return fromMValue(md.getRightsHolders()); } @Override public List<DField<String>> getDcSpatial() { return fromMValue(md.getSpatials()); } @Override public List<DField<String>> getDcAccessRights() { return fromMValue(md.getAccessRights()); } @Override public List<DField<String>> getDcLicense() { return fromMValue(md.getLicenses()); } @Override public Option<String> getOcMediatype() { return Option.none(); // set elsewhere } @Override public Option<String> getOcMediapackage() { return Option.none(); // set elsewhere } @Override public Option<String> getOcKeywords() { return Option.none(); // set elsewhere } @Override public Option<String> getOcCover() { return Option.none(); // set elsewhere } @Override public Option<Date> getOcModified() { return Option.none(); // set elsewhere } @Override public Option<Date> getOcDeleted() { return Option.none(); // set elsewhere } @Override public Option<String> getOcElementtags() { return Option.none(); // set elsewhere } @Override public Option<String> getOcElementflavors() { return Option.none(); // set elsewhere } @Override public List<DField<String>> getOcAcl() { return Collections.EMPTY_LIST; // set elsewhere } @Override public List<DField<String>> getSegmentText() { return Collections.EMPTY_LIST; // set elsewhere } @Override public List<DField<String>> getSegmentHint() { return Collections.EMPTY_LIST; // set elsewhere } }); } static List<DField<String>> fromMValue(List<MetadataValue<String>> as) { return map(as, new ArrayList<DField<String>>(), new Function<MetadataValue<String>, DField<String>>() { @Override public DField<String> apply(MetadataValue<String> v) { return new DField<String>(v.getValue(), v.getLanguage()); } }); } static List<DField<String>> fromDCValue(List<DublinCoreValue> as) { return map(as, new ArrayList<DField<String>>(), new Function<DublinCoreValue, DField<String>>() { @Override public DField<String> apply(DublinCoreValue v) { return new DField<String>(v.getValue(), v.getLanguage()); } }); } /** * Adds authorization fields to the solr document. * * @param doc * the solr document * @param acl * the access control list */ static void setAuthorization(SolrInputDocument doc, SecurityService securityService, AccessControlList acl) { Map<String, List<String>> permissions = new HashMap<String, List<String>>(); // Define containers for common permissions List<String> reads = new ArrayList<String>(); permissions.put(READ.toString(), reads); List<String> writes = new ArrayList<String>(); permissions.put(WRITE.toString(), writes); String adminRole = securityService.getOrganization().getAdminRole(); // The admin user can read and write if (adminRole != null) { reads.add(adminRole); writes.add(adminRole); } for (AccessControlEntry entry : acl.getEntries()) { if (!entry.isAllow()) { logger.warn("Search service does not support denial via ACL, ignoring {}", entry); continue; } List<String> actionPermissions = permissions.get(entry.getAction()); /* * MH-8353 a series could have a permission defined we don't know how to handle -DH */ if (actionPermissions == null) { logger.warn("Search service doesn't know how to handle action: " + entry.getAction()); continue; } if (acl == null) { actionPermissions = new ArrayList<String>(); permissions.put(entry.getAction(), actionPermissions); } actionPermissions.add(entry.getRole()); } // Write the permissions to the solr document for (Map.Entry<String, List<String>> entry : permissions.entrySet()) { Schema.setOcAcl(doc, new DField<String>(mkString(entry.getValue(), " "), entry.getKey())); } } static String mkString(Collection<?> as, String sep) { StringBuffer b = new StringBuffer(); for (Object a : as) { b.append(a).append(sep); } return b.substring(0, b.length() - sep.length()); } private Mpeg7Catalog loadMpeg7Catalog(Catalog catalog) throws IOException { try (InputStream in = workspace.read(catalog.getURI())) { return mpeg7CatalogService.load(in); } catch (NotFoundException e) { throw new IOException("Unable to load metadata from mpeg7 catalog " + catalog); } } /** * Creates a solr input document for the series metadata of the media package. * * @param seriesId * the id of the series * @param acl * the access control list for this mediapackage * @return an input document ready to be posted to solr or null */ private SolrInputDocument createSeriesInputDocument(String seriesId, AccessControlList acl) throws IOException, UnauthorizedException { if (seriesId == null) return null; DublinCoreCatalog dc = null; try { dc = seriesService.getSeries(seriesId); } catch (SeriesException e) { logger.debug("No series dublincore found for series id " + seriesId); return null; } catch (NotFoundException e) { logger.debug("No series dublincore found for series id " + seriesId); return null; } SolrInputDocument doc = new SolrInputDocument(); // Populate document with existing data try { StringBuffer query = new StringBuffer("q="); query = query.append(Schema.ID).append(":").append(SolrUtils.clean(seriesId)); SolrParams params = SolrRequestParsers.parseQueryString(query.toString()); QueryResponse solrResponse = solrServer.query(params); if (solrResponse.getResults().size() > 0) { SolrDocument existingSolrDocument = solrResponse.getResults().get(0); for (String fieldName : existingSolrDocument.getFieldNames()) { doc.addField(fieldName, existingSolrDocument.getFieldValue(fieldName)); } } } catch (Exception e) { logger.error("Error trying to load series " + seriesId, e); } // Fill document Schema.setId(doc, seriesId); // OC specific fields Schema.setOrganization(doc, securityService.getOrganization().getId()); Schema.setOcMediatype(doc, SearchResultItemType.Series.toString()); Schema.setOcModified(doc, new Date()); // DC fields addSeriesMetadata(doc, dc); // Authorization setAuthorization(doc, securityService, acl); return doc; } /** * Add the standard dublin core fields to a series document. * * @param doc * the solr document to fill * @param dc * the dublin core catalog to get the data from */ static void addSeriesMetadata(final SolrInputDocument doc, final DublinCoreCatalog dc) throws IOException { Schema.fill(doc, new Schema.FieldCollector() { @Override public Option<String> getId() { return Option.some(dc.getFirst(DublinCore.PROPERTY_IDENTIFIER)); } @Override public Option<String> getOrganization() { return Option.none(); } @Override public Option<Date> getDcCreated() { return head(dc.get(DublinCore.PROPERTY_CREATED)).flatMap(toDateF); } @Override public Option<Long> getDcExtent() { return head(dc.get(DublinCore.PROPERTY_EXTENT)).flatMap(toDurationF); } @Override public Option<String> getDcLanguage() { return option(dc.getFirst(DublinCore.PROPERTY_LANGUAGE)); } @Override public Option<String> getDcIsPartOf() { return option(dc.getFirst(DublinCore.PROPERTY_IS_PART_OF)); } @Override public Option<String> getDcReplaces() { return option(dc.getFirst(DublinCore.PROPERTY_REPLACES)); } @Override public Option<String> getDcType() { return option(dc.getFirst(DublinCore.PROPERTY_TYPE)); } @Override public Option<Date> getDcAvailableFrom() { return option(dc.getFirst(DublinCore.PROPERTY_AVAILABLE)).flatMap(new Function<String, Option<Date>>() { @Override public Option<Date> apply(String s) { return option(EncodingSchemeUtils.decodePeriod(s).getStart()); } }); } @Override public Option<Date> getDcAvailableTo() { return option(dc.getFirst(DublinCore.PROPERTY_AVAILABLE)).flatMap(new Function<String, Option<Date>>() { @Override public Option<Date> apply(String s) { return option(EncodingSchemeUtils.decodePeriod(s).getEnd()); } }); } @Override public List<DField<String>> getDcTitle() { return fromDCValue(dc.get(DublinCore.PROPERTY_TITLE)); } @Override public List<DField<String>> getDcSubject() { return fromDCValue(dc.get(DublinCore.PROPERTY_SUBJECT)); } @Override public List<DField<String>> getDcCreator() { return fromDCValue(dc.get(DublinCore.PROPERTY_CREATOR)); } @Override public List<DField<String>> getDcPublisher() { return fromDCValue(dc.get(DublinCore.PROPERTY_PUBLISHER)); } @Override public List<DField<String>> getDcContributor() { return fromDCValue(dc.get(DublinCore.PROPERTY_CONTRIBUTOR)); } @Override public List<DField<String>> getDcDescription() { return fromDCValue(dc.get(DublinCore.PROPERTY_DESCRIPTION)); } @Override public List<DField<String>> getDcRightsHolder() { return fromDCValue(dc.get(DublinCore.PROPERTY_RIGHTS_HOLDER)); } @Override public List<DField<String>> getDcSpatial() { return fromDCValue(dc.get(DublinCore.PROPERTY_SPATIAL)); } @Override public List<DField<String>> getDcAccessRights() { return fromDCValue(dc.get(DublinCore.PROPERTY_ACCESS_RIGHTS)); } @Override public List<DField<String>> getDcLicense() { return fromDCValue(dc.get(DublinCore.PROPERTY_LICENSE)); } @Override public Option<String> getOcMediatype() { return Option.none(); } @Override public Option<String> getOcMediapackage() { return Option.none(); } @Override public Option<String> getOcKeywords() { return Option.none(); } @Override public Option<String> getOcCover() { return Option.none(); } @Override public Option<Date> getOcModified() { return Option.none(); } @Override public Option<Date> getOcDeleted() { return Option.none(); } @Override public Option<String> getOcElementtags() { return Option.none(); } @Override public Option<String> getOcElementflavors() { return Option.none(); } @Override public List<DField<String>> getOcAcl() { return Collections.EMPTY_LIST; } @Override public List<DField<String>> getSegmentText() { return Collections.EMPTY_LIST; } @Override public List<DField<String>> getSegmentHint() { return Collections.EMPTY_LIST; } }); } /** * Add the mpeg 7 catalog data to the solr document. * * @param doc * the input document to the solr index * @param mpeg7 * the mpeg7 catalog */ @SuppressWarnings("unchecked") static void addMpeg7Metadata(SolrInputDocument doc, MediaPackage mediaPackage, Mpeg7Catalog mpeg7) { // Check for multimedia content if (!mpeg7.multimediaContent().hasNext()) { logger.warn("Mpeg-7 doesn't contain multimedia content"); return; } // Get the content duration by looking at the first content track. This // of course assumes that all tracks are equally long. MultimediaContent<? extends MultimediaContentType> mc = mpeg7.multimediaContent().next(); MultimediaContentType mct = mc.elements().next(); MediaTime mediaTime = mct.getMediaTime(); Schema.setDcExtent(doc, mediaTime.getMediaDuration().getDurationInMilliseconds()); // Check if the keywords have been filled by (manually) added dublin // core data. If not, look for the most relevant fields in mpeg-7. SortedSet<TextAnnotation> sortedAnnotations = null; if (!"".equals(Schema.getOcKeywords(doc))) { sortedAnnotations = new TreeSet<TextAnnotation>(new Comparator<TextAnnotation>() { @Override public int compare(TextAnnotation a1, TextAnnotation a2) { if ((RELEVANCE_BOOST * a1.getRelevance() + a1.getConfidence()) > (RELEVANCE_BOOST * a2.getRelevance() + a2 .getConfidence())) return -1; else if ((RELEVANCE_BOOST * a1.getRelevance() + a1.getConfidence()) < (RELEVANCE_BOOST * a2.getRelevance() + a2 .getConfidence())) return 1; return 0; } }); } // Iterate over the tracks and extract keywords and hints Iterator<MultimediaContent<? extends MultimediaContentType>> mmIter = mpeg7.multimediaContent(); int segmentCount = 0; while (mmIter.hasNext()) { MultimediaContent<?> multimediaContent = mmIter.next(); // We need to process visual segments first, due to the way they are handled in the ui. for (Iterator<?> iterator = multimediaContent.elements(); iterator.hasNext();) { MultimediaContentType type = (MultimediaContentType) iterator.next(); if (!(type instanceof Video) && !(type instanceof AudioVisual)) continue; // for every segment in the current multimedia content track Video video = (Video) type; Iterator<VideoSegment> vsegments = (Iterator<VideoSegment>) video.getTemporalDecomposition().segments(); while (vsegments.hasNext()) { VideoSegment segment = vsegments.next(); StringBuffer segmentText = new StringBuffer(); StringBuffer hintField = new StringBuffer(); // Collect the video text elements to a segment text SpatioTemporalDecomposition spt = segment.getSpatioTemporalDecomposition(); if (spt != null) { for (VideoText videoText : spt.getVideoText()) { if (segmentText.length() > 0) segmentText.append(" "); segmentText.append(videoText.getText().getText()); // TODO: Add hint on bounding box } } // Add keyword annotations Iterator<TextAnnotation> textAnnotations = segment.textAnnotations(); while (textAnnotations.hasNext()) { TextAnnotation textAnnotation = textAnnotations.next(); Iterator<?> kwIter = textAnnotation.keywordAnnotations(); while (kwIter.hasNext()) { KeywordAnnotation keywordAnnotation = (KeywordAnnotation) kwIter.next(); if (segmentText.length() > 0) segmentText.append(" "); segmentText.append(keywordAnnotation.getKeyword()); } } // Add free text annotations Iterator<TextAnnotation> freeIter = segment.textAnnotations(); if (freeIter.hasNext()) { Iterator<FreeTextAnnotation> freeTextIter = freeIter.next().freeTextAnnotations(); while (freeTextIter.hasNext()) { FreeTextAnnotation freeTextAnnotation = freeTextIter.next(); if (segmentText.length() > 0) segmentText.append(" "); segmentText.append(freeTextAnnotation.getText()); } } // add segment text to solr document Schema.setSegmentText(doc, new DField<String>(segmentText.toString(), Integer.toString(segmentCount))); // get the segments time properties MediaTimePoint timepoint = segment.getMediaTime().getMediaTimePoint(); MediaDuration duration = segment.getMediaTime().getMediaDuration(); // TODO: define a class with hint field constants hintField.append("time=" + timepoint.getTimeInMilliseconds() + "\n"); hintField.append("duration=" + duration.getDurationInMilliseconds() + "\n"); // Look for preview images. Their characteristics are that they are // attached as attachments with a flavor of preview/<something>. String time = timepoint.toString(); for (Attachment slide : mediaPackage.getAttachments(MediaPackageElements.PRESENTATION_SEGMENT_PREVIEW)) { MediaPackageReference ref = slide.getReference(); if (ref != null && time.equals(ref.getProperty("time"))) { hintField.append("preview"); hintField.append("."); hintField.append(ref.getIdentifier()); hintField.append("="); hintField.append(slide.getURI().toString()); hintField.append("\n"); } } logger.trace("Adding segment: " + timepoint.toString()); Schema.setSegmentHint(doc, new DField<String>(hintField.toString(), Integer.toString(segmentCount))); // increase segment counter segmentCount++; } } } // Put the most important keywords into a special solr field if (sortedAnnotations != null) { Schema.setOcKeywords(doc, importantKeywordsString(sortedAnnotations).toString()); } } /** * Generates a string with the most important kewords from the text annotation. * * @param sortedAnnotations * @return The keyword string. */ static StringBuffer importantKeywordsString(SortedSet<TextAnnotation> sortedAnnotations) { // important keyword: // - high relevance // - high confidence // - occur often // - more than MAX_CHAR chars // calculate keyword occurences (histogram) and importance ArrayList<String> list = new ArrayList<String>(); Iterator<TextAnnotation> textAnnotations = sortedAnnotations.iterator(); TextAnnotation textAnnotation = null; String keyword = null; HashMap<String, Integer> histogram = new HashMap<String, Integer>(); HashMap<String, Double> importance = new HashMap<String, Double>(); int occ = 0; double imp; while (textAnnotations.hasNext()) { textAnnotation = textAnnotations.next(); Iterator<KeywordAnnotation> keywordAnnotations = textAnnotation.keywordAnnotations(); while (keywordAnnotations.hasNext()) { KeywordAnnotation annotation = keywordAnnotations.next(); keyword = annotation.getKeyword().toLowerCase(); if (keyword.length() > MAX_CHAR) { occ = 0; if (histogram.keySet().contains(keyword)) { occ = histogram.get(keyword); } histogram.put(keyword, occ + 1); // here the importance value is calculated // from relevance, confidence and frequency of occurence. imp = (RELEVANCE_BOOST * getMaxRelevance(keyword, sortedAnnotations) + getMaxConfidence(keyword, sortedAnnotations)) * (occ + 1); importance.put(keyword, imp); } } } // get the MAX_IMPORTANT_COUNT most important keywords StringBuffer buf = new StringBuffer(); while (list.size() < MAX_IMPORTANT_COUNT && importance.size() > 0) { double max = 0.0; String maxKeyword = null; // get maximum from importance list for (Entry<String, Double> entry : importance.entrySet()) { keyword = entry.getKey(); if (max < entry.getValue()) { max = entry.getValue(); maxKeyword = keyword; } } // pop maximum importance.remove(maxKeyword); // append keyword to string if (buf.length() > 0) buf.append(" "); buf.append(maxKeyword); } return buf; } /** * Gets the maximum confidence for a given keyword in the text annotation. * * @param keyword * @param sortedAnnotations * @return The maximum confidence value. */ static double getMaxConfidence(String keyword, SortedSet<TextAnnotation> sortedAnnotations) { double max = 0.0; String needle = null; TextAnnotation textAnnotation = null; Iterator<TextAnnotation> textAnnotations = sortedAnnotations.iterator(); while (textAnnotations.hasNext()) { textAnnotation = textAnnotations.next(); Iterator<KeywordAnnotation> keywordAnnotations = textAnnotation.keywordAnnotations(); while (keywordAnnotations.hasNext()) { KeywordAnnotation ann = keywordAnnotations.next(); needle = ann.getKeyword().toLowerCase(); if (keyword.equals(needle)) { if (max < textAnnotation.getConfidence()) { max = textAnnotation.getConfidence(); } } } } return max; } /** * Gets the maximum relevance for a given keyword in the text annotation. * * @param keyword * @param sortedAnnotations * @return The maximum relevance value. */ static double getMaxRelevance(String keyword, SortedSet<TextAnnotation> sortedAnnotations) { double max = 0.0; String needle = null; TextAnnotation textAnnotation = null; Iterator<TextAnnotation> textAnnotations = sortedAnnotations.iterator(); while (textAnnotations.hasNext()) { textAnnotation = textAnnotations.next(); Iterator<KeywordAnnotation> keywordAnnotations = textAnnotation.keywordAnnotations(); while (keywordAnnotations.hasNext()) { KeywordAnnotation ann = keywordAnnotations.next(); needle = ann.getKeyword().toLowerCase(); if (keyword.equals(needle)) { if (max < textAnnotation.getRelevance()) { max = textAnnotation.getRelevance(); } } } } return max; } /** * Get metadata from all registered metadata services. */ static List<StaticMetadata> getMetadata(final List<StaticMetadataService> mdServices, final MediaPackage mp) { return flatMap(mdServices, new ArrayList<StaticMetadata>(), new Function<StaticMetadataService, Collection<StaticMetadata>>() { @Override public Collection<StaticMetadata> apply(StaticMetadataService s) { StaticMetadata md = s.getMetadata(mp); return md != null ? Arrays.asList(md) : Collections.<StaticMetadata> emptyList(); } }); } /** * Return all media package tags as a space separated string. */ static String tags(MediaPackage mp) { StringBuilder sb = new StringBuilder(); for (MediaPackageElement element : mp.getElements()) { for (String tag : element.getTags()) { sb.append(tag); sb.append(" "); } } return sb.toString(); } /** * Return all media package flavors as a space separated string. */ static String flavors(MediaPackage mp) { StringBuilder sb = new StringBuilder(); for (MediaPackageElement element : mp.getElements()) { if (element.getFlavor() != null) { sb.append(element.getFlavor().toString()); sb.append(" "); } } return sb.toString(); } /** * Returns number of entries in search index, across all organizations. * * @return number of entries in search index * @throws SearchServiceDatabaseException * if count cannot be retrieved */ public long count() throws SearchServiceDatabaseException { try { QueryResponse response = solrServer.query(new SolrQuery("*:*")); return response.getResults().getNumFound(); } catch (SolrServerException e) { throw new SearchServiceDatabaseException(e); } } }
./CrossVul/dataset_final_sorted/CWE-863/java/good_1947_4
crossvul-java_data_bad_1947_1
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.opencastproject.search.impl.persistence; import org.opencastproject.security.api.Organization; import org.opencastproject.security.impl.jpa.JpaOrganization; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * Entity object for storing search in persistence storage. Media package id is stored as primary key. */ @Entity(name = "SearchEntity") @Table(name = "oc_search", indexes = { @Index(name = "IX_oc_search_series", columnList = ("series_id")), @Index(name = "IX_oc_search_organization", columnList = ("organization")) }) @NamedQueries({ @NamedQuery(name = "Search.findAll", query = "SELECT s FROM SearchEntity s"), @NamedQuery(name = "Search.getCount", query = "SELECT COUNT(s) FROM SearchEntity s"), @NamedQuery(name = "Search.findById", query = "SELECT s FROM SearchEntity s WHERE s.mediaPackageId=:mediaPackageId"), @NamedQuery(name = "Search.findBySeriesId", query = "SELECT s FROM SearchEntity s WHERE s.seriesId=:seriesId"), @NamedQuery(name = "Search.getNoSeries", query = "SELECT s FROM SearchEntity s WHERE s.seriesId IS NULL")}) public class SearchEntity { /** media package id, primary key */ @Id @Column(name = "id", length = 128) private String mediaPackageId; @Column(name = "series_id", length = 128) protected String seriesId; /** Organization id */ @OneToOne(targetEntity = JpaOrganization.class) @JoinColumn(name = "organization", referencedColumnName = "id") protected JpaOrganization organization; /** The media package deleted */ @Column(name = "deletion_date") @Temporal(TemporalType.TIMESTAMP) private Date deletionDate; /** The media package deleted */ @Column(name = "modification_date") @Temporal(TemporalType.TIMESTAMP) private Date modificationDate; /** Serialized media package */ @Lob @Column(name = "mediapackage_xml", length = 65535) private String mediaPackageXML; /** Serialized access control */ @Lob @Column(name = "access_control", length = 65535) protected String accessControl; /** * Default constructor without any import. */ public SearchEntity() { } /** * Returns media package id. * * @return media package id */ public String getMediaPackageId() { return mediaPackageId; } /** * Sets media package id. Id length limit is 128 charachters. * * @param mediaPackageId */ public void setMediaPackageId(String mediaPackageId) { this.mediaPackageId = mediaPackageId; } /** * Returns serialized media package. * * @return serialized media package */ public String getMediaPackageXML() { return mediaPackageXML; } /** * Sets serialized media package * * @param mediaPackageXML */ public void setMediaPackageXML(String mediaPackageXML) { this.mediaPackageXML = mediaPackageXML; } /** * Returns serialized access control * * @return serialized access control */ public String getAccessControl() { return accessControl; } /** * Sets serialized access control. * * @param accessControl * serialized access control */ public void setAccessControl(String accessControl) { this.accessControl = accessControl; } /** * @return the organization */ public JpaOrganization getOrganization() { return organization; } /** * @param organization * the organization to set */ public void setOrganization(Organization organization) { if (organization instanceof JpaOrganization) { this.organization = (JpaOrganization) organization; } else { this.organization = new JpaOrganization(organization.getId(), organization.getName(), organization.getServers(), organization.getAdminRole(), organization.getAnonymousRole(), organization.getProperties()); } } /** * @return the deletion date */ public Date getDeletionDate() { return deletionDate; } /** * Sets the deletion date * * @param deletionDate * the deletion date */ public void setDeletionDate(Date deletionDate) { this.deletionDate = deletionDate; } /** * @return the modification date */ public Date getModificationDate() { return modificationDate; } /** * Sets the modification date * * @param modificationDate * the modification date */ public void setModificationDate(Date modificationDate) { this.modificationDate = modificationDate; } /** * @return the series Id for this search entry */ public String getSeriesId() { return seriesId; } /** * Sets the series ID * * @param seriesId * the series ID */ public void setSeriesId(String seriesId) { this.seriesId = seriesId; } }
./CrossVul/dataset_final_sorted/CWE-863/java/bad_1947_1
crossvul-java_data_bad_4545_1
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.exec.internal; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.core.thing.ThingTypeUID; /** * The {@link ExecBinding} class defines common constants, which are * used across the whole binding. * * @author Karel Goderis - Initial contribution */ @NonNullByDefault public class ExecBindingConstants { public static final String BINDING_ID = "exec"; // List of all Thing Type UIDs public static final ThingTypeUID THING_COMMAND = new ThingTypeUID(BINDING_ID, "command"); // List of all Channel ids public static final String OUTPUT = "output"; public static final String INPUT = "input"; public static final String EXIT = "exit"; public static final String RUN = "run"; public static final String LAST_EXECUTION = "lastexecution"; }
./CrossVul/dataset_final_sorted/CWE-863/java/bad_4545_1
crossvul-java_data_good_4254_3
package com.zrlog.web.handler; import com.hibegin.common.util.IOUtil; import com.hibegin.common.util.http.HttpUtil; import com.hibegin.common.util.http.handle.CloseResponseHandle; import com.jfinal.core.JFinal; import com.jfinal.handler.Handler; import com.zrlog.common.Constants; import com.zrlog.common.vo.AdminTokenVO; import com.zrlog.model.User; import com.zrlog.service.AdminTokenService; import com.zrlog.service.AdminTokenThreadLocal; import com.zrlog.util.BlogBuildInfoUtil; import com.zrlog.web.util.PluginHelper; import org.apache.http.Header; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.log4j.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 这个类负责了对所有的插件路由的代理中转给插件服务(及plugin-core.jar这个进程),使用的是Handler而非Interception也是由于Interception * 不处理静态请求。 * 目前插件服务拦截了 * 1./admin/plugins/* (进行权限检查) * 2./plugin/* /p/* (是plugin的短路由,代码逻辑上是不区分的,不检查权限) * <p> * 如果想了解更多关于插件的实现可以浏览这篇文章 http://blog.zrlog.com/post/zrlog-plugin-dev */ public class PluginHandler extends Handler { private static final Logger LOGGER = Logger.getLogger(PluginHandler.class); private AdminTokenService adminTokenService = new AdminTokenService(); private List<String> pluginHandlerPaths = Arrays.asList("/admin/plugins/", "/plugin/", "/p/"); @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) { //便于Wappalyzer读取 response.addHeader("X-ZrLog", BlogBuildInfoUtil.getVersion()); boolean isPluginPath = false; for (String path : pluginHandlerPaths) { if (target.startsWith(path)) { isPluginPath = true; } } if (isPluginPath) { Map.Entry<AdminTokenVO, User> entry = null; try { entry = adminTokenService.getAdminTokenVOUserEntry(request); if (entry != null) { adminTokenService.setAdminToken(entry.getValue(), entry.getKey().getSessionId(), entry.getKey().getProtocol(), request, response); } if (target.startsWith("/admin/plugins/")) { try { adminPermission(target, request, response); } catch (IOException | InstantiationException e) { LOGGER.error(e); } } else if (target.startsWith("/plugin/") || target.startsWith("/p/")) { try { visitorPermission(target, request, response); } catch (IOException | InstantiationException e) { LOGGER.error(e); } } } finally { isHandled[0] = true; if (entry != null) { AdminTokenThreadLocal.remove(); } } } else { this.next.handle(target, request, response, isHandled); } } /** * 检查是否登陆,未登陆的请求直接放回403的错误页面 * * @param target * @param request * @param response * @throws IOException * @throws InstantiationException */ private void adminPermission(String target, HttpServletRequest request, HttpServletResponse response) throws IOException, InstantiationException { if (AdminTokenThreadLocal.getUser() != null) { accessPlugin(target.replace("/admin/plugins", ""), request, response); } else { response.sendRedirect(request.getContextPath() + "/admin/login?redirectFrom=" + request.getRequestURL() + (request.getQueryString() != null ? "?" + request.getQueryString() : "")); } } /** * 不检查是否登陆,错误请求直接直接转化为403 * * @param target * @param request * @param response * @throws IOException * @throws InstantiationException */ private void visitorPermission(String target, HttpServletRequest request, HttpServletResponse response) throws IOException, InstantiationException { if (!accessPlugin(target.replace("/plugin", "").replace("/p", ""), request, response)) { response.sendError(403); } } /** * 代理中转HTTP请求,目前仅支持,GET,POST 请求方式的中转。 * * @param uri * @param request * @param response * @return true 表示请求正常执行,false 代表遇到了一些问题 * @throws IOException * @throws InstantiationException */ private boolean accessPlugin(String uri, HttpServletRequest request, HttpServletResponse response) throws IOException, InstantiationException { CloseResponseHandle handle = getContext(uri, request.getMethod(), request, true); try { if (handle.getT() != null && handle.getT().getEntity() != null) { response.setStatus(handle.getT().getStatusLine().getStatusCode()); //防止多次被Transfer-Encoding handle.getT().removeHeaders("Transfer-Encoding"); for (Header header : handle.getT().getAllHeaders()) { response.addHeader(header.getName(), header.getValue()); } //将插件服务的HTTP的body返回给调用者 byte[] bytes = IOUtil.getByteByInputStream(handle.getT().getEntity().getContent()); response.addHeader("Content-Length", Integer.valueOf(bytes.length).toString()); response.getOutputStream().write(bytes); response.getOutputStream().close(); return true; } else { return false; } } finally { handle.close(); } } public static CloseResponseHandle getContext(String uri, String method, HttpServletRequest request, boolean disableRedirect) throws IOException, InstantiationException { String pluginServerHttp = Constants.pluginServer; CloseableHttpResponse httpResponse; CloseResponseHandle handle = new CloseResponseHandle(); HttpUtil httpUtil = disableRedirect ? HttpUtil.getDisableRedirectInstance() : HttpUtil.getInstance(); //GET请求不关心request.getInputStream() 的数据 if (method.equals(request.getMethod()) && "GET".equalsIgnoreCase(method)) { httpResponse = httpUtil.sendGetRequest(pluginServerHttp + uri, request.getParameterMap(), handle, PluginHelper.genHeaderMapByRequest(request, AdminTokenThreadLocal.getUser())).getT(); } else { //如果是表单数据提交不关心请求头,反之将所有请求头都发到插件服务 if ("application/x-www-form-urlencoded".equals(request.getContentType())) { httpResponse = httpUtil.sendPostRequest(pluginServerHttp + uri, request.getParameterMap(), handle, PluginHelper.genHeaderMapByRequest(request, AdminTokenThreadLocal.getUser())).getT(); } else { httpResponse = httpUtil.sendPostRequest(pluginServerHttp + uri + "?" + request.getQueryString(), IOUtil.getByteByInputStream(request.getInputStream()), handle, PluginHelper.genHeaderMapByRequest(request, AdminTokenThreadLocal.getUser())).getT(); } } //添加插件服务的HTTP响应头到调用者响应头里面 if (httpResponse != null) { Map<String, String> headerMap = new HashMap<>(); Header[] headers = httpResponse.getAllHeaders(); for (Header header : headers) { headerMap.put(header.getName(), header.getValue()); } if (JFinal.me().getConstants().getDevMode()) { LOGGER.info(uri + " --------------------------------- response"); } for (Map.Entry<String, String> t : headerMap.entrySet()) { if (JFinal.me().getConstants().getDevMode()) { LOGGER.info("key " + t.getKey() + " value-> " + t.getValue()); } } } return handle; } }
./CrossVul/dataset_final_sorted/CWE-863/java/good_4254_3
crossvul-java_data_good_4545_1
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.exec.internal; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.config.core.ConfigConstants; import org.eclipse.smarthome.core.thing.ThingTypeUID; import java.io.File; /** * The {@link ExecBindingConstants} class defines common constants, which are * used across the whole binding. * * @author Karel Goderis - Initial contribution */ @NonNullByDefault public class ExecBindingConstants { public static final String BINDING_ID = "exec"; // List of all Thing Type UIDs public static final ThingTypeUID THING_COMMAND = new ThingTypeUID(BINDING_ID, "command"); // List of all Channel ids public static final String OUTPUT = "output"; public static final String INPUT = "input"; public static final String EXIT = "exit"; public static final String RUN = "run"; public static final String LAST_EXECUTION = "lastexecution"; }
./CrossVul/dataset_final_sorted/CWE-863/java/good_4545_1
crossvul-java_data_good_4951_1
/***************************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF 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 * * * * 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 bsh; import org.junit.Assert; import org.junit.Test; /** * This tests serialization of the beanshell interpreter * * @author Jessen Yu */ public class BshSerializationTest { /** * Tests that Special.NULL_VALUE is correctly serialized/deserialized * * @throws Exception in case of failure */ @Test public void testNullValueSerialization() throws Exception { final Interpreter origInterpreter = new Interpreter(); origInterpreter.eval("myNull = null;"); Assert.assertNull(origInterpreter.eval("myNull")); final Interpreter deserInterpreter = TestUtil.serDeser(origInterpreter); Assert.assertNull(deserInterpreter.eval("myNull")); } /** * Tests that Primitive.NULL is correctly serialized/deserialized * * @throws Exception in case of failure */ @Test public void testSpecialNullSerialization() throws Exception { final Interpreter originalInterpreter = new Interpreter(); originalInterpreter.eval("myNull = null;"); Assert.assertTrue((Boolean) originalInterpreter.eval("myNull == null")); final Interpreter deserInterpreter = TestUtil.serDeser(originalInterpreter); Assert.assertTrue((Boolean) deserInterpreter.eval("myNull == null")); } /** * Tests that a declared method can be serialized (but not exploited) * * @throws Exception in case of failure */ @Test public void testMethodSerialization() throws Exception { final Interpreter origInterpreter = new Interpreter(); origInterpreter.eval("int method() { return 1337; }"); Assert.assertEquals(1337, origInterpreter.eval("method()")); final Interpreter deserInterpreter = TestUtil.serDeser(origInterpreter); Assert.assertEquals(1337, deserInterpreter.eval("method()")); } }
./CrossVul/dataset_final_sorted/CWE-19/java/good_4951_1
crossvul-java_data_bad_4951_1
/***************************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF 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 * * * * 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 bsh; import org.junit.Assert; import org.junit.Test; /** * This tests serialization of the beanshell interpreter * * @author Jessen Yu */ public class BshSerializationTest { /** * Tests that Special.NULL_VALUE is correctly serialized/deserialized * * @throws Exception in case of failure */ @Test public void testNullValueSerialization() throws Exception { final Interpreter origInterpreter = new Interpreter(); origInterpreter.eval("myNull = null;"); Assert.assertNull(origInterpreter.eval("myNull")); final Interpreter deserInterpreter = TestUtil.serDeser(origInterpreter); Assert.assertNull(deserInterpreter.eval("myNull")); } /** * Tests that Primitive.NULL is correctly serialized/deserialized * * @throws Exception in case of failure */ @Test public void testSpecialNullSerialization() throws Exception { final Interpreter originalInterpreter = new Interpreter(); originalInterpreter.eval("myNull = null;"); Assert.assertTrue((Boolean) originalInterpreter.eval("myNull == null")); final Interpreter deserInterpreter = TestUtil.serDeser(originalInterpreter); Assert.assertTrue((Boolean) deserInterpreter.eval("myNull == null")); } }
./CrossVul/dataset_final_sorted/CWE-19/java/bad_4951_1
crossvul-java_data_good_4951_0
/***************************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF 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 * * * * 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. * * * * * * This file is part of the BeanShell Java Scripting distribution. * * Documentation and updates may be found at http://www.beanshell.org/ * * Patrick Niemeyer (pat@pat.net) * * Author of Learning Java, O'Reilly & Associates * * * *****************************************************************************/ package bsh; import java.lang.reflect.*; import java.lang.reflect.InvocationHandler; import java.io.*; import java.util.Hashtable; /** XThis is a dynamically loaded extension which extends This.java and adds support for the generalized interface proxy mechanism introduced in JDK1.3. XThis allows bsh scripted objects to implement arbitrary interfaces (be arbitrary event listener types). Note: This module relies on new features of JDK1.3 and will not compile with JDK1.2 or lower. For those environments simply do not compile this class. Eventually XThis should become simply This, but for backward compatibility we will maintain This without requiring support for the proxy mechanism. XThis stands for "eXtended This" (I had to call it something). @see JThis See also JThis with explicit JFC support for compatibility. @see This */ public class XThis extends This { /** A cache of proxy interface handlers. Currently just one per interface. */ Hashtable interfaces; transient InvocationHandler invocationHandler = new Handler(); public XThis( NameSpace namespace, Interpreter declaringInterp ) { super( namespace, declaringInterp ); } public String toString() { return "'this' reference (XThis) to Bsh object: " + namespace; } /** Get dynamic proxy for interface, caching those it creates. */ public Object getInterface( Class clas ) { return getInterface( new Class[] { clas } ); } /** Get dynamic proxy for interface, caching those it creates. */ public Object getInterface( Class [] ca ) { if ( interfaces == null ) interfaces = new Hashtable(); // Make a hash of the interface hashcodes in order to cache them int hash = 21; for(int i=0; i<ca.length; i++) hash *= ca[i].hashCode() + 3; Object hashKey = new Integer(hash); Object interf = interfaces.get( hashKey ); if ( interf == null ) { ClassLoader classLoader = ca[0].getClassLoader(); // ? interf = Proxy.newProxyInstance( classLoader, ca, invocationHandler ); interfaces.put( hashKey, interf ); } return interf; } /** This is the invocation handler for the dynamic proxy. <p> Notes: Inner class for the invocation handler seems to shield this unavailable interface from JDK1.2 VM... I don't understand this. JThis works just fine even if those classes aren't there (doesn't it?) This class shouldn't be loaded if an XThis isn't instantiated in NameSpace.java, should it? */ class Handler implements InvocationHandler { public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { try { return invokeImpl( proxy, method, args ); } catch ( TargetError te ) { // Unwrap target exception. If the interface declares that // it throws the ex it will be delivered. If not it will be // wrapped in an UndeclaredThrowable throw te.getTarget(); } catch ( EvalError ee ) { // Ease debugging... // XThis.this refers to the enclosing class instance if ( Interpreter.DEBUG ) Interpreter.debug( "EvalError in scripted interface: " + XThis.this.toString() + ": "+ ee ); throw ee; } } public Object invokeImpl( Object proxy, Method method, Object[] args ) throws EvalError { String methodName = method.getName(); CallStack callstack = new CallStack( namespace ); /* If equals() is not explicitly defined we must override the default implemented by the This object protocol for scripted object. To support XThis equals() must test for equality with the generated proxy object, not the scripted bsh This object; otherwise callers from outside in Java will not see a the proxy object as equal to itself. */ BshMethod equalsMethod = null; try { equalsMethod = namespace.getMethod( "equals", new Class [] { Object.class } ); } catch ( UtilEvalError e ) {/*leave null*/ } if ( methodName.equals("equals" ) && equalsMethod == null ) { Object obj = args[0]; return proxy == obj ? Boolean.TRUE : Boolean.FALSE; } /* If toString() is not explicitly defined override the default to show the proxy interfaces. */ BshMethod toStringMethod = null; try { toStringMethod = namespace.getMethod( "toString", new Class [] { } ); } catch ( UtilEvalError e ) {/*leave null*/ } if ( methodName.equals("toString" ) && toStringMethod == null) { Class [] ints = proxy.getClass().getInterfaces(); // XThis.this refers to the enclosing class instance StringBuffer sb = new StringBuffer( XThis.this.toString() + "\nimplements:" ); for(int i=0; i<ints.length; i++) sb.append( " "+ ints[i].getName() + ((ints.length > 1)?",":"") ); return sb.toString(); } Class [] paramTypes = method.getParameterTypes(); return Primitive.unwrap( invokeMethod( methodName, Primitive.wrap(args, paramTypes) ) ); } }; }
./CrossVul/dataset_final_sorted/CWE-19/java/good_4951_0
crossvul-java_data_bad_4951_0
/***************************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF 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 * * * * 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. * * * * * * This file is part of the BeanShell Java Scripting distribution. * * Documentation and updates may be found at http://www.beanshell.org/ * * Patrick Niemeyer (pat@pat.net) * * Author of Learning Java, O'Reilly & Associates * * * *****************************************************************************/ package bsh; import java.lang.reflect.*; import java.lang.reflect.InvocationHandler; import java.io.*; import java.util.Hashtable; /** XThis is a dynamically loaded extension which extends This.java and adds support for the generalized interface proxy mechanism introduced in JDK1.3. XThis allows bsh scripted objects to implement arbitrary interfaces (be arbitrary event listener types). Note: This module relies on new features of JDK1.3 and will not compile with JDK1.2 or lower. For those environments simply do not compile this class. Eventually XThis should become simply This, but for backward compatibility we will maintain This without requiring support for the proxy mechanism. XThis stands for "eXtended This" (I had to call it something). @see JThis See also JThis with explicit JFC support for compatibility. @see This */ public class XThis extends This { /** A cache of proxy interface handlers. Currently just one per interface. */ Hashtable interfaces; InvocationHandler invocationHandler = new Handler(); public XThis( NameSpace namespace, Interpreter declaringInterp ) { super( namespace, declaringInterp ); } public String toString() { return "'this' reference (XThis) to Bsh object: " + namespace; } /** Get dynamic proxy for interface, caching those it creates. */ public Object getInterface( Class clas ) { return getInterface( new Class[] { clas } ); } /** Get dynamic proxy for interface, caching those it creates. */ public Object getInterface( Class [] ca ) { if ( interfaces == null ) interfaces = new Hashtable(); // Make a hash of the interface hashcodes in order to cache them int hash = 21; for(int i=0; i<ca.length; i++) hash *= ca[i].hashCode() + 3; Object hashKey = new Integer(hash); Object interf = interfaces.get( hashKey ); if ( interf == null ) { ClassLoader classLoader = ca[0].getClassLoader(); // ? interf = Proxy.newProxyInstance( classLoader, ca, invocationHandler ); interfaces.put( hashKey, interf ); } return interf; } /** This is the invocation handler for the dynamic proxy. <p> Notes: Inner class for the invocation handler seems to shield this unavailable interface from JDK1.2 VM... I don't understand this. JThis works just fine even if those classes aren't there (doesn't it?) This class shouldn't be loaded if an XThis isn't instantiated in NameSpace.java, should it? */ class Handler implements InvocationHandler, java.io.Serializable { public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { try { return invokeImpl( proxy, method, args ); } catch ( TargetError te ) { // Unwrap target exception. If the interface declares that // it throws the ex it will be delivered. If not it will be // wrapped in an UndeclaredThrowable throw te.getTarget(); } catch ( EvalError ee ) { // Ease debugging... // XThis.this refers to the enclosing class instance if ( Interpreter.DEBUG ) Interpreter.debug( "EvalError in scripted interface: " + XThis.this.toString() + ": "+ ee ); throw ee; } } public Object invokeImpl( Object proxy, Method method, Object[] args ) throws EvalError { String methodName = method.getName(); CallStack callstack = new CallStack( namespace ); /* If equals() is not explicitly defined we must override the default implemented by the This object protocol for scripted object. To support XThis equals() must test for equality with the generated proxy object, not the scripted bsh This object; otherwise callers from outside in Java will not see a the proxy object as equal to itself. */ BshMethod equalsMethod = null; try { equalsMethod = namespace.getMethod( "equals", new Class [] { Object.class } ); } catch ( UtilEvalError e ) {/*leave null*/ } if ( methodName.equals("equals" ) && equalsMethod == null ) { Object obj = args[0]; return proxy == obj ? Boolean.TRUE : Boolean.FALSE; } /* If toString() is not explicitly defined override the default to show the proxy interfaces. */ BshMethod toStringMethod = null; try { toStringMethod = namespace.getMethod( "toString", new Class [] { } ); } catch ( UtilEvalError e ) {/*leave null*/ } if ( methodName.equals("toString" ) && toStringMethod == null) { Class [] ints = proxy.getClass().getInterfaces(); // XThis.this refers to the enclosing class instance StringBuffer sb = new StringBuffer( XThis.this.toString() + "\nimplements:" ); for(int i=0; i<ints.length; i++) sb.append( " "+ ints[i].getName() + ((ints.length > 1)?",":"") ); return sb.toString(); } Class [] paramTypes = method.getParameterTypes(); return Primitive.unwrap( invokeMethod( methodName, Primitive.wrap(args, paramTypes) ) ); } }; }
./CrossVul/dataset_final_sorted/CWE-19/java/bad_4951_0