id
stringlengths
27
31
content
stringlengths
14
287k
max_stars_repo_path
stringlengths
52
57
crossvul-java_data_bad_5761_6
package org.richfaces.demo.paint2d; import java.io.Serializable; public class PaintData implements Serializable{ /** * */ private static final long serialVersionUID = 1L; String text; Integer color; float scale; public Integer getColor() { return color; } public void setColor(Integer color) { this.color = color; } public float getScale() { return scale; } public void setScale(float scale) { this.scale = scale; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_5761_6
crossvul-java_data_good_42_5
package org.bouncycastle.pqc.math.linearalgebra; import java.security.SecureRandom; import java.util.Vector; /** * This abstract class defines the finite field <i>GF(2<sup>n</sup>)</i>. It * holds the extension degree <i>n</i>, the characteristic, the irreducible * fieldpolynomial and conversion matrices. GF2nField is implemented by the * classes GF2nPolynomialField and GF2nONBField. * * @see GF2nONBField * @see GF2nPolynomialField */ public abstract class GF2nField { protected final SecureRandom random; /** * the degree of this field */ protected int mDegree; /** * the irreducible fieldPolynomial stored in normal order (also for ONB) */ protected GF2Polynomial fieldPolynomial; /** * holds a list of GF2nFields to which elements have been converted and thus * a COB-Matrix exists */ protected Vector fields; /** * the COB matrices */ protected Vector matrices; protected GF2nField(SecureRandom random) { this.random = random; } /** * Returns the degree <i>n</i> of this field. * * @return the degree <i>n</i> of this field */ public final int getDegree() { return mDegree; } /** * Returns the fieldpolynomial as a new Bitstring. * * @return a copy of the fieldpolynomial as a new Bitstring */ public final GF2Polynomial getFieldPolynomial() { if (fieldPolynomial == null) { computeFieldPolynomial(); } return new GF2Polynomial(fieldPolynomial); } /** * Decides whether the given object <tt>other</tt> is the same as this * field. * * @param other another object * @return (this == other) */ public final boolean equals(Object other) { if (other == null || !(other instanceof GF2nField)) { return false; } GF2nField otherField = (GF2nField)other; if (otherField.mDegree != mDegree) { return false; } if (!fieldPolynomial.equals(otherField.fieldPolynomial)) { return false; } if ((this instanceof GF2nPolynomialField) && !(otherField instanceof GF2nPolynomialField)) { return false; } if ((this instanceof GF2nONBField) && !(otherField instanceof GF2nONBField)) { return false; } return true; } /** * @return the hash code of this field */ public int hashCode() { return mDegree + fieldPolynomial.hashCode(); } /** * Computes a random root from the given irreducible fieldpolynomial * according to IEEE 1363 algorithm A.5.6. This cal take very long for big * degrees. * * @param B0FieldPolynomial the fieldpolynomial if the other basis as a Bitstring * @return a random root of BOFieldPolynomial in representation according to * this field * @see "P1363 A.5.6, p103f" */ protected abstract GF2nElement getRandomRoot(GF2Polynomial B0FieldPolynomial); /** * Computes the change-of-basis matrix for basis conversion according to * 1363. The result is stored in the lists fields and matrices. * * @param B1 the GF2nField to convert to * @see "P1363 A.7.3, p111ff" */ protected abstract void computeCOBMatrix(GF2nField B1); /** * Computes the fieldpolynomial. This can take a long time for big degrees. */ protected abstract void computeFieldPolynomial(); /** * Inverts the given matrix represented as bitstrings. * * @param matrix the matrix to invert as a Bitstring[] * @return matrix^(-1) */ protected final GF2Polynomial[] invertMatrix(GF2Polynomial[] matrix) { GF2Polynomial[] a = new GF2Polynomial[matrix.length]; GF2Polynomial[] inv = new GF2Polynomial[matrix.length]; GF2Polynomial dummy; int i, j; // initialize a as a copy of matrix and inv as E(inheitsmatrix) for (i = 0; i < mDegree; i++) { a[i] = new GF2Polynomial(matrix[i]); inv[i] = new GF2Polynomial(mDegree); inv[i].setBit(mDegree - 1 - i); } // construct triangle matrix so that for each a[i] the first i bits are // zero for (i = 0; i < mDegree - 1; i++) { // find column where bit i is set j = i; while ((j < mDegree) && !a[j].testBit(mDegree - 1 - i)) { j++; } if (j >= mDegree) { throw new RuntimeException( "GF2nField.invertMatrix: Matrix cannot be inverted!"); } if (i != j) { // swap a[i]/a[j] and inv[i]/inv[j] dummy = a[i]; a[i] = a[j]; a[j] = dummy; dummy = inv[i]; inv[i] = inv[j]; inv[j] = dummy; } for (j = i + 1; j < mDegree; j++) { // add column i to all columns>i // having their i-th bit set if (a[j].testBit(mDegree - 1 - i)) { a[j].addToThis(a[i]); inv[j].addToThis(inv[i]); } } } // construct Einheitsmatrix from a for (i = mDegree - 1; i > 0; i--) { for (j = i - 1; j >= 0; j--) { // eliminate the i-th bit in all // columns < i if (a[j].testBit(mDegree - 1 - i)) { a[j].addToThis(a[i]); inv[j].addToThis(inv[i]); } } } return inv; } /** * Converts the given element in representation according to this field to a * new element in representation according to B1 using the change-of-basis * matrix calculated by computeCOBMatrix. * * @param elem the GF2nElement to convert * @param basis the basis to convert <tt>elem</tt> to * @return <tt>elem</tt> converted to a new element representation * according to <tt>basis</tt> * @see GF2nField#computeCOBMatrix * @see GF2nField#getRandomRoot * @see GF2nPolynomial * @see "P1363 A.7 p109ff" */ public final GF2nElement convert(GF2nElement elem, GF2nField basis) throws RuntimeException { if (basis == this) { return (GF2nElement)elem.clone(); } if (fieldPolynomial.equals(basis.fieldPolynomial)) { return (GF2nElement)elem.clone(); } if (mDegree != basis.mDegree) { throw new RuntimeException("GF2nField.convert: B1 has a" + " different degree and thus cannot be coverted to!"); } int i; GF2Polynomial[] COBMatrix; i = fields.indexOf(basis); if (i == -1) { computeCOBMatrix(basis); i = fields.indexOf(basis); } COBMatrix = (GF2Polynomial[])matrices.elementAt(i); GF2nElement elemCopy = (GF2nElement)elem.clone(); if (elemCopy instanceof GF2nONBElement) { // remember: ONB treats its bits in reverse order ((GF2nONBElement)elemCopy).reverseOrder(); } GF2Polynomial bs = new GF2Polynomial(mDegree, elemCopy.toFlexiBigInt()); bs.expandN(mDegree); GF2Polynomial result = new GF2Polynomial(mDegree); for (i = 0; i < mDegree; i++) { if (bs.vectorMult(COBMatrix[i])) { result.setBit(mDegree - 1 - i); } } if (basis instanceof GF2nPolynomialField) { return new GF2nPolynomialElement((GF2nPolynomialField)basis, result); } else if (basis instanceof GF2nONBField) { GF2nONBElement res = new GF2nONBElement((GF2nONBField)basis, result.toFlexiBigInt()); // TODO Remember: ONB treats its Bits in reverse order !!! res.reverseOrder(); return res; } else { throw new RuntimeException( "GF2nField.convert: B1 must be an instance of " + "GF2nPolynomialField or GF2nONBField!"); } } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_42_5
crossvul-java_data_bad_42_8
package org.bouncycastle.pqc.jcajce.provider.xmss; import java.io.IOException; import java.security.PrivateKey; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.pqc.asn1.PQCObjectIdentifiers; import org.bouncycastle.pqc.asn1.XMSSMTKeyParams; import org.bouncycastle.pqc.asn1.XMSSMTPrivateKey; import org.bouncycastle.pqc.asn1.XMSSPrivateKey; import org.bouncycastle.pqc.crypto.xmss.BDSStateMap; import org.bouncycastle.pqc.crypto.xmss.XMSSMTParameters; import org.bouncycastle.pqc.crypto.xmss.XMSSMTPrivateKeyParameters; import org.bouncycastle.pqc.crypto.xmss.XMSSUtil; import org.bouncycastle.pqc.jcajce.interfaces.XMSSMTKey; import org.bouncycastle.util.Arrays; public class BCXMSSMTPrivateKey implements PrivateKey, XMSSMTKey { private final ASN1ObjectIdentifier treeDigest; private final XMSSMTPrivateKeyParameters keyParams; public BCXMSSMTPrivateKey( ASN1ObjectIdentifier treeDigest, XMSSMTPrivateKeyParameters keyParams) { this.treeDigest = treeDigest; this.keyParams = keyParams; } public BCXMSSMTPrivateKey(PrivateKeyInfo keyInfo) throws IOException { XMSSMTKeyParams keyParams = XMSSMTKeyParams.getInstance(keyInfo.getPrivateKeyAlgorithm().getParameters()); this.treeDigest = keyParams.getTreeDigest().getAlgorithm(); XMSSPrivateKey xmssMtPrivateKey = XMSSPrivateKey.getInstance(keyInfo.parsePrivateKey()); try { XMSSMTPrivateKeyParameters.Builder keyBuilder = new XMSSMTPrivateKeyParameters .Builder(new XMSSMTParameters(keyParams.getHeight(), keyParams.getLayers(), DigestUtil.getDigest(treeDigest))) .withIndex(xmssMtPrivateKey.getIndex()) .withSecretKeySeed(xmssMtPrivateKey.getSecretKeySeed()) .withSecretKeyPRF(xmssMtPrivateKey.getSecretKeyPRF()) .withPublicSeed(xmssMtPrivateKey.getPublicSeed()) .withRoot(xmssMtPrivateKey.getRoot()); if (xmssMtPrivateKey.getBdsState() != null) { keyBuilder.withBDSState((BDSStateMap)XMSSUtil.deserialize(xmssMtPrivateKey.getBdsState())); } this.keyParams = keyBuilder.build(); } catch (ClassNotFoundException e) { throw new IOException("ClassNotFoundException processing BDS state: " + e.getMessage()); } } public String getAlgorithm() { return "XMSSMT"; } public String getFormat() { return "PKCS#8"; } public byte[] getEncoded() { PrivateKeyInfo pki; try { AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.xmss_mt, new XMSSMTKeyParams(keyParams.getParameters().getHeight(), keyParams.getParameters().getLayers(), new AlgorithmIdentifier(treeDigest))); pki = new PrivateKeyInfo(algorithmIdentifier, createKeyStructure()); return pki.getEncoded(); } catch (IOException e) { return null; } } CipherParameters getKeyParams() { return keyParams; } public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof BCXMSSMTPrivateKey) { BCXMSSMTPrivateKey otherKey = (BCXMSSMTPrivateKey)o; return treeDigest.equals(otherKey.treeDigest) && Arrays.areEqual(keyParams.toByteArray(), otherKey.keyParams.toByteArray()); } return false; } public int hashCode() { return treeDigest.hashCode() + 37 * Arrays.hashCode(keyParams.toByteArray()); } private XMSSMTPrivateKey createKeyStructure() { byte[] keyData = keyParams.toByteArray(); int n = keyParams.getParameters().getDigestSize(); int totalHeight = keyParams.getParameters().getHeight(); int indexSize = (totalHeight + 7) / 8; int secretKeySize = n; int secretKeyPRFSize = n; int publicSeedSize = n; int rootSize = n; int position = 0; int index = (int)XMSSUtil.bytesToXBigEndian(keyData, position, indexSize); if (!XMSSUtil.isIndexValid(totalHeight, index)) { throw new IllegalArgumentException("index out of bounds"); } position += indexSize; byte[] secretKeySeed = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeySize); position += secretKeySize; byte[] secretKeyPRF = XMSSUtil.extractBytesAtOffset(keyData, position, secretKeyPRFSize); position += secretKeyPRFSize; byte[] publicSeed = XMSSUtil.extractBytesAtOffset(keyData, position, publicSeedSize); position += publicSeedSize; byte[] root = XMSSUtil.extractBytesAtOffset(keyData, position, rootSize); position += rootSize; /* import BDS state */ byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(keyData, position, keyData.length - position); return new XMSSMTPrivateKey(index, secretKeySeed, secretKeyPRF, publicSeed, root, bdsStateBinary); } ASN1ObjectIdentifier getTreeDigestOID() { return treeDigest; } public int getHeight() { return keyParams.getParameters().getHeight(); } public int getLayers() { return keyParams.getParameters().getLayers(); } public String getTreeDigest() { return DigestUtil.getXMSSDigestName(treeDigest); } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_42_8
crossvul-java_data_good_1893_1
package io.onedev.server.web; import org.apache.wicket.core.request.mapper.ResourceMapper; import org.apache.wicket.markup.html.pages.BrowserInfoPage; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.request.IRequestMapper; import org.apache.wicket.request.mapper.CompoundRequestMapper; import io.onedev.server.GeneralException; import io.onedev.server.web.asset.icon.IconScope; import io.onedev.server.web.mapper.BaseResourceMapper; import io.onedev.server.web.mapper.DynamicPathPageMapper; import io.onedev.server.web.mapper.DynamicPathResourceMapper; import io.onedev.server.web.page.admin.authenticator.AuthenticatorPage; import io.onedev.server.web.page.admin.databasebackup.DatabaseBackupPage; import io.onedev.server.web.page.admin.generalsecuritysetting.GeneralSecuritySettingPage; import io.onedev.server.web.page.admin.groovyscript.GroovyScriptListPage; import io.onedev.server.web.page.admin.group.GroupListPage; import io.onedev.server.web.page.admin.group.authorization.GroupAuthorizationsPage; import io.onedev.server.web.page.admin.group.create.NewGroupPage; import io.onedev.server.web.page.admin.group.membership.GroupMembershipsPage; import io.onedev.server.web.page.admin.group.profile.GroupProfilePage; import io.onedev.server.web.page.admin.issuesetting.defaultboard.DefaultBoardListPage; import io.onedev.server.web.page.admin.issuesetting.fieldspec.IssueFieldListPage; import io.onedev.server.web.page.admin.issuesetting.issuetemplate.IssueTemplateListPage; import io.onedev.server.web.page.admin.issuesetting.statespec.IssueStateListPage; import io.onedev.server.web.page.admin.issuesetting.transitionspec.StateTransitionListPage; import io.onedev.server.web.page.admin.jobexecutor.JobExecutorsPage; import io.onedev.server.web.page.admin.mailsetting.MailSettingPage; import io.onedev.server.web.page.admin.role.NewRolePage; import io.onedev.server.web.page.admin.role.RoleDetailPage; import io.onedev.server.web.page.admin.role.RoleListPage; import io.onedev.server.web.page.admin.serverinformation.ServerInformationPage; import io.onedev.server.web.page.admin.serverlog.ServerLogPage; import io.onedev.server.web.page.admin.ssh.SshSettingPage; import io.onedev.server.web.page.admin.sso.SsoConnectorListPage; import io.onedev.server.web.page.admin.sso.SsoProcessPage; import io.onedev.server.web.page.admin.systemsetting.SystemSettingPage; import io.onedev.server.web.page.admin.user.UserListPage; import io.onedev.server.web.page.admin.user.accesstoken.UserAccessTokenPage; import io.onedev.server.web.page.admin.user.authorization.UserAuthorizationsPage; import io.onedev.server.web.page.admin.user.avatar.UserAvatarPage; import io.onedev.server.web.page.admin.user.create.NewUserPage; import io.onedev.server.web.page.admin.user.membership.UserMembershipsPage; import io.onedev.server.web.page.admin.user.password.UserPasswordPage; import io.onedev.server.web.page.admin.user.profile.UserProfilePage; import io.onedev.server.web.page.admin.user.ssh.UserSshKeysPage; import io.onedev.server.web.page.builds.BuildListPage; import io.onedev.server.web.page.issues.IssueListPage; import io.onedev.server.web.page.my.accesstoken.MyAccessTokenPage; import io.onedev.server.web.page.my.avatar.MyAvatarPage; import io.onedev.server.web.page.my.password.MyPasswordPage; import io.onedev.server.web.page.my.profile.MyProfilePage; import io.onedev.server.web.page.my.sshkeys.MySshKeysPage; import io.onedev.server.web.page.project.NewProjectPage; import io.onedev.server.web.page.project.ProjectListPage; import io.onedev.server.web.page.project.blob.ProjectBlobPage; import io.onedev.server.web.page.project.branches.ProjectBranchesPage; import io.onedev.server.web.page.project.builds.ProjectBuildsPage; import io.onedev.server.web.page.project.builds.detail.InvalidBuildPage; import io.onedev.server.web.page.project.builds.detail.artifacts.BuildArtifactsPage; import io.onedev.server.web.page.project.builds.detail.changes.BuildChangesPage; import io.onedev.server.web.page.project.builds.detail.dashboard.BuildDashboardPage; import io.onedev.server.web.page.project.builds.detail.issues.FixedIssuesPage; import io.onedev.server.web.page.project.builds.detail.log.BuildLogPage; import io.onedev.server.web.page.project.codecomments.InvalidCodeCommentPage; import io.onedev.server.web.page.project.codecomments.ProjectCodeCommentsPage; import io.onedev.server.web.page.project.commits.CommitDetailPage; import io.onedev.server.web.page.project.commits.ProjectCommitsPage; import io.onedev.server.web.page.project.compare.RevisionComparePage; import io.onedev.server.web.page.project.dashboard.ProjectDashboardPage; import io.onedev.server.web.page.project.issues.boards.IssueBoardsPage; import io.onedev.server.web.page.project.issues.create.NewIssuePage; import io.onedev.server.web.page.project.issues.detail.IssueActivitiesPage; import io.onedev.server.web.page.project.issues.detail.IssueBuildsPage; import io.onedev.server.web.page.project.issues.detail.IssueCommitsPage; import io.onedev.server.web.page.project.issues.detail.IssuePullRequestsPage; import io.onedev.server.web.page.project.issues.list.ProjectIssueListPage; import io.onedev.server.web.page.project.issues.milestones.MilestoneDetailPage; import io.onedev.server.web.page.project.issues.milestones.MilestoneEditPage; import io.onedev.server.web.page.project.issues.milestones.MilestoneListPage; import io.onedev.server.web.page.project.issues.milestones.NewMilestonePage; import io.onedev.server.web.page.project.pullrequests.InvalidPullRequestPage; import io.onedev.server.web.page.project.pullrequests.ProjectPullRequestsPage; import io.onedev.server.web.page.project.pullrequests.create.NewPullRequestPage; import io.onedev.server.web.page.project.pullrequests.detail.activities.PullRequestActivitiesPage; import io.onedev.server.web.page.project.pullrequests.detail.changes.PullRequestChangesPage; import io.onedev.server.web.page.project.pullrequests.detail.codecomments.PullRequestCodeCommentsPage; import io.onedev.server.web.page.project.pullrequests.detail.mergepreview.MergePreviewPage; import io.onedev.server.web.page.project.setting.authorization.ProjectAuthorizationsPage; import io.onedev.server.web.page.project.setting.avatar.AvatarEditPage; import io.onedev.server.web.page.project.setting.branchprotection.BranchProtectionsPage; import io.onedev.server.web.page.project.setting.build.ActionAuthorizationsPage; import io.onedev.server.web.page.project.setting.build.BuildPreservationsPage; import io.onedev.server.web.page.project.setting.build.JobSecretsPage; import io.onedev.server.web.page.project.setting.general.GeneralProjectSettingPage; import io.onedev.server.web.page.project.setting.tagprotection.TagProtectionsPage; import io.onedev.server.web.page.project.setting.webhook.WebHooksPage; import io.onedev.server.web.page.project.stats.ProjectContribsPage; import io.onedev.server.web.page.project.stats.SourceLinesPage; import io.onedev.server.web.page.project.tags.ProjectTagsPage; import io.onedev.server.web.page.pullrequests.PullRequestListPage; import io.onedev.server.web.page.simple.error.PageNotFoundErrorPage; import io.onedev.server.web.page.simple.security.LoginPage; import io.onedev.server.web.page.simple.security.LogoutPage; import io.onedev.server.web.page.simple.security.PasswordResetPage; import io.onedev.server.web.page.simple.security.SignUpPage; import io.onedev.server.web.page.simple.serverinit.ServerInitPage; import io.onedev.server.web.resource.ArchiveResourceReference; import io.onedev.server.web.resource.ArtifactResourceReference; import io.onedev.server.web.resource.AttachmentResourceReference; import io.onedev.server.web.resource.BuildLogResourceReference; import io.onedev.server.web.resource.RawBlobResourceReference; import io.onedev.server.web.resource.ServerLogResourceReference; import io.onedev.server.web.resource.SvgSpriteResourceReference; public class BaseUrlMapper extends CompoundRequestMapper { @Override public CompoundRequestMapper add(IRequestMapper mapper) { if (mapper instanceof ResourceMapper && !(mapper instanceof BaseResourceMapper)) throw new GeneralException("Base resource mapper should be used"); return super.add(mapper); } public BaseUrlMapper(WebApplication app) { add(new DynamicPathPageMapper("init", ServerInitPage.class)); add(new DynamicPathPageMapper("loading", BrowserInfoPage.class)); add(new DynamicPathPageMapper("issues", IssueListPage.class)); add(new DynamicPathPageMapper("pull-requests", PullRequestListPage.class)); add(new DynamicPathPageMapper("builds", BuildListPage.class)); addProjectPages(); addMyPages(); addAdministrationPages(); addSecurityPages(); addResources(); addErrorPages(); } private void addMyPages() { add(new DynamicPathPageMapper("my/profile", MyProfilePage.class)); add(new DynamicPathPageMapper("my/avatar", MyAvatarPage.class)); add(new DynamicPathPageMapper("my/password", MyPasswordPage.class)); add(new DynamicPathPageMapper("my/ssh-keys", MySshKeysPage.class)); add(new DynamicPathPageMapper("my/access-token", MyAccessTokenPage.class)); } private void addResources() { add(new BaseResourceMapper("downloads/server-log", new ServerLogResourceReference())); add(new BaseResourceMapper("downloads/projects/${project}/builds/${build}/log", new BuildLogResourceReference())); add(new BaseResourceMapper("projects/${project}/archive/${revision}", new ArchiveResourceReference())); add(new DynamicPathResourceMapper("projects/${project}/raw/${revision}/${path}", new RawBlobResourceReference())); add(new BaseResourceMapper("projects/${project}/attachment/${uuid}/${attachment}", new AttachmentResourceReference())); add(new DynamicPathResourceMapper("downloads/projects/${project}/builds/${build}/artifacts/${path}", new ArtifactResourceReference())); add(new BaseResourceMapper(SvgSpriteResourceReference.DEFAULT_MOUNT_PATH, new SvgSpriteResourceReference(IconScope.class))); } private void addErrorPages() { add(new DynamicPathPageMapper("/errors/404", PageNotFoundErrorPage.class)); } private void addSecurityPages() { add(new DynamicPathPageMapper("login", LoginPage.class)); add(new DynamicPathPageMapper("logout", LogoutPage.class)); add(new DynamicPathPageMapper("signup", SignUpPage.class)); add(new DynamicPathPageMapper("reset-password", PasswordResetPage.class)); add(new DynamicPathPageMapper(SsoProcessPage.MOUNT_PATH + "/${stage}/${connector}", SsoProcessPage.class)); } private void addAdministrationPages() { add(new DynamicPathPageMapper("administration", UserListPage.class)); add(new DynamicPathPageMapper("administration/users", UserListPage.class)); add(new DynamicPathPageMapper("administration/users/new", NewUserPage.class)); add(new DynamicPathPageMapper("administration/users/${user}/profile", UserProfilePage.class)); add(new DynamicPathPageMapper("administration/users/${user}/groups", UserMembershipsPage.class)); add(new DynamicPathPageMapper("administration/users/${user}/authorizations", UserAuthorizationsPage.class)); add(new DynamicPathPageMapper("administration/users/${user}/avatar", UserAvatarPage.class)); add(new DynamicPathPageMapper("administration/users/${user}/password", UserPasswordPage.class)); add(new DynamicPathPageMapper("administration/users/${user}/ssh-keys", UserSshKeysPage.class)); add(new DynamicPathPageMapper("administration/users/${user}/access-token", UserAccessTokenPage.class)); add(new DynamicPathPageMapper("administration/roles", RoleListPage.class)); add(new DynamicPathPageMapper("administration/roles/new", NewRolePage.class)); add(new DynamicPathPageMapper("administration/roles/${role}", RoleDetailPage.class)); add(new DynamicPathPageMapper("administration/groups", GroupListPage.class)); add(new DynamicPathPageMapper("administration/groups/new", NewGroupPage.class)); add(new DynamicPathPageMapper("administration/groups/${group}/profile", GroupProfilePage.class)); add(new DynamicPathPageMapper("administration/groups/${group}/members", GroupMembershipsPage.class)); add(new DynamicPathPageMapper("administration/groups/${group}/authorizations", GroupAuthorizationsPage.class)); add(new DynamicPathPageMapper("administration/settings/system", SystemSettingPage.class)); add(new DynamicPathPageMapper("administration/settings/mail", MailSettingPage.class)); add(new DynamicPathPageMapper("administration/settings/backup", DatabaseBackupPage.class)); add(new DynamicPathPageMapper("administration/settings/security", GeneralSecuritySettingPage.class)); add(new DynamicPathPageMapper("administration/settings/authenticator", AuthenticatorPage.class)); add(new DynamicPathPageMapper("administration/settings/sso-connectors", SsoConnectorListPage.class)); add(new DynamicPathPageMapper("administration/settings/ssh", SshSettingPage.class)); add(new DynamicPathPageMapper("administration/settings/job-executors", JobExecutorsPage.class)); add(new DynamicPathPageMapper("administration/settings/groovy-scripts", GroovyScriptListPage.class)); add(new DynamicPathPageMapper("administration/settings/issue-fields", IssueFieldListPage.class)); add(new DynamicPathPageMapper("administration/settings/issue-states", IssueStateListPage.class)); add(new DynamicPathPageMapper("administration/settings/state-transitions", StateTransitionListPage.class)); add(new DynamicPathPageMapper("administration/settings/issue-boards", DefaultBoardListPage.class)); add(new DynamicPathPageMapper("administration/settings/issue-templates", IssueTemplateListPage.class)); add(new DynamicPathPageMapper("administration/server-log", ServerLogPage.class)); add(new DynamicPathPageMapper("administration/server-information", ServerInformationPage.class)); } private void addProjectPages() { add(new DynamicPathPageMapper("projects", ProjectListPage.class)); add(new DynamicPathPageMapper("projects/new", NewProjectPage.class)); add(new DynamicPathPageMapper("projects/${project}", ProjectDashboardPage.class)); add(new DynamicPathPageMapper("projects/${project}/blob/#{revision}/#{path}", ProjectBlobPage.class)); add(new DynamicPathPageMapper("projects/${project}/commits", ProjectCommitsPage.class)); add(new DynamicPathPageMapper("projects/${project}/commits/${revision}", CommitDetailPage.class)); add(new DynamicPathPageMapper("projects/${project}/compare", RevisionComparePage.class)); add(new DynamicPathPageMapper("projects/${project}/stats/contribs", ProjectContribsPage.class)); add(new DynamicPathPageMapper("projects/${project}/stats/lines", SourceLinesPage.class)); add(new DynamicPathPageMapper("projects/${project}/branches", ProjectBranchesPage.class)); add(new DynamicPathPageMapper("projects/${project}/tags", ProjectTagsPage.class)); add(new DynamicPathPageMapper("projects/${project}/code-comments", ProjectCodeCommentsPage.class)); add(new DynamicPathPageMapper("projects/${project}/code-comments/${code-comment}/invalid", InvalidCodeCommentPage.class)); add(new DynamicPathPageMapper("projects/${project}/pulls", ProjectPullRequestsPage.class)); add(new DynamicPathPageMapper("projects/${project}/pulls/new", NewPullRequestPage.class)); add(new DynamicPathPageMapper("projects/${project}/pulls/${request}", PullRequestActivitiesPage.class)); add(new DynamicPathPageMapper("projects/${project}/pulls/${request}/activities", PullRequestActivitiesPage.class)); add(new DynamicPathPageMapper("projects/${project}/pulls/${request}/code-comments", PullRequestCodeCommentsPage.class)); add(new DynamicPathPageMapper("projects/${project}/pulls/${request}/changes", PullRequestChangesPage.class)); add(new DynamicPathPageMapper("projects/${project}/pulls/${request}/merge-preview", MergePreviewPage.class)); add(new DynamicPathPageMapper("projects/${project}/pulls/${request}/invalid", InvalidPullRequestPage.class)); add(new DynamicPathPageMapper("projects/${project}/issues/boards", IssueBoardsPage.class)); add(new DynamicPathPageMapper("projects/${project}/issues/boards/${board}", IssueBoardsPage.class)); add(new DynamicPathPageMapper("projects/${project}/issues/list", ProjectIssueListPage.class)); add(new DynamicPathPageMapper("projects/${project}/issues/${issue}", IssueActivitiesPage.class)); add(new DynamicPathPageMapper("projects/${project}/issues/${issue}/activities", IssueActivitiesPage.class)); add(new DynamicPathPageMapper("projects/${project}/issues/${issue}/commits", IssueCommitsPage.class)); add(new DynamicPathPageMapper("projects/${project}/issues/${issue}/pull-requests", IssuePullRequestsPage.class)); add(new DynamicPathPageMapper("projects/${project}/issues/${issue}/builds", IssueBuildsPage.class)); add(new DynamicPathPageMapper("projects/${project}/issues/new", NewIssuePage.class)); add(new DynamicPathPageMapper("projects/${project}/milestones", MilestoneListPage.class)); add(new DynamicPathPageMapper("projects/${project}/milestones/${milestone}", MilestoneDetailPage.class)); add(new DynamicPathPageMapper("projects/${project}/milestones/${milestone}/edit", MilestoneEditPage.class)); add(new DynamicPathPageMapper("projects/${project}/milestones/new", NewMilestonePage.class)); add(new DynamicPathPageMapper("projects/${project}/builds", ProjectBuildsPage.class)); add(new DynamicPathPageMapper("projects/${project}/builds/${build}", BuildDashboardPage.class)); add(new DynamicPathPageMapper("projects/${project}/builds/${build}/log", BuildLogPage.class)); add(new DynamicPathPageMapper("projects/${project}/builds/${build}/changes", BuildChangesPage.class)); add(new DynamicPathPageMapper("projects/${project}/builds/${build}/fixed-issues", FixedIssuesPage.class)); add(new DynamicPathPageMapper("projects/${project}/builds/${build}/artifacts", BuildArtifactsPage.class)); add(new DynamicPathPageMapper("projects/${project}/builds/${build}/invalid", InvalidBuildPage.class)); add(new DynamicPathPageMapper("projects/${project}/settings/general", GeneralProjectSettingPage.class)); add(new DynamicPathPageMapper("projects/${project}/settings/authorizations", ProjectAuthorizationsPage.class)); add(new DynamicPathPageMapper("projects/${project}/settings/avatar-edit", AvatarEditPage.class)); add(new DynamicPathPageMapper("projects/${project}/settings/branch-protection", BranchProtectionsPage.class)); add(new DynamicPathPageMapper("projects/${project}/settings/tag-protection", TagProtectionsPage.class)); add(new DynamicPathPageMapper("projects/${project}/settings/build/job-secrets", JobSecretsPage.class)); add(new DynamicPathPageMapper("projects/${project}/settings/build/action-authorizations", ActionAuthorizationsPage.class)); add(new DynamicPathPageMapper("projects/${project}/settings/build/build-preserve-rules", BuildPreservationsPage.class)); add(new DynamicPathPageMapper("projects/${project}/settings/web-hooks", WebHooksPage.class)); } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_1893_1
crossvul-java_data_good_172_1
package com.fasterxml.jackson.databind.jsontype.impl; import java.util.Collections; import java.util.HashSet; import java.util.Set; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; /** * Helper class used to encapsulate rules that determine subtypes that * are invalid to use, even with default typing, mostly due to security * concerns. * Used by <code>BeanDeserializerFacotry</code> * * @since 2.8.11 */ public class SubTypeValidator { protected final static String PREFIX_SPRING = "org.springframework."; protected final static String PREFIX_C3P0 = "com.mchange.v2.c3p0."; /** * Set of well-known "nasty classes", deserialization of which is considered dangerous * and should (and is) prevented by default. */ protected final static Set<String> DEFAULT_NO_DESER_CLASS_NAMES; static { Set<String> s = new HashSet<String>(); // Courtesy of [https://github.com/kantega/notsoserial]: // (and wrt [databind#1599]) s.add("org.apache.commons.collections.functors.InvokerTransformer"); s.add("org.apache.commons.collections.functors.InstantiateTransformer"); s.add("org.apache.commons.collections4.functors.InvokerTransformer"); s.add("org.apache.commons.collections4.functors.InstantiateTransformer"); s.add("org.codehaus.groovy.runtime.ConvertedClosure"); s.add("org.codehaus.groovy.runtime.MethodClosure"); s.add("org.springframework.beans.factory.ObjectFactory"); s.add("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl"); s.add("org.apache.xalan.xsltc.trax.TemplatesImpl"); // [databind#1680]: may or may not be problem, take no chance s.add("com.sun.rowset.JdbcRowSetImpl"); // [databind#1737]; JDK provided s.add("java.util.logging.FileHandler"); s.add("java.rmi.server.UnicastRemoteObject"); // [databind#1737]; 3rd party //s.add("org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor"); // deprecated by [databind#1855] s.add("org.springframework.beans.factory.config.PropertyPathFactoryBean"); // s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource"); // deprecated by [databind#1931] // s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource"); // - "" - // [databind#1855]: more 3rd party s.add("org.apache.tomcat.dbcp.dbcp2.BasicDataSource"); s.add("com.sun.org.apache.bcel.internal.util.ClassLoader"); // [databind#2032]: more 3rd party; data exfiltration via xml parsed ext entities s.add("org.apache.ibatis.parsing.XPathParser"); // [databind#2052]: Jodd-db, with jndi/ldap lookup s.add("jodd.db.connection.DataSourceConnectionProvider"); // [databind#2058]: Oracle JDBC driver, with jndi/ldap lookup s.add("oracle.jdbc.connector.OracleManagedConnectionFactory"); s.add("oracle.jdbc.rowset.OracleJDBCRowSet"); DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s); } /** * Set of class names of types that are never to be deserialized. */ protected Set<String> _cfgIllegalClassNames = DEFAULT_NO_DESER_CLASS_NAMES; private final static SubTypeValidator instance = new SubTypeValidator(); protected SubTypeValidator() { } public static SubTypeValidator instance() { return instance; } public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException { // There are certain nasty classes that could cause problems, mostly // via default typing -- catch them here. final Class<?> raw = type.getRawClass(); String full = raw.getName(); main_check: do { if (_cfgIllegalClassNames.contains(full)) { break; } // 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling // for some Spring framework types // 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces if (raw.isInterface()) { ; } else if (full.startsWith(PREFIX_SPRING)) { for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()){ String name = cls.getSimpleName(); // looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there? if ("AbstractPointcutAdvisor".equals(name) // ditto for "FileSystemXmlApplicationContext": block all ApplicationContexts || "AbstractApplicationContext".equals(name)) { break main_check; } } } else if (full.startsWith(PREFIX_C3P0)) { // [databind#1737]; more 3rd party // s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource"); // s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource"); // [databind#1931]; more 3rd party // com.mchange.v2.c3p0.ComboPooledDataSource // com.mchange.v2.c3p0.debug.AfterCloseLoggingComboPooledDataSource if (full.endsWith("DataSource")) { break main_check; } } return; } while (false); throw JsonMappingException.from(ctxt, String.format("Illegal type (%s) to deserialize: prevented for security reasons", full)); } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_172_1
crossvul-java_data_bad_42_1
package org.bouncycastle.pqc.crypto.rainbow; import org.bouncycastle.crypto.CipherParameters; public class RainbowParameters implements CipherParameters { /** * DEFAULT PARAMS */ /* * Vi = vinegars per layer whereas n is vu (vu = 33 = n) such that * * v1 = 6; o1 = 12-6 = 6 * * v2 = 12; o2 = 17-12 = 5 * * v3 = 17; o3 = 22-17 = 5 * * v4 = 22; o4 = 33-22 = 11 * * v5 = 33; (o5 = 0) */ private final int[] DEFAULT_VI = {6, 12, 17, 22, 33}; private int[] vi;// set of vinegar vars per layer. /** * Default Constructor The elements of the array containing the number of * Vinegar variables in each layer are set to the default values here. */ public RainbowParameters() { this.vi = this.DEFAULT_VI; } /** * Constructor with parameters * * @param vi The elements of the array containing the number of Vinegar * variables per layer are set to the values of the input array. */ public RainbowParameters(int[] vi) { this.vi = vi; try { checkParams(); } catch (Exception e) { e.printStackTrace(); } } private void checkParams() throws Exception { if (vi == null) { throw new Exception("no layers defined."); } if (vi.length > 1) { for (int i = 0; i < vi.length - 1; i++) { if (vi[i] >= vi[i + 1]) { throw new Exception( "v[i] has to be smaller than v[i+1]"); } } } else { throw new Exception( "Rainbow needs at least 1 layer, such that v1 < v2."); } } /** * Getter for the number of layers * * @return the number of layers */ public int getNumOfLayers() { return this.vi.length - 1; } /** * Getter for the number of all the polynomials in Rainbow * * @return the number of the polynomials */ public int getDocLength() { return vi[vi.length - 1] - vi[0]; } /** * Getter for the array containing the number of Vinegar-variables per layer * * @return the numbers of vinegars per layer */ public int[] getVi() { return this.vi; } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_42_1
crossvul-java_data_good_3054_1
package hudson.util; import hudson.model.Items; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.servlet.ServletInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.when; public class XStream2Security383Test { @Rule public JenkinsRule j = new JenkinsRule(); @Rule public TemporaryFolder f = new TemporaryFolder(); @Mock private StaplerRequest req; @Mock private StaplerResponse rsp; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @Test @Issue("SECURITY-383") public void testXmlLoad() throws Exception { File exploitFile = f.newFile(); try { // be extra sure there's no file already if (exploitFile.exists() && !exploitFile.delete()) { throw new IllegalStateException("file exists and cannot be deleted"); } File tempJobDir = new File(j.jenkins.getRootDir(), "security383"); String exploitXml = IOUtils.toString( XStream2Security383Test.class.getResourceAsStream( "/hudson/util/XStream2Security383Test/config.xml"), "UTF-8"); exploitXml = exploitXml.replace("@TOKEN@", exploitFile.getAbsolutePath()); FileUtils.write(new File(tempJobDir, "config.xml"), exploitXml); try { Items.load(j.jenkins, tempJobDir); } catch (Exception e) { // ignore } assertFalse("no file should be created here", exploitFile.exists()); } finally { exploitFile.delete(); } } @Test @Issue("SECURITY-383") public void testPostJobXml() throws Exception { File exploitFile = f.newFile(); try { // be extra sure there's no file already if (exploitFile.exists() && !exploitFile.delete()) { throw new IllegalStateException("file exists and cannot be deleted"); } File tempJobDir = new File(j.jenkins.getRootDir(), "security383"); String exploitXml = IOUtils.toString( XStream2Security383Test.class.getResourceAsStream( "/hudson/util/XStream2Security383Test/config.xml"), "UTF-8"); exploitXml = exploitXml.replace("@TOKEN@", exploitFile.getAbsolutePath()); when(req.getMethod()).thenReturn("POST"); when(req.getInputStream()).thenReturn(new Stream(IOUtils.toInputStream(exploitXml))); when(req.getContentType()).thenReturn("application/xml"); when(req.getParameter("name")).thenReturn("foo"); try { j.jenkins.doCreateItem(req, rsp); } catch (Exception e) { // don't care } assertFalse("no file should be created here", exploitFile.exists()); } finally { exploitFile.delete(); } } private static class Stream extends ServletInputStream { private final InputStream inner; public Stream(final InputStream inner) { this.inner = inner; } @Override public int read() throws IOException { return inner.read(); } } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_3054_1
crossvul-java_data_bad_449_1
package com.fasterxml.jackson.databind.jsontype.impl; import java.util.Collections; import java.util.HashSet; import java.util.Set; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; /** * Helper class used to encapsulate rules that determine subtypes that * are invalid to use, even with default typing, mostly due to security * concerns. * Used by <code>BeanDeserializerFacotry</code> * * @since 2.8.11 */ public class SubTypeValidator { protected final static String PREFIX_SPRING = "org.springframework."; protected final static String PREFIX_C3P0 = "com.mchange.v2.c3p0."; /** * Set of well-known "nasty classes", deserialization of which is considered dangerous * and should (and is) prevented by default. */ protected final static Set<String> DEFAULT_NO_DESER_CLASS_NAMES; static { Set<String> s = new HashSet<String>(); // Courtesy of [https://github.com/kantega/notsoserial]: // (and wrt [databind#1599]) s.add("org.apache.commons.collections.functors.InvokerTransformer"); s.add("org.apache.commons.collections.functors.InstantiateTransformer"); s.add("org.apache.commons.collections4.functors.InvokerTransformer"); s.add("org.apache.commons.collections4.functors.InstantiateTransformer"); s.add("org.codehaus.groovy.runtime.ConvertedClosure"); s.add("org.codehaus.groovy.runtime.MethodClosure"); s.add("org.springframework.beans.factory.ObjectFactory"); s.add("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl"); s.add("org.apache.xalan.xsltc.trax.TemplatesImpl"); // [databind#1680]: may or may not be problem, take no chance s.add("com.sun.rowset.JdbcRowSetImpl"); // [databind#1737]; JDK provided s.add("java.util.logging.FileHandler"); s.add("java.rmi.server.UnicastRemoteObject"); // [databind#1737]; 3rd party //s.add("org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor"); // deprecated by [databind#1855] s.add("org.springframework.beans.factory.config.PropertyPathFactoryBean"); // s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource"); // deprecated by [databind#1931] // s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource"); // - "" - // [databind#1855]: more 3rd party s.add("org.apache.tomcat.dbcp.dbcp2.BasicDataSource"); s.add("com.sun.org.apache.bcel.internal.util.ClassLoader"); // [databind#2032]: more 3rd party; data exfiltration via xml parsed ext entities s.add("org.apache.ibatis.parsing.XPathParser"); // [databind#2052]: Jodd-db, with jndi/ldap lookup s.add("jodd.db.connection.DataSourceConnectionProvider"); // [databind#2058]: Oracle JDBC driver, with jndi/ldap lookup s.add("oracle.jdbc.connector.OracleManagedConnectionFactory"); s.add("oracle.jdbc.rowset.OracleJDBCRowSet"); // [databind#1899]: more 3rd party s.add("org.hibernate.jmx.StatisticsService"); s.add("org.apache.ibatis.datasource.jndi.JndiDataSourceFactory"); // [databind#2097]: some 3rd party, one JDK-bundled s.add("org.slf4j.ext.EventData"); s.add("flex.messaging.util.concurrent.AsynchBeansWorkManagerExecutor"); s.add("com.sun.deploy.security.ruleset.DRSHelper"); s.add("org.apache.axis2.jaxws.spi.handler.HandlerResolverImpl"); DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s); } /** * Set of class names of types that are never to be deserialized. */ protected Set<String> _cfgIllegalClassNames = DEFAULT_NO_DESER_CLASS_NAMES; private final static SubTypeValidator instance = new SubTypeValidator(); protected SubTypeValidator() { } public static SubTypeValidator instance() { return instance; } public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException { // There are certain nasty classes that could cause problems, mostly // via default typing -- catch them here. final Class<?> raw = type.getRawClass(); String full = raw.getName(); main_check: do { if (_cfgIllegalClassNames.contains(full)) { break; } // 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling // for some Spring framework types // 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces if (raw.isInterface()) { ; } else if (full.startsWith(PREFIX_SPRING)) { for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()){ String name = cls.getSimpleName(); // looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there? if ("AbstractPointcutAdvisor".equals(name) // ditto for "FileSystemXmlApplicationContext": block all ApplicationContexts || "AbstractApplicationContext".equals(name)) { break main_check; } } } else if (full.startsWith(PREFIX_C3P0)) { // [databind#1737]; more 3rd party // s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource"); // s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource"); // [databind#1931]; more 3rd party // com.mchange.v2.c3p0.ComboPooledDataSource // com.mchange.v2.c3p0.debug.AfterCloseLoggingComboPooledDataSource if (full.endsWith("DataSource")) { break main_check; } } return; } while (false); throw JsonMappingException.from(ctxt, String.format("Illegal type (%s) to deserialize: prevented for security reasons", full)); } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_449_1
crossvul-java_data_bad_590_2
404: Not Found
./CrossVul/dataset_final_sorted/CWE-502/java/bad_590_2
crossvul-java_data_bad_42_2
package org.bouncycastle.pqc.crypto.xmss; import java.io.IOException; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.util.Arrays; /** * XMSS^MT Private Key. */ public final class XMSSMTPrivateKeyParameters extends AsymmetricKeyParameter implements XMSSStoreableObjectInterface { private final XMSSMTParameters params; private final long index; private final byte[] secretKeySeed; private final byte[] secretKeyPRF; private final byte[] publicSeed; private final byte[] root; private final BDSStateMap bdsState; private XMSSMTPrivateKeyParameters(Builder builder) { super(true); params = builder.params; if (params == null) { throw new NullPointerException("params == null"); } int n = params.getDigestSize(); byte[] privateKey = builder.privateKey; if (privateKey != null) { if (builder.xmss == null) { throw new NullPointerException("xmss == null"); } /* import */ int totalHeight = params.getHeight(); int indexSize = (totalHeight + 7) / 8; int secretKeySize = n; int secretKeyPRFSize = n; int publicSeedSize = n; int rootSize = n; /* int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize; if (privateKey.length != totalSize) { throw new ParseException("private key has wrong size", 0); } */ int position = 0; index = XMSSUtil.bytesToXBigEndian(privateKey, position, indexSize); if (!XMSSUtil.isIndexValid(totalHeight, index)) { throw new IllegalArgumentException("index out of bounds"); } position += indexSize; secretKeySeed = XMSSUtil.extractBytesAtOffset(privateKey, position, secretKeySize); position += secretKeySize; secretKeyPRF = XMSSUtil.extractBytesAtOffset(privateKey, position, secretKeyPRFSize); position += secretKeyPRFSize; publicSeed = XMSSUtil.extractBytesAtOffset(privateKey, position, publicSeedSize); position += publicSeedSize; root = XMSSUtil.extractBytesAtOffset(privateKey, position, rootSize); position += rootSize; /* import BDS state */ byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(privateKey, position, privateKey.length - position); BDSStateMap bdsImport = null; try { bdsImport = (BDSStateMap)XMSSUtil.deserialize(bdsStateBinary); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } bdsImport.setXMSS(builder.xmss); bdsState = bdsImport; } else { /* set */ index = builder.index; byte[] tmpSecretKeySeed = builder.secretKeySeed; if (tmpSecretKeySeed != null) { if (tmpSecretKeySeed.length != n) { throw new IllegalArgumentException("size of secretKeySeed needs to be equal size of digest"); } secretKeySeed = tmpSecretKeySeed; } else { secretKeySeed = new byte[n]; } byte[] tmpSecretKeyPRF = builder.secretKeyPRF; if (tmpSecretKeyPRF != null) { if (tmpSecretKeyPRF.length != n) { throw new IllegalArgumentException("size of secretKeyPRF needs to be equal size of digest"); } secretKeyPRF = tmpSecretKeyPRF; } else { secretKeyPRF = new byte[n]; } byte[] tmpPublicSeed = builder.publicSeed; if (tmpPublicSeed != null) { if (tmpPublicSeed.length != n) { throw new IllegalArgumentException("size of publicSeed needs to be equal size of digest"); } publicSeed = tmpPublicSeed; } else { publicSeed = new byte[n]; } byte[] tmpRoot = builder.root; if (tmpRoot != null) { if (tmpRoot.length != n) { throw new IllegalArgumentException("size of root needs to be equal size of digest"); } root = tmpRoot; } else { root = new byte[n]; } BDSStateMap tmpBDSState = builder.bdsState; if (tmpBDSState != null) { bdsState = tmpBDSState; } else { long globalIndex = builder.index; int totalHeight = params.getHeight(); if (XMSSUtil.isIndexValid(totalHeight, globalIndex) && tmpPublicSeed != null && tmpSecretKeySeed != null) { bdsState = new BDSStateMap(params, builder.index, tmpPublicSeed, tmpSecretKeySeed); } else { bdsState = new BDSStateMap(); } } } } public static class Builder { /* mandatory */ private final XMSSMTParameters params; /* optional */ private long index = 0L; private byte[] secretKeySeed = null; private byte[] secretKeyPRF = null; private byte[] publicSeed = null; private byte[] root = null; private BDSStateMap bdsState = null; private byte[] privateKey = null; private XMSSParameters xmss = null; public Builder(XMSSMTParameters params) { super(); this.params = params; } public Builder withIndex(long val) { index = val; return this; } public Builder withSecretKeySeed(byte[] val) { secretKeySeed = XMSSUtil.cloneArray(val); return this; } public Builder withSecretKeyPRF(byte[] val) { secretKeyPRF = XMSSUtil.cloneArray(val); return this; } public Builder withPublicSeed(byte[] val) { publicSeed = XMSSUtil.cloneArray(val); return this; } public Builder withRoot(byte[] val) { root = XMSSUtil.cloneArray(val); return this; } public Builder withBDSState(BDSStateMap val) { bdsState = val; return this; } public Builder withPrivateKey(byte[] privateKeyVal, XMSSParameters xmssVal) { privateKey = XMSSUtil.cloneArray(privateKeyVal); xmss = xmssVal; return this; } public XMSSMTPrivateKeyParameters build() { return new XMSSMTPrivateKeyParameters(this); } } public byte[] toByteArray() { /* index || secretKeySeed || secretKeyPRF || publicSeed || root */ int n = params.getDigestSize(); int indexSize = (params.getHeight() + 7) / 8; int secretKeySize = n; int secretKeyPRFSize = n; int publicSeedSize = n; int rootSize = n; int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize; byte[] out = new byte[totalSize]; int position = 0; /* copy index */ byte[] indexBytes = XMSSUtil.toBytesBigEndian(index, indexSize); XMSSUtil.copyBytesAtOffset(out, indexBytes, position); position += indexSize; /* copy secretKeySeed */ XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position); position += secretKeySize; /* copy secretKeyPRF */ XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position); position += secretKeyPRFSize; /* copy publicSeed */ XMSSUtil.copyBytesAtOffset(out, publicSeed, position); position += publicSeedSize; /* copy root */ XMSSUtil.copyBytesAtOffset(out, root, position); /* concatenate bdsState */ byte[] bdsStateOut = null; try { bdsStateOut = XMSSUtil.serialize(bdsState); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("error serializing bds state"); } return Arrays.concatenate(out, bdsStateOut); } public long getIndex() { return index; } public byte[] getSecretKeySeed() { return XMSSUtil.cloneArray(secretKeySeed); } public byte[] getSecretKeyPRF() { return XMSSUtil.cloneArray(secretKeyPRF); } public byte[] getPublicSeed() { return XMSSUtil.cloneArray(publicSeed); } public byte[] getRoot() { return XMSSUtil.cloneArray(root); } BDSStateMap getBDSState() { return bdsState; } public XMSSMTParameters getParameters() { return params; } public XMSSMTPrivateKeyParameters getNextKey() { BDSStateMap newState = new BDSStateMap(bdsState, params, this.getIndex(), publicSeed, secretKeySeed); return new XMSSMTPrivateKeyParameters.Builder(params).withIndex(index + 1) .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF) .withPublicSeed(publicSeed).withRoot(root) .withBDSState(newState).build(); } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_42_2
crossvul-java_data_bad_662_0
/** * Copyright (c) 2004-2011 QOS.ch * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.slf4j.ext; import java.io.Serializable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.beans.ExceptionListener; /** * Base class for Event Data. Event Data contains data to be logged about an * event. Users may extend this class for each EventType they want to log. * * @author Ralph Goers */ public class EventData implements Serializable { private static final long serialVersionUID = 153270778642103985L; private Map<String, Object> eventData = new HashMap<String, Object>(); public static final String EVENT_MESSAGE = "EventMessage"; public static final String EVENT_TYPE = "EventType"; public static final String EVENT_DATETIME = "EventDateTime"; public static final String EVENT_ID = "EventId"; /** * Default Constructor */ public EventData() { } /** * Constructor to create event data from a Map. * * @param map * The event data. */ public EventData(Map<String, Object> map) { eventData.putAll(map); } /** * Construct from a serialized form of the Map containing the RequestInfo * elements * * @param xml * The serialized form of the RequestInfo Map. */ @SuppressWarnings("unchecked") public EventData(String xml) { ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); try { XMLDecoder decoder = new XMLDecoder(bais); this.eventData = (Map<String, Object>) decoder.readObject(); } catch (Exception e) { throw new EventException("Error decoding " + xml, e); } } /** * Serialize all the EventData items into an XML representation. * * @return an XML String containing all the EventData items. */ public String toXML() { return toXML(eventData); } /** * Serialize all the EventData items into an XML representation. * * @param map the Map to transform * @return an XML String containing all the EventData items. */ public static String toXML(Map<String, Object> map) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { XMLEncoder encoder = new XMLEncoder(baos); encoder.setExceptionListener(new ExceptionListener() { public void exceptionThrown(Exception exception) { exception.printStackTrace(); } }); encoder.writeObject(map); encoder.close(); return baos.toString(); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Retrieve the event identifier. * * @return The event identifier */ public String getEventId() { return (String) this.eventData.get(EVENT_ID); } /** * Set the event identifier. * * @param eventId * The event identifier. */ public void setEventId(String eventId) { if (eventId == null) { throw new IllegalArgumentException("eventId cannot be null"); } this.eventData.put(EVENT_ID, eventId); } /** * Retrieve the message text associated with this event, if any. * * @return The message text associated with this event or null if there is * none. */ public String getMessage() { return (String) this.eventData.get(EVENT_MESSAGE); } /** * Set the message text associated with this event. * * @param message * The message text. */ public void setMessage(String message) { this.eventData.put(EVENT_MESSAGE, message); } /** * Retrieve the date and time the event occurred. * * @return The Date associated with the event. */ public Date getEventDateTime() { return (Date) this.eventData.get(EVENT_DATETIME); } /** * Set the date and time the event occurred in case it is not the same as when * the event was logged. * * @param eventDateTime * The event Date. */ public void setEventDateTime(Date eventDateTime) { this.eventData.put(EVENT_DATETIME, eventDateTime); } /** * Set the type of event that occurred. * * @param eventType * The type of the event. */ public void setEventType(String eventType) { this.eventData.put(EVENT_TYPE, eventType); } /** * Retrieve the type of the event. * * @return The event type. */ public String getEventType() { return (String) this.eventData.get(EVENT_TYPE); } /** * Add arbitrary attributes about the event. * * @param name * The attribute's key. * @param obj * The data associated with the key. */ public void put(String name, Serializable obj) { this.eventData.put(name, obj); } /** * Retrieve an event attribute. * * @param name * The attribute's key. * @return The value associated with the key or null if the key is not * present. */ public Serializable get(String name) { return (Serializable) this.eventData.get(name); } /** * Populate the event data from a Map. * * @param data * The Map to copy. */ public void putAll(Map<String, Object> data) { this.eventData.putAll(data); } /** * Returns the number of attributes in the EventData. * * @return the number of attributes in the EventData. */ public int getSize() { return this.eventData.size(); } /** * Returns an Iterator over all the entries in the EventData. * * @return an Iterator that can be used to access all the event attributes. */ public Iterator<Map.Entry<String, Object>> getEntrySetIterator() { return this.eventData.entrySet().iterator(); } /** * Retrieve all the attributes in the EventData as a Map. Changes to this map * will be reflected in the EventData. * * @return The Map of attributes in this EventData instance. */ public Map<String, Object> getEventMap() { return this.eventData; } /** * Convert the EventData to a String. * * @return The EventData as a String. */ @Override public String toString() { return toXML(); } /** * Compare two EventData objects for equality. * * @param o * The Object to compare. * @return true if the objects are the same instance or contain all the same * keys and their values. */ @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof EventData || o instanceof Map)) { return false; } Map<String, Object> map = (o instanceof EventData) ? ((EventData) o).getEventMap() : (Map<String, Object>) o; return this.eventData.equals(map); } /** * Compute the hashCode for this EventData instance. * * @return The hashcode for this EventData instance. */ @Override public int hashCode() { return this.eventData.hashCode(); } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_662_0
crossvul-java_data_bad_42_3
package org.bouncycastle.pqc.crypto.xmss; import java.io.IOException; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; /** * XMSS Private Key. */ public final class XMSSPrivateKeyParameters extends AsymmetricKeyParameter implements XMSSStoreableObjectInterface { /** * XMSS parameters object. */ private final XMSSParameters params; /** * Secret for the derivation of WOTS+ secret keys. */ private final byte[] secretKeySeed; /** * Secret for the randomization of message digests during signature * creation. */ private final byte[] secretKeyPRF; /** * Public seed for the randomization of hashes. */ private final byte[] publicSeed; /** * Public root of binary tree. */ private final byte[] root; /** * BDS state. */ private final BDS bdsState; private XMSSPrivateKeyParameters(Builder builder) { super(true); params = builder.params; if (params == null) { throw new NullPointerException("params == null"); } int n = params.getDigestSize(); byte[] privateKey = builder.privateKey; if (privateKey != null) { if (builder.xmss == null) { throw new NullPointerException("xmss == null"); } /* import */ int height = params.getHeight(); int indexSize = 4; int secretKeySize = n; int secretKeyPRFSize = n; int publicSeedSize = n; int rootSize = n; /* int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize; if (privateKey.length != totalSize) { throw new ParseException("private key has wrong size", 0); } */ int position = 0; int index = Pack.bigEndianToInt(privateKey, position); if (!XMSSUtil.isIndexValid(height, index)) { throw new IllegalArgumentException("index out of bounds"); } position += indexSize; secretKeySeed = XMSSUtil.extractBytesAtOffset(privateKey, position, secretKeySize); position += secretKeySize; secretKeyPRF = XMSSUtil.extractBytesAtOffset(privateKey, position, secretKeyPRFSize); position += secretKeyPRFSize; publicSeed = XMSSUtil.extractBytesAtOffset(privateKey, position, publicSeedSize); position += publicSeedSize; root = XMSSUtil.extractBytesAtOffset(privateKey, position, rootSize); position += rootSize; /* import BDS state */ byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(privateKey, position, privateKey.length - position); BDS bdsImport = null; try { bdsImport = (BDS)XMSSUtil.deserialize(bdsStateBinary); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } bdsImport.setXMSS(builder.xmss); bdsImport.validate(); if (bdsImport.getIndex() != index) { throw new IllegalStateException("serialized BDS has wrong index"); } bdsState = bdsImport; } else { /* set */ byte[] tmpSecretKeySeed = builder.secretKeySeed; if (tmpSecretKeySeed != null) { if (tmpSecretKeySeed.length != n) { throw new IllegalArgumentException("size of secretKeySeed needs to be equal size of digest"); } secretKeySeed = tmpSecretKeySeed; } else { secretKeySeed = new byte[n]; } byte[] tmpSecretKeyPRF = builder.secretKeyPRF; if (tmpSecretKeyPRF != null) { if (tmpSecretKeyPRF.length != n) { throw new IllegalArgumentException("size of secretKeyPRF needs to be equal size of digest"); } secretKeyPRF = tmpSecretKeyPRF; } else { secretKeyPRF = new byte[n]; } byte[] tmpPublicSeed = builder.publicSeed; if (tmpPublicSeed != null) { if (tmpPublicSeed.length != n) { throw new IllegalArgumentException("size of publicSeed needs to be equal size of digest"); } publicSeed = tmpPublicSeed; } else { publicSeed = new byte[n]; } byte[] tmpRoot = builder.root; if (tmpRoot != null) { if (tmpRoot.length != n) { throw new IllegalArgumentException("size of root needs to be equal size of digest"); } root = tmpRoot; } else { root = new byte[n]; } BDS tmpBDSState = builder.bdsState; if (tmpBDSState != null) { bdsState = tmpBDSState; } else { if (builder.index < ((1 << params.getHeight()) - 2) && tmpPublicSeed != null && tmpSecretKeySeed != null) { bdsState = new BDS(params, tmpPublicSeed, tmpSecretKeySeed, (OTSHashAddress)new OTSHashAddress.Builder().build(), builder.index); } else { bdsState = new BDS(params, builder.index); } } } } public static class Builder { /* mandatory */ private final XMSSParameters params; /* optional */ private int index = 0; private byte[] secretKeySeed = null; private byte[] secretKeyPRF = null; private byte[] publicSeed = null; private byte[] root = null; private BDS bdsState = null; private byte[] privateKey = null; private XMSSParameters xmss = null; public Builder(XMSSParameters params) { super(); this.params = params; } public Builder withIndex(int val) { index = val; return this; } public Builder withSecretKeySeed(byte[] val) { secretKeySeed = XMSSUtil.cloneArray(val); return this; } public Builder withSecretKeyPRF(byte[] val) { secretKeyPRF = XMSSUtil.cloneArray(val); return this; } public Builder withPublicSeed(byte[] val) { publicSeed = XMSSUtil.cloneArray(val); return this; } public Builder withRoot(byte[] val) { root = XMSSUtil.cloneArray(val); return this; } public Builder withBDSState(BDS valBDS) { bdsState = valBDS; return this; } public Builder withPrivateKey(byte[] privateKeyVal, XMSSParameters xmssParameters) { privateKey = XMSSUtil.cloneArray(privateKeyVal); xmss = xmssParameters; return this; } public XMSSPrivateKeyParameters build() { return new XMSSPrivateKeyParameters(this); } } public byte[] toByteArray() { /* index || secretKeySeed || secretKeyPRF || publicSeed || root */ int n = params.getDigestSize(); int indexSize = 4; int secretKeySize = n; int secretKeyPRFSize = n; int publicSeedSize = n; int rootSize = n; int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize; byte[] out = new byte[totalSize]; int position = 0; /* copy index */ Pack.intToBigEndian(bdsState.getIndex(), out, position); position += indexSize; /* copy secretKeySeed */ XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position); position += secretKeySize; /* copy secretKeyPRF */ XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position); position += secretKeyPRFSize; /* copy publicSeed */ XMSSUtil.copyBytesAtOffset(out, publicSeed, position); position += publicSeedSize; /* copy root */ XMSSUtil.copyBytesAtOffset(out, root, position); /* concatenate bdsState */ byte[] bdsStateOut = null; try { bdsStateOut = XMSSUtil.serialize(bdsState); } catch (IOException e) { throw new RuntimeException("error serializing bds state: " + e.getMessage()); } return Arrays.concatenate(out, bdsStateOut); } public int getIndex() { return bdsState.getIndex(); } public byte[] getSecretKeySeed() { return XMSSUtil.cloneArray(secretKeySeed); } public byte[] getSecretKeyPRF() { return XMSSUtil.cloneArray(secretKeyPRF); } public byte[] getPublicSeed() { return XMSSUtil.cloneArray(publicSeed); } public byte[] getRoot() { return XMSSUtil.cloneArray(root); } BDS getBDSState() { return bdsState; } public XMSSParameters getParameters() { return params; } public XMSSPrivateKeyParameters getNextKey() { /* prepare authentication path for next leaf */ int treeHeight = this.params.getHeight(); if (this.getIndex() < ((1 << treeHeight) - 1)) { return new XMSSPrivateKeyParameters.Builder(params) .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF) .withPublicSeed(publicSeed).withRoot(root) .withBDSState(bdsState.getNextState(publicSeed, secretKeySeed, (OTSHashAddress)new OTSHashAddress.Builder().build())).build(); } else { return new XMSSPrivateKeyParameters.Builder(params) .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF) .withPublicSeed(publicSeed).withRoot(root) .withBDSState(new BDS(params, getIndex() + 1)).build(); // no more nodes left. } } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_42_3
crossvul-java_data_bad_5761_2
404: Not Found
./CrossVul/dataset_final_sorted/CWE-502/java/bad_5761_2
crossvul-java_data_good_449_1
package com.fasterxml.jackson.databind.jsontype.impl; import java.util.Collections; import java.util.HashSet; import java.util.Set; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonMappingException; /** * Helper class used to encapsulate rules that determine subtypes that * are invalid to use, even with default typing, mostly due to security * concerns. * Used by <code>BeanDeserializerFacotry</code> * * @since 2.8.11 */ public class SubTypeValidator { protected final static String PREFIX_SPRING = "org.springframework."; protected final static String PREFIX_C3P0 = "com.mchange.v2.c3p0."; /** * Set of well-known "nasty classes", deserialization of which is considered dangerous * and should (and is) prevented by default. */ protected final static Set<String> DEFAULT_NO_DESER_CLASS_NAMES; static { Set<String> s = new HashSet<String>(); // Courtesy of [https://github.com/kantega/notsoserial]: // (and wrt [databind#1599]) s.add("org.apache.commons.collections.functors.InvokerTransformer"); s.add("org.apache.commons.collections.functors.InstantiateTransformer"); s.add("org.apache.commons.collections4.functors.InvokerTransformer"); s.add("org.apache.commons.collections4.functors.InstantiateTransformer"); s.add("org.codehaus.groovy.runtime.ConvertedClosure"); s.add("org.codehaus.groovy.runtime.MethodClosure"); s.add("org.springframework.beans.factory.ObjectFactory"); s.add("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl"); s.add("org.apache.xalan.xsltc.trax.TemplatesImpl"); // [databind#1680]: may or may not be problem, take no chance s.add("com.sun.rowset.JdbcRowSetImpl"); // [databind#1737]; JDK provided s.add("java.util.logging.FileHandler"); s.add("java.rmi.server.UnicastRemoteObject"); // [databind#1737]; 3rd party //s.add("org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor"); // deprecated by [databind#1855] s.add("org.springframework.beans.factory.config.PropertyPathFactoryBean"); // s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource"); // deprecated by [databind#1931] // s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource"); // - "" - // [databind#1855]: more 3rd party s.add("org.apache.tomcat.dbcp.dbcp2.BasicDataSource"); s.add("com.sun.org.apache.bcel.internal.util.ClassLoader"); // [databind#2032]: more 3rd party; data exfiltration via xml parsed ext entities s.add("org.apache.ibatis.parsing.XPathParser"); // [databind#2052]: Jodd-db, with jndi/ldap lookup s.add("jodd.db.connection.DataSourceConnectionProvider"); // [databind#2058]: Oracle JDBC driver, with jndi/ldap lookup s.add("oracle.jdbc.connector.OracleManagedConnectionFactory"); s.add("oracle.jdbc.rowset.OracleJDBCRowSet"); // [databind#1899]: more 3rd party s.add("org.hibernate.jmx.StatisticsService"); s.add("org.apache.ibatis.datasource.jndi.JndiDataSourceFactory"); // [databind#2097]: some 3rd party, one JDK-bundled s.add("org.slf4j.ext.EventData"); s.add("flex.messaging.util.concurrent.AsynchBeansWorkManagerExecutor"); s.add("com.sun.deploy.security.ruleset.DRSHelper"); s.add("org.apache.axis2.jaxws.spi.handler.HandlerResolverImpl"); // [databind#2186]: yet more 3rd party gadgets s.add("org.jboss.util.propertyeditor.DocumentEditor"); s.add("org.apache.openjpa.ee.RegistryManagedRuntime"); s.add("org.apache.openjpa.ee.JNDIManagedRuntime"); s.add("org.apache.axis2.transport.jms.JMSOutTransportInfo"); DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s); } /** * Set of class names of types that are never to be deserialized. */ protected Set<String> _cfgIllegalClassNames = DEFAULT_NO_DESER_CLASS_NAMES; private final static SubTypeValidator instance = new SubTypeValidator(); protected SubTypeValidator() { } public static SubTypeValidator instance() { return instance; } public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException { // There are certain nasty classes that could cause problems, mostly // via default typing -- catch them here. final Class<?> raw = type.getRawClass(); String full = raw.getName(); main_check: do { if (_cfgIllegalClassNames.contains(full)) { break; } // 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling // for some Spring framework types // 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces if (raw.isInterface()) { ; } else if (full.startsWith(PREFIX_SPRING)) { for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()){ String name = cls.getSimpleName(); // looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there? if ("AbstractPointcutAdvisor".equals(name) // ditto for "FileSystemXmlApplicationContext": block all ApplicationContexts || "AbstractApplicationContext".equals(name)) { break main_check; } } } else if (full.startsWith(PREFIX_C3P0)) { // [databind#1737]; more 3rd party // s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource"); // s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource"); // [databind#1931]; more 3rd party // com.mchange.v2.c3p0.ComboPooledDataSource // com.mchange.v2.c3p0.debug.AfterCloseLoggingComboPooledDataSource if (full.endsWith("DataSource")) { break main_check; } } return; } while (false); throw JsonMappingException.from(ctxt, String.format("Illegal type (%s) to deserialize: prevented for security reasons", full)); } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_449_1
crossvul-java_data_bad_3054_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-502/java/bad_3054_1
crossvul-java_data_good_42_2
package org.bouncycastle.pqc.crypto.xmss; import java.io.IOException; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.util.Arrays; /** * XMSS^MT Private Key. */ public final class XMSSMTPrivateKeyParameters extends AsymmetricKeyParameter implements XMSSStoreableObjectInterface { private final XMSSMTParameters params; private final long index; private final byte[] secretKeySeed; private final byte[] secretKeyPRF; private final byte[] publicSeed; private final byte[] root; private final BDSStateMap bdsState; private XMSSMTPrivateKeyParameters(Builder builder) { super(true); params = builder.params; if (params == null) { throw new NullPointerException("params == null"); } int n = params.getDigestSize(); byte[] privateKey = builder.privateKey; if (privateKey != null) { if (builder.xmss == null) { throw new NullPointerException("xmss == null"); } /* import */ int totalHeight = params.getHeight(); int indexSize = (totalHeight + 7) / 8; int secretKeySize = n; int secretKeyPRFSize = n; int publicSeedSize = n; int rootSize = n; /* int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize; if (privateKey.length != totalSize) { throw new ParseException("private key has wrong size", 0); } */ int position = 0; index = XMSSUtil.bytesToXBigEndian(privateKey, position, indexSize); if (!XMSSUtil.isIndexValid(totalHeight, index)) { throw new IllegalArgumentException("index out of bounds"); } position += indexSize; secretKeySeed = XMSSUtil.extractBytesAtOffset(privateKey, position, secretKeySize); position += secretKeySize; secretKeyPRF = XMSSUtil.extractBytesAtOffset(privateKey, position, secretKeyPRFSize); position += secretKeyPRFSize; publicSeed = XMSSUtil.extractBytesAtOffset(privateKey, position, publicSeedSize); position += publicSeedSize; root = XMSSUtil.extractBytesAtOffset(privateKey, position, rootSize); position += rootSize; /* import BDS state */ byte[] bdsStateBinary = XMSSUtil.extractBytesAtOffset(privateKey, position, privateKey.length - position); try { BDSStateMap bdsImport = (BDSStateMap)XMSSUtil.deserialize(bdsStateBinary, BDSStateMap.class); bdsImport.setXMSS(builder.xmss); bdsState = bdsImport; } catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e.getMessage(), e); } } else { /* set */ index = builder.index; byte[] tmpSecretKeySeed = builder.secretKeySeed; if (tmpSecretKeySeed != null) { if (tmpSecretKeySeed.length != n) { throw new IllegalArgumentException("size of secretKeySeed needs to be equal size of digest"); } secretKeySeed = tmpSecretKeySeed; } else { secretKeySeed = new byte[n]; } byte[] tmpSecretKeyPRF = builder.secretKeyPRF; if (tmpSecretKeyPRF != null) { if (tmpSecretKeyPRF.length != n) { throw new IllegalArgumentException("size of secretKeyPRF needs to be equal size of digest"); } secretKeyPRF = tmpSecretKeyPRF; } else { secretKeyPRF = new byte[n]; } byte[] tmpPublicSeed = builder.publicSeed; if (tmpPublicSeed != null) { if (tmpPublicSeed.length != n) { throw new IllegalArgumentException("size of publicSeed needs to be equal size of digest"); } publicSeed = tmpPublicSeed; } else { publicSeed = new byte[n]; } byte[] tmpRoot = builder.root; if (tmpRoot != null) { if (tmpRoot.length != n) { throw new IllegalArgumentException("size of root needs to be equal size of digest"); } root = tmpRoot; } else { root = new byte[n]; } BDSStateMap tmpBDSState = builder.bdsState; if (tmpBDSState != null) { bdsState = tmpBDSState; } else { long globalIndex = builder.index; int totalHeight = params.getHeight(); if (XMSSUtil.isIndexValid(totalHeight, globalIndex) && tmpPublicSeed != null && tmpSecretKeySeed != null) { bdsState = new BDSStateMap(params, builder.index, tmpPublicSeed, tmpSecretKeySeed); } else { bdsState = new BDSStateMap(); } } } } public static class Builder { /* mandatory */ private final XMSSMTParameters params; /* optional */ private long index = 0L; private byte[] secretKeySeed = null; private byte[] secretKeyPRF = null; private byte[] publicSeed = null; private byte[] root = null; private BDSStateMap bdsState = null; private byte[] privateKey = null; private XMSSParameters xmss = null; public Builder(XMSSMTParameters params) { super(); this.params = params; } public Builder withIndex(long val) { index = val; return this; } public Builder withSecretKeySeed(byte[] val) { secretKeySeed = XMSSUtil.cloneArray(val); return this; } public Builder withSecretKeyPRF(byte[] val) { secretKeyPRF = XMSSUtil.cloneArray(val); return this; } public Builder withPublicSeed(byte[] val) { publicSeed = XMSSUtil.cloneArray(val); return this; } public Builder withRoot(byte[] val) { root = XMSSUtil.cloneArray(val); return this; } public Builder withBDSState(BDSStateMap val) { bdsState = val; return this; } public Builder withPrivateKey(byte[] privateKeyVal, XMSSParameters xmssVal) { privateKey = XMSSUtil.cloneArray(privateKeyVal); xmss = xmssVal; return this; } public XMSSMTPrivateKeyParameters build() { return new XMSSMTPrivateKeyParameters(this); } } public byte[] toByteArray() { /* index || secretKeySeed || secretKeyPRF || publicSeed || root */ int n = params.getDigestSize(); int indexSize = (params.getHeight() + 7) / 8; int secretKeySize = n; int secretKeyPRFSize = n; int publicSeedSize = n; int rootSize = n; int totalSize = indexSize + secretKeySize + secretKeyPRFSize + publicSeedSize + rootSize; byte[] out = new byte[totalSize]; int position = 0; /* copy index */ byte[] indexBytes = XMSSUtil.toBytesBigEndian(index, indexSize); XMSSUtil.copyBytesAtOffset(out, indexBytes, position); position += indexSize; /* copy secretKeySeed */ XMSSUtil.copyBytesAtOffset(out, secretKeySeed, position); position += secretKeySize; /* copy secretKeyPRF */ XMSSUtil.copyBytesAtOffset(out, secretKeyPRF, position); position += secretKeyPRFSize; /* copy publicSeed */ XMSSUtil.copyBytesAtOffset(out, publicSeed, position); position += publicSeedSize; /* copy root */ XMSSUtil.copyBytesAtOffset(out, root, position); /* concatenate bdsState */ try { return Arrays.concatenate(out, XMSSUtil.serialize(bdsState)); } catch (IOException e) { throw new IllegalStateException("error serializing bds state: " + e.getMessage(), e); } } public long getIndex() { return index; } public byte[] getSecretKeySeed() { return XMSSUtil.cloneArray(secretKeySeed); } public byte[] getSecretKeyPRF() { return XMSSUtil.cloneArray(secretKeyPRF); } public byte[] getPublicSeed() { return XMSSUtil.cloneArray(publicSeed); } public byte[] getRoot() { return XMSSUtil.cloneArray(root); } BDSStateMap getBDSState() { return bdsState; } public XMSSMTParameters getParameters() { return params; } public XMSSMTPrivateKeyParameters getNextKey() { BDSStateMap newState = new BDSStateMap(bdsState, params, this.getIndex(), publicSeed, secretKeySeed); return new XMSSMTPrivateKeyParameters.Builder(params).withIndex(index + 1) .withSecretKeySeed(secretKeySeed).withSecretKeyPRF(secretKeyPRF) .withPublicSeed(publicSeed).withRoot(root) .withBDSState(newState).build(); } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_42_2
crossvul-java_data_good_5761_6
package org.richfaces.demo.paint2d; import org.ajax4jsf.resource.SerializableResource; public class PaintData implements SerializableResource { /** * */ private static final long serialVersionUID = 1L; String text; Integer color; float scale; public Integer getColor() { return color; } public void setColor(Integer color) { this.color = color; } public float getScale() { return scale; } public void setScale(float scale) { this.scale = scale; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_5761_6
crossvul-java_data_good_42_4
package org.bouncycastle.pqc.crypto.xmss; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.bouncycastle.crypto.Digest; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; /** * Utils for XMSS implementation. */ public class XMSSUtil { /** * Calculates the logarithm base 2 for a given Integer. * * @param n Number. * @return Logarithm to base 2 of {@code n}. */ public static int log2(int n) { int log = 0; while ((n >>= 1) != 0) { log++; } return log; } /** * Convert int/long to n-byte array. * * @param value int/long value. * @param sizeInByte Size of byte array in byte. * @return int/long as big-endian byte array of size {@code sizeInByte}. */ public static byte[] toBytesBigEndian(long value, int sizeInByte) { byte[] out = new byte[sizeInByte]; for (int i = (sizeInByte - 1); i >= 0; i--) { out[i] = (byte)value; value >>>= 8; } return out; } /* * Copy long to byte array in big-endian at specific offset. */ public static void longToBigEndian(long value, byte[] in, int offset) { if (in == null) { throw new NullPointerException("in == null"); } if ((in.length - offset) < 8) { throw new IllegalArgumentException("not enough space in array"); } in[offset] = (byte)((value >> 56) & 0xff); in[offset + 1] = (byte)((value >> 48) & 0xff); in[offset + 2] = (byte)((value >> 40) & 0xff); in[offset + 3] = (byte)((value >> 32) & 0xff); in[offset + 4] = (byte)((value >> 24) & 0xff); in[offset + 5] = (byte)((value >> 16) & 0xff); in[offset + 6] = (byte)((value >> 8) & 0xff); in[offset + 7] = (byte)((value) & 0xff); } /* * Generic convert from big endian byte array to long. */ public static long bytesToXBigEndian(byte[] in, int offset, int size) { if (in == null) { throw new NullPointerException("in == null"); } long res = 0; for (int i = offset; i < (offset + size); i++) { res = (res << 8) | (in[i] & 0xff); } return res; } /** * Clone a byte array. * * @param in byte array. * @return Copy of byte array. */ public static byte[] cloneArray(byte[] in) { if (in == null) { throw new NullPointerException("in == null"); } byte[] out = new byte[in.length]; for (int i = 0; i < in.length; i++) { out[i] = in[i]; } return out; } /** * Clone a 2d byte array. * * @param in 2d byte array. * @return Copy of 2d byte array. */ public static byte[][] cloneArray(byte[][] in) { if (hasNullPointer(in)) { throw new NullPointerException("in has null pointers"); } byte[][] out = new byte[in.length][]; for (int i = 0; i < in.length; i++) { out[i] = new byte[in[i].length]; for (int j = 0; j < in[i].length; j++) { out[i][j] = in[i][j]; } } return out; } /** * Compares two 2d-byte arrays. * * @param a 2d-byte array 1. * @param b 2d-byte array 2. * @return true if all values in 2d-byte array are equal false else. */ public static boolean areEqual(byte[][] a, byte[][] b) { if (hasNullPointer(a) || hasNullPointer(b)) { throw new NullPointerException("a or b == null"); } for (int i = 0; i < a.length; i++) { if (!Arrays.areEqual(a[i], b[i])) { return false; } } return true; } /** * Dump content of 2d byte array. * * @param x byte array. */ public static void dumpByteArray(byte[][] x) { if (hasNullPointer(x)) { throw new NullPointerException("x has null pointers"); } for (int i = 0; i < x.length; i++) { System.out.println(Hex.toHexString(x[i])); } } /** * Checks whether 2d byte array has null pointers. * * @param in 2d byte array. * @return true if at least one null pointer is found false else. */ public static boolean hasNullPointer(byte[][] in) { if (in == null) { return true; } for (int i = 0; i < in.length; i++) { if (in[i] == null) { return true; } } return false; } /** * Copy src byte array to dst byte array at offset. * * @param dst Destination. * @param src Source. * @param offset Destination offset. */ public static void copyBytesAtOffset(byte[] dst, byte[] src, int offset) { if (dst == null) { throw new NullPointerException("dst == null"); } if (src == null) { throw new NullPointerException("src == null"); } if (offset < 0) { throw new IllegalArgumentException("offset hast to be >= 0"); } if ((src.length + offset) > dst.length) { throw new IllegalArgumentException("src length + offset must not be greater than size of destination"); } for (int i = 0; i < src.length; i++) { dst[offset + i] = src[i]; } } /** * Copy length bytes at position offset from src. * * @param src Source byte array. * @param offset Offset in source byte array. * @param length Length of bytes to copy. * @return New byte array. */ public static byte[] extractBytesAtOffset(byte[] src, int offset, int length) { if (src == null) { throw new NullPointerException("src == null"); } if (offset < 0) { throw new IllegalArgumentException("offset hast to be >= 0"); } if (length < 0) { throw new IllegalArgumentException("length hast to be >= 0"); } if ((offset + length) > src.length) { throw new IllegalArgumentException("offset + length must not be greater then size of source array"); } byte[] out = new byte[length]; for (int i = 0; i < out.length; i++) { out[i] = src[offset + i]; } return out; } /** * Check whether an index is valid or not. * * @param height Height of binary tree. * @param index Index to validate. * @return true if index is valid false else. */ public static boolean isIndexValid(int height, long index) { if (index < 0) { throw new IllegalStateException("index must not be negative"); } return index < (1L << height); } /** * Determine digest size of digest. * * @param digest Digest. * @return Digest size. */ public static int getDigestSize(Digest digest) { if (digest == null) { throw new NullPointerException("digest == null"); } String algorithmName = digest.getAlgorithmName(); if (algorithmName.equals("SHAKE128")) { return 32; } if (algorithmName.equals("SHAKE256")) { return 64; } return digest.getDigestSize(); } public static long getTreeIndex(long index, int xmssTreeHeight) { return index >> xmssTreeHeight; } public static int getLeafIndex(long index, int xmssTreeHeight) { return (int)(index & ((1L << xmssTreeHeight) - 1L)); } public static byte[] serialize(Object obj) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(obj); oos.flush(); return out.toByteArray(); } public static Object deserialize(byte[] data, Class clazz) throws IOException, ClassNotFoundException { ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new ObjectInputStream(in); Object obj = is.readObject(); if (is.available() != 0) { throw new IOException("unexpected data found at end of ObjectInputStream"); } if (clazz.isInstance(obj)) { return obj; } else { throw new IOException("unexpected class found in ObjectInputStream"); } } public static int calculateTau(int index, int height) { int tau = 0; for (int i = 0; i < height; i++) { if (((index >> i) & 1) == 0) { tau = i; break; } } return tau; } public static boolean isNewBDSInitNeeded(long globalIndex, int xmssHeight, int layer) { if (globalIndex == 0) { return false; } return (globalIndex % (long)Math.pow((1 << xmssHeight), layer + 1) == 0) ? true : false; } public static boolean isNewAuthenticationPathNeeded(long globalIndex, int xmssHeight, int layer) { if (globalIndex == 0) { return false; } return ((globalIndex + 1) % (long)Math.pow((1 << xmssHeight), layer) == 0) ? true : false; } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_42_4
crossvul-java_data_good_5761_1
/** * License Agreement. * * Rich Faces - Natural Ajax for Java Server Faces (JSF) * * Copyright (C) 2007 Exadel, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.ajax4jsf.resource; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.Deflater; import java.util.zip.Inflater; import javax.faces.FacesException; import javax.faces.context.FacesContext; import javax.imageio.ImageIO; import javax.servlet.ServletContext; import org.ajax4jsf.Messages; import org.ajax4jsf.resource.util.URLToStreamHelper; import org.ajax4jsf.util.base64.Codec; import org.ajax4jsf.webapp.WebXml; import org.apache.commons.digester.Digester; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Produce instances of InternetResource's for any types - jar resource, dynamic * created image, component-incapsulated etc. Realised as singleton class to * support cache, configuration etc. * * @author shura (latest modification by $Author: alexsmirnov $) * @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:56:58 $ * */ public class ResourceBuilderImpl extends InternetResourceBuilder { private static final Log log = LogFactory.getLog(ResourceBuilderImpl.class); private static final String DATA_SEPARATOR = "/DATA/"; private static final String DATA_BYTES_SEPARATOR = "/DATB/"; private static final Pattern DATA_SEPARATOR_PATTERN = Pattern .compile("/DAT(A|B)/"); private static final ResourceRenderer defaultRenderer = new MimeRenderer(null); private Map<String, ResourceRenderer> renderers; /** * keep resources instances . TODO - put this map to application-scope * attribute, for support clastering environment. */ private Map<String, InternetResource> resources = Collections.synchronizedMap(new HashMap<String, InternetResource>()); private long _startTime; private Codec codec; private static final ResourceRenderer scriptRenderer = new ScriptRenderer(); private static final ResourceRenderer styleRenderer = new StyleRenderer(); static { // renderers.put(".htc",new BehaviorRenderer()); // set in-memory caching ImageIO Thread thread = Thread.currentThread(); ClassLoader initialTCCL = thread.getContextClassLoader(); try { ClassLoader systemCL = ClassLoader.getSystemClassLoader(); thread.setContextClassLoader(systemCL); ImageIO.setUseCache(false); } finally { thread.setContextClassLoader(initialTCCL); } } public WebXml getWebXml(FacesContext context) { WebXml webXml = WebXml.getInstance(context); if (null == webXml) { throw new FacesException( "Resources framework is not initialised, check web.xml for Filter configuration"); } return webXml; } public ResourceBuilderImpl() { super(); _startTime = System.currentTimeMillis(); codec = new Codec(); renderers = new HashMap<String, ResourceRenderer>(); // append known renderers for extentions. renderers.put(".gif", new GifRenderer()); ResourceRenderer renderer = new JpegRenderer(); renderers.put(".jpeg", renderer); renderers.put(".jpg", renderer); renderers.put(".png", new PngRenderer()); renderers.put(".js", getScriptRenderer()); renderers.put(".css", getStyleRenderer()); renderers.put(".log", new LogfileRenderer()); renderers.put(".html", new HTMLRenderer()); renderers.put(".xhtml", new MimeRenderer("application/xhtml+xml")); renderers.put(".xml", new MimeRenderer("text/xml")); renderers.put(".xcss", new TemplateCSSRenderer()); renderers.put(".swf", new MimeRenderer("application/x-shockwave-flash")); } /** * @throws FacesException */ protected void registerResources() throws FacesException { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> e = loader .getResources("META-INF/resources-config.xml"); while (e.hasMoreElements()) { URL resource = e.nextElement(); registerConfig(resource); } } catch (IOException e) { throw new FacesException(e); } } private void registerConfig(URL resourceConfig) { try { if (log.isDebugEnabled()) { log.debug("Process resources configuration file " + resourceConfig.toExternalForm()); } InputStream in = URLToStreamHelper.urlToStream(resourceConfig); try { Digester digester = new Digester(); digester.setValidating(false); digester.setEntityResolver(new EntityResolver() { // Dummi resolver - alvays do nothing public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } }); digester.setNamespaceAware(false); digester.setUseContextClassLoader(true); digester.push(this); digester.addObjectCreate("resource-config/resource", "class", JarResource.class); digester.addObjectCreate("resource-config/resource/renderer", "class", HTMLRenderer.class); digester.addCallMethod( "resource-config/resource/renderer/content-type", "setContentType", 0); digester.addSetNext("resource-config/resource/renderer", "setRenderer", ResourceRenderer.class.getName()); digester.addCallMethod("resource-config/resource/name", "setKey", 0); digester.addCallMethod("resource-config/resource/path", "setPath", 0); digester.addCallMethod("resource-config/resource/cacheable", "setCacheable", 0); digester.addCallMethod( "resource-config/resource/session-aware", "setSessionAware", 0); digester.addCallMethod("resource-config/resource/property", "setProperty", 2); digester.addCallParam("resource-config/resource/property/name", 0); digester.addCallParam( "resource-config/resource/property/value", 1); digester.addCallMethod("resource-config/resource/content-type", "setContentType", 0); digester.addSetNext("resource-config/resource", "addResource", InternetResource.class.getName()); digester.parse(in); } finally { in.close(); } } catch (IOException e) { throw new FacesException(e); } catch (SAXException e) { throw new FacesException(e); } } /** */ public void init() throws FacesException { // TODO - mace codec configurable. registerResources(); } /** * Base point for creating resource. Must detect type and build appropriate * instance. Currently - make static resource for ordinary request, or * instance of class. * * @param base * base object for resource ( resourcess in classpath will be get * relative to it package ) * @param path * key - path to resource, resource class name etc. * @return * @throws FacesException */ public InternetResource createResource(Object base, String path) throws FacesException { // TODO - detect type of resource ( for example, resources location path // in Skin try { return getResource(path); } catch (ResourceNotFoundException e) { try { return getResource(buildKey(base, path)); } catch (ResourceNotFoundException e1) { if (log.isDebugEnabled()) { log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_INFO, path)); } } } // path - is class name ? InternetResource res; try { Class<?> resourceClass = Class.forName(path); res = createDynamicResource(path, resourceClass); } catch (Exception e) { try { res = createJarResource(base, path); } catch (ResourceNotFoundException ex) { res = createStaticResource(path); } // TODO - if resource not found, create static ? } return res; } private String buildKey(Object base, String path) { if (path.startsWith("/")) { return path.substring(1); } if (null == base) { return path; } StringBuffer packageName = new StringBuffer(base.getClass() .getPackage().getName().replace('.', '/')); return packageName.append("/").append(path).toString(); } public String getUri(InternetResource resource, FacesContext context, Object storeData) { StringBuffer uri = new StringBuffer();// ResourceServlet.DEFAULT_SERVLET_PATH).append("/"); uri.append(resource.getKey()); // append serialized data as Base-64 encoded request string. if (storeData != null) { try { byte[] objectData; if (storeData instanceof byte[]) { objectData = (byte[]) storeData; uri.append(DATA_BYTES_SEPARATOR); } else { ByteArrayOutputStream dataSteram = new ByteArrayOutputStream( 1024); ObjectOutputStream objStream = new ObjectOutputStream( dataSteram); objStream.writeObject(storeData); objStream.flush(); objStream.close(); dataSteram.close(); objectData = dataSteram.toByteArray(); uri.append(DATA_SEPARATOR); } byte[] dataArray = encrypt(objectData); uri.append(new String(dataArray, "ISO-8859-1")); // / byte[] objectData = dataSteram.toByteArray(); // / uri.append("?").append(new // String(Base64.encodeBase64(objectData), // / "ISO-8859-1")); } catch (Exception e) { // Ignore errors, log it log.error(Messages .getMessage(Messages.QUERY_STRING_BUILDING_ERROR), e); } } boolean isGlobal = !resource.isSessionAware(); String resourceURL = getWebXml(context).getFacesResourceURL(context, uri.toString(), isGlobal);// context.getApplication().getViewHandler().getResourceURL(context,uri.toString()); if (!isGlobal) { resourceURL = context.getExternalContext().encodeResourceURL( resourceURL); } if (log.isDebugEnabled()) { log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO, resource.getKey(), resourceURL)); } return resourceURL;// context.getExternalContext().encodeResourceURL(resourceURL); } /** * @param key * @return */ public InternetResource getResourceForKey(String key) throws ResourceNotFoundException { Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(key); if (matcher.find()) { int data = matcher.start(); key = key.substring(0, data); } return getResource(key); } public Object getResourceDataForKey(String key) { Object data = null; String dataString = null; Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(key); if (matcher.find()) { if (log.isDebugEnabled()) { log.debug(Messages.getMessage( Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, key, dataString)); } int dataStart = matcher.end(); dataString = key.substring(dataStart); byte[] objectArray = null; byte[] dataArray; try { dataArray = dataString.getBytes("ISO-8859-1"); objectArray = decrypt(dataArray); } catch (UnsupportedEncodingException e1) { // default encoding always presented. } if ("B".equals(matcher.group(1))) { data = objectArray; } else { try { ObjectInputStream in = new LookAheadObjectInputStream(new ByteArrayInputStream(objectArray)); data = in.readObject(); } catch (StreamCorruptedException e) { log.error(Messages .getMessage(Messages.STREAM_CORRUPTED_ERROR), e); } catch (IOException e) { log.error(Messages .getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR), e); } catch (ClassNotFoundException e) { log .error( Messages .getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR), e); } } } return data; } public InternetResource getResource(String path) throws ResourceNotFoundException { InternetResource internetResource = (InternetResource) resources .get(path); if (null == internetResource) { throw new ResourceNotFoundException("Resource not registered : " + path); } else { return internetResource; } } public void addResource(InternetResource resource) { resources.put(resource.getKey(), resource); ResourceRenderer renderer = resource.getRenderer(null); if (renderer == null) { setRenderer(resource, resource.getKey()); } } public void addResource(String key, InternetResource resource) { resources.put(key, resource); resource.setKey(key); // TODO - set renderer ? } // public String getFacesResourceKey(HttpServletRequest request) { // return getWebXml(context).getFacesResourceKey(request); // } public String getFacesResourceURL(FacesContext context, String Url, boolean isGlobal) { return getWebXml(context).getFacesResourceURL(context, Url, isGlobal); } /** * Build resource for link to static context in webapp. * * @param path * @return * @throws FacesException */ protected InternetResource createStaticResource(String path) throws ResourceNotFoundException, FacesException { FacesContext context = FacesContext.getCurrentInstance(); if (null != context) { if (context.getExternalContext().getContext() instanceof ServletContext) { ServletContext servletContext = (ServletContext) context .getExternalContext().getContext(); InputStream in = servletContext.getResourceAsStream(path); if (null != in) { InternetResourceBase res = new StaticResource(path); setRenderer(res, path); res.setLastModified(new Date(getStartTime())); addResource(path, res); try { in.close(); } catch (IOException e) { } return res; } } } throw new ResourceNotFoundException(Messages.getMessage( Messages.STATIC_RESOURCE_NOT_FOUND_ERROR, path)); } private void setRenderer(InternetResource res, String path) throws FacesException { int lastPoint = path.lastIndexOf('.'); if (lastPoint > 0) { String ext = path.substring(lastPoint); ResourceRenderer resourceRenderer = getRendererByExtension(ext); if (null != resourceRenderer) { res.setRenderer(resourceRenderer); } else { if (log.isDebugEnabled()) { log.debug(Messages.getMessage( Messages.NO_RESOURCE_REGISTERED_ERROR_2, path, renderers.keySet())); } // String mimeType = servletContext.getMimeType(path); res.setRenderer(defaultRenderer); } } } /** * @param ext * @return */ protected ResourceRenderer getRendererByExtension(String ext) { return renderers .get(ext); } /** * Create resurce to send from classpath relative to base class. * * @param base * @param path * @return * @throws FacesException */ protected InternetResource createJarResource(Object base, String path) throws ResourceNotFoundException, FacesException { String key = buildKey(base, path); ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (null != loader.getResource(key)) { JarResource res = new JarResource(key); setRenderer(res, path); res.setLastModified(new Date(getStartTime())); addResource(key, res); return res; } else { throw new ResourceNotFoundException(Messages.getMessage( Messages.NO_RESOURCE_EXISTS_ERROR, key)); } } /** * Create resource by instatiate given class. * * @param path * @param instatiate * @return */ protected InternetResource createDynamicResource(String path, Class<?> instatiate) throws ResourceNotFoundException { if (InternetResource.class.isAssignableFrom(instatiate)) { InternetResource resource; try { resource = (InternetResource) instatiate.newInstance(); addResource(path, resource); } catch (Exception e) { String message = Messages.getMessage( Messages.INSTANTIATE_RESOURCE_ERROR, instatiate .toString()); log.error(message, e); throw new ResourceNotFoundException(message, e); } return resource; } throw new FacesException(Messages .getMessage(Messages.INSTANTIATE_CLASS_ERROR)); } /** * Create resource by instatiate {@link UserResource} class with given * properties ( or got from cache ). * * @param cacheable * @param session * @param mime * @return * @throws FacesException */ public InternetResource createUserResource(boolean cacheable, boolean session, String mime) throws FacesException { String path = getUserResourceKey(cacheable, session, mime); InternetResource userResource; try { userResource = getResource(path); } catch (ResourceNotFoundException e) { userResource = new UserResource(cacheable, session, mime); addResource(path, userResource); } return userResource; } /** * Generate resource key for user-generated resource with given properties. * * @param cacheable * @param session * @param mime * @return */ private String getUserResourceKey(boolean cacheable, boolean session, String mime) { StringBuffer pathBuffer = new StringBuffer(UserResource.class.getName()); pathBuffer.append(cacheable ? "/c" : "/n"); pathBuffer.append(session ? "/s" : "/n"); if (null != mime) { pathBuffer.append('/').append(mime.hashCode()); } String path = pathBuffer.toString(); return path; } /** * @return Returns the startTime for application. */ public long getStartTime() { return _startTime; } protected byte[] encrypt(byte[] src) { try { Deflater compressor = new Deflater(Deflater.BEST_SPEED); byte[] compressed = new byte[src.length + 100]; compressor.setInput(src); compressor.finish(); int totalOut = compressor.deflate(compressed); byte[] zipsrc = new byte[totalOut]; System.arraycopy(compressed, 0, zipsrc, 0, totalOut); compressor.end(); return codec.encode(zipsrc); } catch (Exception e) { throw new FacesException("Error encode resource data", e); } } protected byte[] decrypt(byte[] src) { try { byte[] zipsrc = codec.decode(src); Inflater decompressor = new Inflater(); byte[] uncompressed = new byte[zipsrc.length * 5]; decompressor.setInput(zipsrc); int totalOut = decompressor.inflate(uncompressed); byte[] out = new byte[totalOut]; System.arraycopy(uncompressed, 0, out, 0, totalOut); decompressor.end(); return out; } catch (Exception e) { throw new FacesException("Error decode resource data", e); } } @Override public ResourceRenderer getScriptRenderer() { return scriptRenderer; } @Override public ResourceRenderer getStyleRenderer() { return styleRenderer; } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_5761_1
crossvul-java_data_good_590_2
/* * Copyright 2013-present Facebook, 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.facebook.buck.parser; import com.facebook.buck.parser.thrift.RemoteDaemonicParserState; import java.io.IOException; import java.io.InputStream; import java.io.InvalidClassException; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.util.HashSet; import java.util.Set; /** A ObjectInputStream that will deserialize only RemoteDaemonicParserState. */ public class ParserStateObjectInputStream extends ObjectInputStream { private Set<String> whitelist; public ParserStateObjectInputStream(InputStream inputStream) throws IOException { super(inputStream); whitelist = new HashSet<>(); whitelist.add(RemoteDaemonicParserState.class.getName()); } @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (!whitelist.contains(desc.getName())) { throw new InvalidClassException(desc.getName(), "Can't deserialize this class"); } return super.resolveClass(desc); } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_590_2
crossvul-java_data_good_42_1
package org.bouncycastle.pqc.crypto.rainbow; import org.bouncycastle.crypto.CipherParameters; public class RainbowParameters implements CipherParameters { /** * DEFAULT PARAMS */ /* * Vi = vinegars per layer whereas n is vu (vu = 33 = n) such that * * v1 = 6; o1 = 12-6 = 6 * * v2 = 12; o2 = 17-12 = 5 * * v3 = 17; o3 = 22-17 = 5 * * v4 = 22; o4 = 33-22 = 11 * * v5 = 33; (o5 = 0) */ private final int[] DEFAULT_VI = {6, 12, 17, 22, 33}; private int[] vi;// set of vinegar vars per layer. /** * Default Constructor The elements of the array containing the number of * Vinegar variables in each layer are set to the default values here. */ public RainbowParameters() { this.vi = this.DEFAULT_VI; } /** * Constructor with parameters * * @param vi The elements of the array containing the number of Vinegar * variables per layer are set to the values of the input array. */ public RainbowParameters(int[] vi) { this.vi = vi; checkParams(); } private void checkParams() { if (vi == null) { throw new IllegalArgumentException("no layers defined."); } if (vi.length > 1) { for (int i = 0; i < vi.length - 1; i++) { if (vi[i] >= vi[i + 1]) { throw new IllegalArgumentException( "v[i] has to be smaller than v[i+1]"); } } } else { throw new IllegalArgumentException( "Rainbow needs at least 1 layer, such that v1 < v2."); } } /** * Getter for the number of layers * * @return the number of layers */ public int getNumOfLayers() { return this.vi.length - 1; } /** * Getter for the number of all the polynomials in Rainbow * * @return the number of the polynomials */ public int getDocLength() { return vi[vi.length - 1] - vi[0]; } /** * Getter for the array containing the number of Vinegar-variables per layer * * @return the numbers of vinegars per layer */ public int[] getVi() { return this.vi; } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_42_1
crossvul-java_data_bad_5761_5
package org.richfaces.demo.media; import java.awt.Color; import java.io.Serializable; public class MediaData implements Serializable{ private static final long serialVersionUID = 1L; Integer Width=110; Integer Height=50; Color Background=new Color(0,0,0); Color DrawColor=new Color(255,255,255); public MediaData() { } public Color getBackground() { return Background; } public void setBackground(Color background) { Background = background; } public Color getDrawColor() { return DrawColor; } public void setDrawColor(Color drawColor) { DrawColor = drawColor; } public Integer getHeight() { return Height; } public void setHeight(Integer height) { Height = height; } public Integer getWidth() { return Width; } public void setWidth(Integer width) { Width = width; } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_5761_5
crossvul-java_data_bad_5761_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-502/java/bad_5761_0
crossvul-java_data_good_5761_3
/** * License Agreement. * * Rich Faces - Natural Ajax for Java Server Faces (JSF) * * Copyright (C) 2007 Exadel, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.ajax4jsf.resource; import java.io.IOException; import java.io.OutputStream; import java.io.Serializable; import java.util.Date; import javax.el.ELContext; import javax.el.MethodExpression; import javax.el.ValueExpression; import javax.faces.component.UIComponent; import javax.faces.component.UIComponentBase; import javax.faces.context.FacesContext; /** * @author shura * */ public class UserResource extends InternetResourceBase { private String contentType; /** * */ public UserResource(boolean cacheable, boolean session, String mime) { super(); setCacheable(cacheable); setSessionAware(session); setContentType(mime); } /** * @return Returns the contentType. */ public String getContentType(ResourceContext resourceContext) { return contentType; } /** * @param contentType The contentType to set. */ public void setContentType(String contentType) { this.contentType = contentType; } /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#getDataToStore(javax.faces.context.FacesContext, java.lang.Object) */ public Object getDataToStore(FacesContext context, Object data) { UriData dataToStore = null; if (data instanceof ResourceComponent2) { ResourceComponent2 resource = (ResourceComponent2) data; dataToStore = new UriData(); dataToStore.value = resource.getValue(); dataToStore.createContent = UIComponentBase.saveAttachedState(context,resource.getCreateContentExpression()); if (data instanceof UIComponent) { UIComponent component = (UIComponent) data; ValueExpression expires = component.getValueExpression("expires"); if (null != expires) { dataToStore.expires = UIComponentBase.saveAttachedState(context,expires); } ValueExpression lastModified = component.getValueExpression("lastModified"); if (null != lastModified) { dataToStore.modified = UIComponentBase.saveAttachedState(context,lastModified); } } } return dataToStore; } /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#send(org.ajax4jsf.resource.ResourceContext) */ public void send(ResourceContext context) throws IOException { UriData data = (UriData) restoreData(context); FacesContext facesContext = FacesContext.getCurrentInstance(); if (null != data && null != facesContext ) { // Send headers ELContext elContext = facesContext.getELContext(); // if(data.expires != null){ // ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires); // Date expires = (Date) binding.getValue(elContext); // context.setDateHeader("Expires",expires.getTime()); // } // if(data.modified != null){ // ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified); // Date modified = (Date) binding.getValue(elContext); // context.setDateHeader("Last-Modified",modified.getTime()); // } // Send content OutputStream out = context.getOutputStream(); MethodExpression send = (MethodExpression) UIComponentBase.restoreAttachedState(facesContext,data.createContent); send.invoke(elContext,new Object[]{out,data.value}); } } @Override public Date getLastModified(ResourceContext resourceContext) { UriData data = (UriData) restoreData(resourceContext); FacesContext facesContext = FacesContext.getCurrentInstance(); if (null != data && null != facesContext ) { // Send headers ELContext elContext = facesContext.getELContext(); if(data.modified != null){ ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.modified); Date modified = (Date) binding.getValue(elContext); if (null != modified) { return modified; } } } return super.getLastModified(resourceContext); } @Override public long getExpired(ResourceContext resourceContext) { UriData data = (UriData) restoreData(resourceContext); FacesContext facesContext = FacesContext.getCurrentInstance(); if (null != data && null != facesContext ) { // Send headers ELContext elContext = facesContext.getELContext(); if(data.expires != null){ ValueExpression binding = (ValueExpression) UIComponentBase.restoreAttachedState(facesContext,data.expires); Date expires = (Date) binding.getValue(elContext); if (null != expires) { return expires.getTime()-System.currentTimeMillis(); } } } return super.getExpired(resourceContext); } /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#requireFacesContext() */ public boolean requireFacesContext() { // TODO Auto-generated method stub return true; } public static class UriData implements SerializableResource { /** * */ private static final long serialVersionUID = 1258987L; private Object value; private Object createContent; private Object expires; private Object modified; } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_5761_3
crossvul-java_data_bad_42_0
package org.bouncycastle.pqc.crypto.gmss; import java.security.SecureRandom; import java.util.Vector; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.KeyGenerationParameters; import org.bouncycastle.pqc.crypto.gmss.util.GMSSRandom; import org.bouncycastle.pqc.crypto.gmss.util.WinternitzOTSVerify; import org.bouncycastle.pqc.crypto.gmss.util.WinternitzOTSignature; /** * This class implements key pair generation of the generalized Merkle signature * scheme (GMSS). * * @see GMSSSigner */ public class GMSSKeyPairGenerator implements AsymmetricCipherKeyPairGenerator { /** * The source of randomness for OTS private key generation */ private GMSSRandom gmssRandom; /** * The hash function used for the construction of the authentication trees */ private Digest messDigestTree; /** * An array of the seeds for the PRGN (for main tree, and all current * subtrees) */ private byte[][] currentSeeds; /** * An array of seeds for the PRGN (for all subtrees after next) */ private byte[][] nextNextSeeds; /** * An array of the RootSignatures */ private byte[][] currentRootSigs; /** * Class of hash function to use */ private GMSSDigestProvider digestProvider; /** * The length of the seed for the PRNG */ private int mdLength; /** * the number of Layers */ private int numLayer; /** * Flag indicating if the class already has been initialized */ private boolean initialized = false; /** * Instance of GMSSParameterset */ private GMSSParameters gmssPS; /** * An array of the heights of the authentication trees of each layer */ private int[] heightOfTrees; /** * An array of the Winternitz parameter 'w' of each layer */ private int[] otsIndex; /** * The parameter K needed for the authentication path computation */ private int[] K; private GMSSKeyGenerationParameters gmssParams; /** * The GMSS OID. */ public static final String OID = "1.3.6.1.4.1.8301.3.1.3.3"; /** * The standard constructor tries to generate the GMSS algorithm identifier * with the corresponding OID. * * @param digestProvider provider for digest implementations. */ public GMSSKeyPairGenerator(GMSSDigestProvider digestProvider) { this.digestProvider = digestProvider; messDigestTree = digestProvider.get(); // set mdLength this.mdLength = messDigestTree.getDigestSize(); // construct randomizer this.gmssRandom = new GMSSRandom(messDigestTree); } /** * Generates the GMSS key pair. The public key is an instance of * JDKGMSSPublicKey, the private key is an instance of JDKGMSSPrivateKey. * * @return Key pair containing a JDKGMSSPublicKey and a JDKGMSSPrivateKey */ private AsymmetricCipherKeyPair genKeyPair() { if (!initialized) { initializeDefault(); } // initialize authenticationPaths and treehash instances byte[][][] currentAuthPaths = new byte[numLayer][][]; byte[][][] nextAuthPaths = new byte[numLayer - 1][][]; Treehash[][] currentTreehash = new Treehash[numLayer][]; Treehash[][] nextTreehash = new Treehash[numLayer - 1][]; Vector[] currentStack = new Vector[numLayer]; Vector[] nextStack = new Vector[numLayer - 1]; Vector[][] currentRetain = new Vector[numLayer][]; Vector[][] nextRetain = new Vector[numLayer - 1][]; for (int i = 0; i < numLayer; i++) { currentAuthPaths[i] = new byte[heightOfTrees[i]][mdLength]; currentTreehash[i] = new Treehash[heightOfTrees[i] - K[i]]; if (i > 0) { nextAuthPaths[i - 1] = new byte[heightOfTrees[i]][mdLength]; nextTreehash[i - 1] = new Treehash[heightOfTrees[i] - K[i]]; } currentStack[i] = new Vector(); if (i > 0) { nextStack[i - 1] = new Vector(); } } // initialize roots byte[][] currentRoots = new byte[numLayer][mdLength]; byte[][] nextRoots = new byte[numLayer - 1][mdLength]; // initialize seeds byte[][] seeds = new byte[numLayer][mdLength]; // initialize seeds[] by copying starting-seeds of first trees of each // layer for (int i = 0; i < numLayer; i++) { System.arraycopy(currentSeeds[i], 0, seeds[i], 0, mdLength); } // initialize rootSigs currentRootSigs = new byte[numLayer - 1][mdLength]; // ------------------------- // ------------------------- // --- calculation of current authpaths and current rootsigs (AUTHPATHS, // SIG)------ // from bottom up to the root for (int h = numLayer - 1; h >= 0; h--) { GMSSRootCalc tree = new GMSSRootCalc(this.heightOfTrees[h], this.K[h], digestProvider); try { // on lowest layer no lower root is available, so just call // the method with null as first parameter if (h == numLayer - 1) { tree = this.generateCurrentAuthpathAndRoot(null, currentStack[h], seeds[h], h); } else // otherwise call the method with the former computed root // value { tree = this.generateCurrentAuthpathAndRoot(currentRoots[h + 1], currentStack[h], seeds[h], h); } } catch (Exception e1) { e1.printStackTrace(); } // set initial values needed for the private key construction for (int i = 0; i < heightOfTrees[h]; i++) { System.arraycopy(tree.getAuthPath()[i], 0, currentAuthPaths[h][i], 0, mdLength); } currentRetain[h] = tree.getRetain(); currentTreehash[h] = tree.getTreehash(); System.arraycopy(tree.getRoot(), 0, currentRoots[h], 0, mdLength); } // --- calculation of next authpaths and next roots (AUTHPATHS+, ROOTS+) // ------ for (int h = numLayer - 2; h >= 0; h--) { GMSSRootCalc tree = this.generateNextAuthpathAndRoot(nextStack[h], seeds[h + 1], h + 1); // set initial values needed for the private key construction for (int i = 0; i < heightOfTrees[h + 1]; i++) { System.arraycopy(tree.getAuthPath()[i], 0, nextAuthPaths[h][i], 0, mdLength); } nextRetain[h] = tree.getRetain(); nextTreehash[h] = tree.getTreehash(); System.arraycopy(tree.getRoot(), 0, nextRoots[h], 0, mdLength); // create seed for the Merkle tree after next (nextNextSeeds) // SEEDs++ System.arraycopy(seeds[h + 1], 0, this.nextNextSeeds[h], 0, mdLength); } // ------------ // generate JDKGMSSPublicKey GMSSPublicKeyParameters publicKey = new GMSSPublicKeyParameters(currentRoots[0], gmssPS); // generate the JDKGMSSPrivateKey GMSSPrivateKeyParameters privateKey = new GMSSPrivateKeyParameters(currentSeeds, nextNextSeeds, currentAuthPaths, nextAuthPaths, currentTreehash, nextTreehash, currentStack, nextStack, currentRetain, nextRetain, nextRoots, currentRootSigs, gmssPS, digestProvider); // return the KeyPair return (new AsymmetricCipherKeyPair(publicKey, privateKey)); } /** * calculates the authpath for tree in layer h which starts with seed[h] * additionally computes the rootSignature of underlaying root * * @param currentStack stack used for the treehash instance created by this method * @param lowerRoot stores the root of the lower tree * @param seed starting seeds * @param h actual layer */ private GMSSRootCalc generateCurrentAuthpathAndRoot(byte[] lowerRoot, Vector currentStack, byte[] seed, int h) { byte[] help = new byte[mdLength]; byte[] OTSseed = new byte[mdLength]; OTSseed = gmssRandom.nextSeed(seed); WinternitzOTSignature ots; // data structure that constructs the whole tree and stores // the initial values for treehash, Auth and retain GMSSRootCalc treeToConstruct = new GMSSRootCalc(this.heightOfTrees[h], this.K[h], digestProvider); treeToConstruct.initialize(currentStack); // generate the first leaf if (h == numLayer - 1) { ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]); help = ots.getPublicKey(); } else { // for all layers except the lowest, generate the signature of the // underlying root // and reuse this signature to compute the first leaf of acual layer // more efficiently (by verifiing the signature) ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]); currentRootSigs[h] = ots.getSignature(lowerRoot); WinternitzOTSVerify otsver = new WinternitzOTSVerify(digestProvider.get(), otsIndex[h]); help = otsver.Verify(lowerRoot, currentRootSigs[h]); } // update the tree with the first leaf treeToConstruct.update(help); int seedForTreehashIndex = 3; int count = 0; // update the tree 2^(H) - 1 times, from the second to the last leaf for (int i = 1; i < (1 << this.heightOfTrees[h]); i++) { // initialize the seeds for the leaf generation with index 3 * 2^h if (i == seedForTreehashIndex && count < this.heightOfTrees[h] - this.K[h]) { treeToConstruct.initializeTreehashSeed(seed, count); seedForTreehashIndex *= 2; count++; } OTSseed = gmssRandom.nextSeed(seed); ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]); treeToConstruct.update(ots.getPublicKey()); } if (treeToConstruct.wasFinished()) { return treeToConstruct; } System.err.println("Baum noch nicht fertig konstruiert!!!"); return null; } /** * calculates the authpath and root for tree in layer h which starts with * seed[h] * * @param nextStack stack used for the treehash instance created by this method * @param seed starting seeds * @param h actual layer */ private GMSSRootCalc generateNextAuthpathAndRoot(Vector nextStack, byte[] seed, int h) { byte[] OTSseed = new byte[numLayer]; WinternitzOTSignature ots; // data structure that constructs the whole tree and stores // the initial values for treehash, Auth and retain GMSSRootCalc treeToConstruct = new GMSSRootCalc(this.heightOfTrees[h], this.K[h], this.digestProvider); treeToConstruct.initialize(nextStack); int seedForTreehashIndex = 3; int count = 0; // update the tree 2^(H) times, from the first to the last leaf for (int i = 0; i < (1 << this.heightOfTrees[h]); i++) { // initialize the seeds for the leaf generation with index 3 * 2^h if (i == seedForTreehashIndex && count < this.heightOfTrees[h] - this.K[h]) { treeToConstruct.initializeTreehashSeed(seed, count); seedForTreehashIndex *= 2; count++; } OTSseed = gmssRandom.nextSeed(seed); ots = new WinternitzOTSignature(OTSseed, digestProvider.get(), otsIndex[h]); treeToConstruct.update(ots.getPublicKey()); } if (treeToConstruct.wasFinished()) { return treeToConstruct; } System.err.println("N�chster Baum noch nicht fertig konstruiert!!!"); return null; } /** * This method initializes the GMSS KeyPairGenerator using an integer value * <code>keySize</code> as input. It provides a simple use of the GMSS for * testing demands. * <p> * A given <code>keysize</code> of less than 10 creates an amount 2^10 * signatures. A keySize between 10 and 20 creates 2^20 signatures. Given an * integer greater than 20 the key pair generator creates 2^40 signatures. * * @param keySize Assigns the parameters used for the GMSS signatures. There are * 3 choices:<br> * 1. keysize &lt;= 10: creates 2^10 signatures using the * parameterset<br> * P = (2, (5, 5), (3, 3), (3, 3))<br> * 2. keysize &gt; 10 and &lt;= 20: creates 2^20 signatures using the * parameterset<br> * P = (2, (10, 10), (5, 4), (2, 2))<br> * 3. keysize &gt; 20: creates 2^40 signatures using the * parameterset<br> * P = (2, (10, 10, 10, 10), (9, 9, 9, 3), (2, 2, 2, 2)) * @param secureRandom not used by GMSS, the SHA1PRNG of the SUN Provider is always * used */ public void initialize(int keySize, SecureRandom secureRandom) { KeyGenerationParameters kgp; if (keySize <= 10) { // create 2^10 keys int[] defh = {10}; int[] defw = {3}; int[] defk = {2}; // XXX sec random neede? kgp = new GMSSKeyGenerationParameters(secureRandom, new GMSSParameters(defh.length, defh, defw, defk)); } else if (keySize <= 20) { // create 2^20 keys int[] defh = {10, 10}; int[] defw = {5, 4}; int[] defk = {2, 2}; kgp = new GMSSKeyGenerationParameters(secureRandom, new GMSSParameters(defh.length, defh, defw, defk)); } else { // create 2^40 keys, keygen lasts around 80 seconds int[] defh = {10, 10, 10, 10}; int[] defw = {9, 9, 9, 3}; int[] defk = {2, 2, 2, 2}; kgp = new GMSSKeyGenerationParameters(secureRandom, new GMSSParameters(defh.length, defh, defw, defk)); } // call the initializer with the chosen parameters this.initialize(kgp); } /** * Initalizes the key pair generator using a parameter set as input */ public void initialize(KeyGenerationParameters param) { this.gmssParams = (GMSSKeyGenerationParameters)param; // generate GMSSParameterset this.gmssPS = new GMSSParameters(gmssParams.getParameters().getNumOfLayers(), gmssParams.getParameters().getHeightOfTrees(), gmssParams.getParameters().getWinternitzParameter(), gmssParams.getParameters().getK()); this.numLayer = gmssPS.getNumOfLayers(); this.heightOfTrees = gmssPS.getHeightOfTrees(); this.otsIndex = gmssPS.getWinternitzParameter(); this.K = gmssPS.getK(); // seeds this.currentSeeds = new byte[numLayer][mdLength]; this.nextNextSeeds = new byte[numLayer - 1][mdLength]; // construct SecureRandom for initial seed generation SecureRandom secRan = new SecureRandom(); // generation of initial seeds for (int i = 0; i < numLayer; i++) { secRan.nextBytes(currentSeeds[i]); gmssRandom.nextSeed(currentSeeds[i]); } this.initialized = true; } /** * This method is called by generateKeyPair() in case that no other * initialization method has been called by the user */ private void initializeDefault() { int[] defh = {10, 10, 10, 10}; int[] defw = {3, 3, 3, 3}; int[] defk = {2, 2, 2, 2}; KeyGenerationParameters kgp = new GMSSKeyGenerationParameters(new SecureRandom(), new GMSSParameters(defh.length, defh, defw, defk)); this.initialize(kgp); } public void init(KeyGenerationParameters param) { this.initialize(param); } public AsymmetricCipherKeyPair generateKeyPair() { return genKeyPair(); } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_42_0
crossvul-java_data_good_1893_5
package io.onedev.server.product; import java.util.EnumSet; import javax.inject.Inject; import javax.servlet.DispatcherType; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.apache.shiro.web.env.EnvironmentLoader; import org.apache.shiro.web.env.EnvironmentLoaderListener; import org.apache.shiro.web.servlet.ShiroFilter; import org.apache.wicket.protocol.http.WicketServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.glassfish.jersey.servlet.ServletContainer; import io.onedev.commons.launcher.bootstrap.Bootstrap; import io.onedev.server.git.GitFilter; import io.onedev.server.git.hookcallback.GitPostReceiveCallback; import io.onedev.server.git.hookcallback.GitPreReceiveCallback; import io.onedev.server.security.DefaultWebEnvironment; import io.onedev.server.util.ServerConfig; import io.onedev.server.util.jetty.ClasspathAssetServlet; import io.onedev.server.util.jetty.FileAssetServlet; import io.onedev.server.util.jetty.ServletConfigurator; import io.onedev.server.web.asset.icon.IconScope; import io.onedev.server.web.img.ImageScope; import io.onedev.server.web.websocket.WebSocketManager; public class ProductServletConfigurator implements ServletConfigurator { private final ServerConfig serverConfig; private final ShiroFilter shiroFilter; private final GitFilter gitFilter; private final GitPreReceiveCallback preReceiveServlet; private final GitPostReceiveCallback postReceiveServlet; private final WicketServlet wicketServlet; private final ServletContainer jerseyServlet; private final WebSocketManager webSocketManager; @Inject public ProductServletConfigurator(ServerConfig serverConfig, ShiroFilter shiroFilter, GitFilter gitFilter, GitPreReceiveCallback preReceiveServlet, GitPostReceiveCallback postReceiveServlet, WicketServlet wicketServlet, WebSocketManager webSocketManager, ServletContainer jerseyServlet) { this.serverConfig = serverConfig; this.shiroFilter = shiroFilter; this.gitFilter = gitFilter; this.preReceiveServlet = preReceiveServlet; this.postReceiveServlet = postReceiveServlet; this.wicketServlet = wicketServlet; this.webSocketManager = webSocketManager; this.jerseyServlet = jerseyServlet; } @Override public void configure(ServletContextHandler context) { context.setContextPath("/"); context.getSessionHandler().setMaxInactiveInterval(serverConfig.getSessionTimeout()); context.setInitParameter(EnvironmentLoader.ENVIRONMENT_CLASS_PARAM, DefaultWebEnvironment.class.getName()); context.addEventListener(new EnvironmentLoaderListener()); context.addFilter(new FilterHolder(shiroFilter), "/*", EnumSet.allOf(DispatcherType.class)); context.addFilter(new FilterHolder(gitFilter), "/*", EnumSet.allOf(DispatcherType.class)); context.addServlet(new ServletHolder(preReceiveServlet), GitPreReceiveCallback.PATH + "/*"); context.addServlet(new ServletHolder(postReceiveServlet), GitPostReceiveCallback.PATH + "/*"); /* * Add wicket servlet as the default servlet which will serve all requests failed to * match a path pattern */ context.addServlet(new ServletHolder(wicketServlet), "/"); context.addServlet(new ServletHolder(new ClasspathAssetServlet(ImageScope.class)), "/img/*"); context.addServlet(new ServletHolder(new ClasspathAssetServlet(IconScope.class)), "/icon/*"); context.getSessionHandler().addEventListener(new HttpSessionListener() { @Override public void sessionCreated(HttpSessionEvent se) { } @Override public void sessionDestroyed(HttpSessionEvent se) { webSocketManager.onDestroySession(se.getSession().getId()); } }); /* * Configure a servlet to serve contents under site folder. Site folder can be used * to hold site specific web assets. */ ServletHolder fileServletHolder = new ServletHolder(new FileAssetServlet(Bootstrap.getSiteDir())); context.addServlet(fileServletHolder, "/site/*"); context.addServlet(fileServletHolder, "/robots.txt"); context.addServlet(new ServletHolder(jerseyServlet), "/rest/*"); } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_1893_5
crossvul-java_data_good_5761_5
package org.richfaces.demo.media; import java.awt.Color; import org.ajax4jsf.resource.SerializableResource; public class MediaData implements SerializableResource { private static final long serialVersionUID = 1L; Integer Width=110; Integer Height=50; Color Background=new Color(0,0,0); Color DrawColor=new Color(255,255,255); public MediaData() { } public Color getBackground() { return Background; } public void setBackground(Color background) { Background = background; } public Color getDrawColor() { return DrawColor; } public void setDrawColor(Color drawColor) { DrawColor = drawColor; } public Integer getHeight() { return Height; } public void setHeight(Integer height) { Height = height; } public Integer getWidth() { return Width; } public void setWidth(Integer width) { Width = width; } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_5761_5
crossvul-java_data_bad_5761_7
/** * License Agreement. * * JBoss RichFaces - Ajax4jsf Component Library * * Copyright (C) 2007 Exadel, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.richfaces.renderkit.html; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.Serializable; import javax.faces.FacesException; import javax.faces.component.UIComponentBase; import javax.faces.context.FacesContext; import javax.faces.el.MethodBinding; import org.ajax4jsf.resource.GifRenderer; import org.ajax4jsf.resource.ImageRenderer; import org.ajax4jsf.resource.InternetResourceBase; import org.ajax4jsf.resource.JpegRenderer; import org.ajax4jsf.resource.PngRenderer; import org.ajax4jsf.resource.ResourceContext; import org.ajax4jsf.resource.ResourceRenderer; import org.ajax4jsf.util.HtmlColor; import org.richfaces.component.UIPaint2D; /** * Resource for create image by managed bean method * @author asmirnov@exadel.com (latest modification by $Author: aizobov $) * @version $Revision: 1.4 $ $Date: 2007/02/28 10:35:23 $ * */ public class Paint2DResource extends InternetResourceBase { private static final ImageRenderer[] _renderers= {new GifRenderer(), new JpegRenderer(), new PngRenderer()}; // private static final ThreadLocal<String> threadLocalContentType = new ThreadLocal<String>(); /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#getRenderer() */ public ResourceRenderer getRenderer() { return _renderers[0]; } public ResourceRenderer getRenderer(ResourceContext context) { ImageData data = null; if (context != null) { data = (ImageData) restoreData(context); } ImageRenderer renderer = _renderers[null==data?0:data._format]; return renderer; } /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#isCacheable() */ public boolean isCacheable() { return false; } public boolean isCacheable(ResourceContext resourceContext) { ImageData data = (ImageData) restoreData(resourceContext); return data.cacheable; } /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#requireFacesContext() */ public boolean requireFacesContext() { // work in context return true; } /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#getDataToStore(javax.faces.context.FacesContext, java.lang.Object) */ protected Object getDataToStore(FacesContext context, Object data) { if (data instanceof UIPaint2D) { UIPaint2D paint2D = (UIPaint2D) data; ImageData dataToStore = new ImageData(); dataToStore._width = paint2D.getWidth(); dataToStore._height = paint2D.getHeight(); dataToStore._data = paint2D.getData(); dataToStore._paint = UIComponentBase.saveAttachedState(context, paint2D.getPaint()); String format = paint2D.getFormat(); if("jpeg".equalsIgnoreCase(format)) { dataToStore._format = 1; } else if("png".equalsIgnoreCase(format)) { dataToStore._format = 2; } String bgColor = paint2D.getBgcolor(); try { dataToStore._bgColor = HtmlColor.decode(bgColor).getRGB(); } catch (Exception e) {} dataToStore.cacheable = paint2D.isCacheable(); return dataToStore; } else { throw new FacesException("Data for painting image resource not instance of UIPaint2D"); } } private static final class ImageData implements Serializable { private static final long serialVersionUID = 4452040100045367728L; int _width=1; int _height = 1; Object _data; int _format = 0; Object _paint; boolean cacheable = false; /* * init color with transparent by default */ int _bgColor = 0; } /** * Primary calculation of image dimensions - used when HTML code is generated * to render IMG's width and height * Subclasses should override this method to provide correct sizes of rendered images * @param facesContext * @return dimensions of the image to be displayed on page */ public Dimension getDimensions(FacesContext facesContext, Object data){ if (data instanceof UIPaint2D) { UIPaint2D paint2D = (UIPaint2D) data; return new Dimension(paint2D.getWidth(),paint2D.getHeight()); } return new Dimension(1,1); } /** * Secondary calculation is used basically by getImage method * @param resourceContext * @return */ protected Dimension getDimensions(ResourceContext resourceContext){ ImageData data = (ImageData) restoreData(resourceContext); return new Dimension(data._width,data._height); } /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#send(javax.faces.context.FacesContext, java.lang.Object) */ public void send(ResourceContext context) throws IOException { ImageData data = (ImageData) restoreData(context); ImageRenderer renderer = (ImageRenderer) getRenderer(context); FacesContext facesContext = FacesContext.getCurrentInstance(); try { BufferedImage image = renderer.createImage(data._width,data._height); Graphics2D graphics = image.createGraphics(); try { if (data._bgColor != 0) { Color color = new Color(data._bgColor); graphics.setBackground(color); graphics.clearRect(0, 0, data._width, data._height); } MethodBinding paint = (MethodBinding) UIComponentBase.restoreAttachedState(facesContext, data._paint); paint.invoke(facesContext, new Object[] {graphics,data._data}); } finally { if (graphics != null) { graphics.dispose(); } } renderer.sendImage(context, image); } catch (Exception e) { // log.error("Error send image from resource "+context.getPathInfo(),e); throw new FacesException("Error send image ",e); } } // public String getContentType(ResourceContext context) { // Object contentType = threadLocalContentType.get(); // if (contentType != null) { // return (String) contentType; // } else { // return super.getContentType(context); // } // } /* (non-Javadoc) * @see org.ajax4jsf.resource.InternetResourceBase#sendHeaders(org.ajax4jsf.resource.ResourceContext) */ // public void sendHeaders(ResourceContext context) { // ImageData data = (ImageData) restoreData(context); // ImageRenderer renderer = _renderers[data._format]; // threadLocalContentType.set(renderer.getContentType()); // // super.sendHeaders(context); // // threadLocalContentType.set(null); // } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_5761_7
crossvul-java_data_good_42_6
package org.bouncycastle.pqc.crypto.test; import java.io.IOException; import java.security.SecureRandom; import junit.framework.TestCase; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.pqc.crypto.xmss.XMSS; import org.bouncycastle.pqc.crypto.xmss.XMSSMT; import org.bouncycastle.pqc.crypto.xmss.XMSSMTParameters; import org.bouncycastle.pqc.crypto.xmss.XMSSParameters; import org.bouncycastle.pqc.crypto.xmss.XMSSPrivateKeyParameters; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Base64; /** * Test cases for XMSSMTPrivateKey class. */ public class XMSSMTPrivateKeyTest extends TestCase { public void testPrivateKeySerialisation() throws Exception { String stream = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArO0ABXNyACJzdW4ucm1pLnNlcnZlci5BY3RpdmF0aW9uR3JvdXBJbXBsT+r9SAwuMqcCAARaAA1ncm91cEluYWN0aXZlTAAGYWN0aXZldAAVTGphdmEvdXRpbC9IYXNodGFibGU7TAAHZ3JvdXBJRHQAJ0xqYXZhL3JtaS9hY3RpdmF0aW9uL0FjdGl2YXRpb25Hcm91cElEO0wACWxvY2tlZElEc3QAEExqYXZhL3V0aWwvTGlzdDt4cgAjamF2YS5ybWkuYWN0aXZhdGlvbi5BY3RpdmF0aW9uR3JvdXCVLvKwBSnVVAIAA0oAC2luY2FybmF0aW9uTAAHZ3JvdXBJRHEAfgACTAAHbW9uaXRvcnQAJ0xqYXZhL3JtaS9hY3RpdmF0aW9uL0FjdGl2YXRpb25Nb25pdG9yO3hyACNqYXZhLnJtaS5zZXJ2ZXIuVW5pY2FzdFJlbW90ZU9iamVjdEUJEhX14n4xAgADSQAEcG9ydEwAA2NzZnQAKExqYXZhL3JtaS9zZXJ2ZXIvUk1JQ2xpZW50U29ja2V0RmFjdG9yeTtMAANzc2Z0AChMamF2YS9ybWkvc2VydmVyL1JNSVNlcnZlclNvY2tldEZhY3Rvcnk7eHIAHGphdmEucm1pLnNlcnZlci5SZW1vdGVTZXJ2ZXLHGQcSaPM5+wIAAHhyABxqYXZhLnJtaS5zZXJ2ZXIuUmVtb3RlT2JqZWN002G0kQxhMx4DAAB4cHcSABBVbmljYXN0U2VydmVyUmVmeAAAFbNwcAAAAAAAAAAAcHAAcHBw"; XMSSParameters params = new XMSSParameters(10, new SHA256Digest()); byte[] output = Base64.decode(new String(stream).getBytes("UTF-8")); //Simple Exploit try { new XMSSPrivateKeyParameters.Builder(params).withPrivateKey(output, params).build(); } catch (IllegalArgumentException e) { assertTrue(e.getCause() instanceof IOException); } //Same Exploit other method XMSS xmss2 = new XMSS(params, new SecureRandom()); xmss2.generateKeys(); byte[] publicKey = xmss2.exportPublicKey(); try { xmss2.importState(output, publicKey); } catch (IllegalArgumentException e) { assertTrue(e.getCause() instanceof IOException); } } public void testPrivateKeyParsingSHA256() throws Exception { XMSSMTParameters params = new XMSSMTParameters(20, 10, new SHA256Digest()); XMSSMT mt = new XMSSMT(params, new SecureRandom()); mt.generateKeys(); byte[] privateKey = mt.exportPrivateKey(); byte[] publicKey = mt.exportPublicKey(); mt.importState(privateKey, publicKey); assertTrue(Arrays.areEqual(privateKey, mt.exportPrivateKey())); } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_42_6
crossvul-java_data_good_1893_0
package io.onedev.server; import java.io.Serializable; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.inject.Singleton; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityNotFoundException; import javax.persistence.OneToMany; import javax.persistence.Transient; import javax.persistence.Version; import javax.validation.Configuration; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.apache.shiro.authc.credential.PasswordService; import org.apache.shiro.authz.UnauthorizedException; import org.apache.shiro.guice.aop.ShiroAopModule; import org.apache.shiro.mgt.RememberMeManager; import org.apache.shiro.realm.Realm; import org.apache.shiro.web.filter.mgt.FilterChainManager; import org.apache.shiro.web.filter.mgt.FilterChainResolver; import org.apache.shiro.web.mgt.WebSecurityManager; import org.apache.shiro.web.servlet.ShiroFilter; import org.apache.sshd.common.keyprovider.KeyPairProvider; import org.apache.wicket.Application; import org.apache.wicket.core.request.mapper.StalePageException; import org.apache.wicket.protocol.http.PageExpiredException; import org.apache.wicket.protocol.http.WicketFilter; import org.apache.wicket.protocol.http.WicketServlet; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.websocket.api.WebSocketPolicy; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletContainer; import org.hibernate.CallbackException; import org.hibernate.Interceptor; import org.hibernate.ObjectNotFoundException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.StaleStateException; import org.hibernate.boot.model.naming.PhysicalNamingStrategy; import org.hibernate.collection.internal.PersistentBag; import org.hibernate.exception.ConstraintViolationException; import org.hibernate.type.Type; import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.inject.Provider; import com.google.inject.matcher.AbstractMatcher; import com.google.inject.matcher.Matchers; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamOmitField; import com.thoughtworks.xstream.converters.basic.NullConverter; import com.thoughtworks.xstream.converters.extended.ISO8601DateConverter; import com.thoughtworks.xstream.converters.extended.ISO8601SqlTimestampConverter; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import com.thoughtworks.xstream.core.JVM; import com.thoughtworks.xstream.mapper.MapperWrapper; import com.vladsch.flexmark.Extension; import io.onedev.commons.launcher.bootstrap.Bootstrap; import io.onedev.commons.launcher.loader.AbstractPlugin; import io.onedev.commons.launcher.loader.AbstractPluginModule; import io.onedev.commons.launcher.loader.ImplementationProvider; import io.onedev.commons.utils.ExceptionUtils; import io.onedev.commons.utils.StringUtils; import io.onedev.server.buildspec.job.DefaultJobManager; import io.onedev.server.buildspec.job.JobManager; import io.onedev.server.buildspec.job.log.DefaultLogManager; import io.onedev.server.buildspec.job.log.LogManager; import io.onedev.server.buildspec.job.log.instruction.LogInstruction; import io.onedev.server.entitymanager.BuildDependenceManager; import io.onedev.server.entitymanager.BuildManager; import io.onedev.server.entitymanager.BuildParamManager; import io.onedev.server.entitymanager.BuildQuerySettingManager; import io.onedev.server.entitymanager.CodeCommentManager; import io.onedev.server.entitymanager.CodeCommentQuerySettingManager; import io.onedev.server.entitymanager.CodeCommentReplyManager; import io.onedev.server.entitymanager.CommitQuerySettingManager; import io.onedev.server.entitymanager.GroupAuthorizationManager; import io.onedev.server.entitymanager.GroupManager; import io.onedev.server.entitymanager.IssueChangeManager; import io.onedev.server.entitymanager.IssueCommentManager; import io.onedev.server.entitymanager.IssueFieldManager; import io.onedev.server.entitymanager.IssueManager; import io.onedev.server.entitymanager.IssueQuerySettingManager; import io.onedev.server.entitymanager.IssueVoteManager; import io.onedev.server.entitymanager.IssueWatchManager; import io.onedev.server.entitymanager.MembershipManager; import io.onedev.server.entitymanager.MilestoneManager; import io.onedev.server.entitymanager.ProjectManager; import io.onedev.server.entitymanager.PullRequestAssignmentManager; import io.onedev.server.entitymanager.PullRequestChangeManager; import io.onedev.server.entitymanager.PullRequestCommentManager; import io.onedev.server.entitymanager.PullRequestManager; import io.onedev.server.entitymanager.PullRequestQuerySettingManager; import io.onedev.server.entitymanager.PullRequestReviewManager; import io.onedev.server.entitymanager.PullRequestUpdateManager; import io.onedev.server.entitymanager.PullRequestVerificationManager; import io.onedev.server.entitymanager.PullRequestWatchManager; import io.onedev.server.entitymanager.RoleManager; import io.onedev.server.entitymanager.SettingManager; import io.onedev.server.entitymanager.SshKeyManager; import io.onedev.server.entitymanager.UrlManager; import io.onedev.server.entitymanager.UserAuthorizationManager; import io.onedev.server.entitymanager.UserManager; import io.onedev.server.entitymanager.impl.DefaultBuildDependenceManager; import io.onedev.server.entitymanager.impl.DefaultBuildManager; import io.onedev.server.entitymanager.impl.DefaultBuildParamManager; import io.onedev.server.entitymanager.impl.DefaultBuildQuerySettingManager; import io.onedev.server.entitymanager.impl.DefaultCodeCommentManager; import io.onedev.server.entitymanager.impl.DefaultCodeCommentQuerySettingManager; import io.onedev.server.entitymanager.impl.DefaultCodeCommentReplyManager; import io.onedev.server.entitymanager.impl.DefaultCommitQuerySettingManager; import io.onedev.server.entitymanager.impl.DefaultGroupAuthorizationManager; import io.onedev.server.entitymanager.impl.DefaultGroupManager; import io.onedev.server.entitymanager.impl.DefaultIssueChangeManager; import io.onedev.server.entitymanager.impl.DefaultIssueCommentManager; import io.onedev.server.entitymanager.impl.DefaultIssueFieldManager; import io.onedev.server.entitymanager.impl.DefaultIssueManager; import io.onedev.server.entitymanager.impl.DefaultIssueQuerySettingManager; import io.onedev.server.entitymanager.impl.DefaultIssueVoteManager; import io.onedev.server.entitymanager.impl.DefaultIssueWatchManager; import io.onedev.server.entitymanager.impl.DefaultMembershipManager; import io.onedev.server.entitymanager.impl.DefaultMilestoneManager; import io.onedev.server.entitymanager.impl.DefaultProjectManager; import io.onedev.server.entitymanager.impl.DefaultPullRequestAssignmentManager; import io.onedev.server.entitymanager.impl.DefaultPullRequestChangeManager; import io.onedev.server.entitymanager.impl.DefaultPullRequestCommentManager; import io.onedev.server.entitymanager.impl.DefaultPullRequestManager; import io.onedev.server.entitymanager.impl.DefaultPullRequestQuerySettingManager; import io.onedev.server.entitymanager.impl.DefaultPullRequestReviewManager; import io.onedev.server.entitymanager.impl.DefaultPullRequestUpdateManager; import io.onedev.server.entitymanager.impl.DefaultPullRequestVerificationManager; import io.onedev.server.entitymanager.impl.DefaultPullRequestWatchManager; import io.onedev.server.entitymanager.impl.DefaultRoleManager; import io.onedev.server.entitymanager.impl.DefaultSettingManager; import io.onedev.server.entitymanager.impl.DefaultSshKeyManager; import io.onedev.server.entitymanager.impl.DefaultUserAuthorizationManager; import io.onedev.server.entitymanager.impl.DefaultUserManager; import io.onedev.server.git.GitFilter; import io.onedev.server.git.GitSshCommandCreator; import io.onedev.server.git.config.GitConfig; import io.onedev.server.git.hookcallback.GitPostReceiveCallback; import io.onedev.server.git.hookcallback.GitPreReceiveCallback; import io.onedev.server.infomanager.CommitInfoManager; import io.onedev.server.infomanager.DefaultCommitInfoManager; import io.onedev.server.infomanager.DefaultPullRequestInfoManager; import io.onedev.server.infomanager.DefaultUserInfoManager; import io.onedev.server.infomanager.PullRequestInfoManager; import io.onedev.server.infomanager.UserInfoManager; import io.onedev.server.maintenance.ApplyDatabaseConstraints; import io.onedev.server.maintenance.BackupDatabase; import io.onedev.server.maintenance.CheckDataVersion; import io.onedev.server.maintenance.CleanDatabase; import io.onedev.server.maintenance.DataManager; import io.onedev.server.maintenance.DefaultDataManager; import io.onedev.server.maintenance.ResetAdminPassword; import io.onedev.server.maintenance.RestoreDatabase; import io.onedev.server.maintenance.Upgrade; import io.onedev.server.model.support.administration.GroovyScript; import io.onedev.server.model.support.administration.authenticator.Authenticator; import io.onedev.server.model.support.administration.jobexecutor.AutoDiscoveredJobExecutor; import io.onedev.server.model.support.administration.jobexecutor.JobExecutor; import io.onedev.server.notification.BuildNotificationManager; import io.onedev.server.notification.CodeCommentNotificationManager; import io.onedev.server.notification.CommitNotificationManager; import io.onedev.server.notification.DefaultMailManager; import io.onedev.server.notification.IssueNotificationManager; import io.onedev.server.notification.MailManager; import io.onedev.server.notification.PullRequestNotificationManager; import io.onedev.server.notification.WebHookManager; import io.onedev.server.persistence.DefaultIdManager; import io.onedev.server.persistence.DefaultPersistManager; import io.onedev.server.persistence.DefaultSessionManager; import io.onedev.server.persistence.DefaultTransactionManager; import io.onedev.server.persistence.HibernateInterceptor; import io.onedev.server.persistence.IdManager; import io.onedev.server.persistence.PersistListener; import io.onedev.server.persistence.PersistManager; import io.onedev.server.persistence.PrefixedNamingStrategy; import io.onedev.server.persistence.SessionFactoryProvider; import io.onedev.server.persistence.SessionInterceptor; import io.onedev.server.persistence.SessionManager; import io.onedev.server.persistence.SessionProvider; import io.onedev.server.persistence.TransactionInterceptor; import io.onedev.server.persistence.TransactionManager; import io.onedev.server.persistence.annotation.Sessional; import io.onedev.server.persistence.annotation.Transactional; import io.onedev.server.persistence.dao.Dao; import io.onedev.server.persistence.dao.DefaultDao; import io.onedev.server.rest.RestConstants; import io.onedev.server.rest.jersey.DefaultServletContainer; import io.onedev.server.rest.jersey.JerseyConfigurator; import io.onedev.server.rest.jersey.ResourceConfigProvider; import io.onedev.server.search.code.DefaultIndexManager; import io.onedev.server.search.code.DefaultSearchManager; import io.onedev.server.search.code.IndexManager; import io.onedev.server.search.code.SearchManager; import io.onedev.server.security.BasicAuthenticationFilter; import io.onedev.server.security.BearerAuthenticationFilter; import io.onedev.server.security.CodePullAuthorizationSource; import io.onedev.server.security.DefaultFilterChainResolver; import io.onedev.server.security.DefaultPasswordService; import io.onedev.server.security.DefaultRememberMeManager; import io.onedev.server.security.DefaultWebSecurityManager; import io.onedev.server.security.FilterChainConfigurator; import io.onedev.server.security.SecurityUtils; import io.onedev.server.security.realm.AbstractAuthorizingRealm; import io.onedev.server.ssh.DefaultKeyPairProvider; import io.onedev.server.ssh.DefaultSshAuthenticator; import io.onedev.server.ssh.SshAuthenticator; import io.onedev.server.ssh.SshCommandCreator; import io.onedev.server.ssh.SshServerLauncher; import io.onedev.server.storage.AttachmentStorageManager; import io.onedev.server.storage.DefaultAttachmentStorageManager; import io.onedev.server.storage.DefaultStorageManager; import io.onedev.server.storage.StorageManager; import io.onedev.server.util.jackson.ObjectMapperConfigurator; import io.onedev.server.util.jackson.ObjectMapperProvider; import io.onedev.server.util.jackson.git.GitObjectMapperConfigurator; import io.onedev.server.util.jackson.hibernate.HibernateObjectMapperConfigurator; import io.onedev.server.util.jetty.DefaultJettyLauncher; import io.onedev.server.util.jetty.JettyLauncher; import io.onedev.server.util.markdown.DefaultMarkdownManager; import io.onedev.server.util.markdown.EntityReferenceManager; import io.onedev.server.util.markdown.MarkdownManager; import io.onedev.server.util.markdown.MarkdownProcessor; import io.onedev.server.util.schedule.DefaultTaskScheduler; import io.onedev.server.util.schedule.TaskScheduler; import io.onedev.server.util.script.ScriptContribution; import io.onedev.server.util.validation.DefaultEntityValidator; import io.onedev.server.util.validation.EntityValidator; import io.onedev.server.util.validation.ValidatorProvider; import io.onedev.server.util.work.BatchWorkManager; import io.onedev.server.util.work.DefaultBatchWorkManager; import io.onedev.server.util.work.DefaultWorkExecutor; import io.onedev.server.util.work.WorkExecutor; import io.onedev.server.util.xstream.CollectionConverter; import io.onedev.server.util.xstream.HibernateProxyConverter; import io.onedev.server.util.xstream.MapConverter; import io.onedev.server.util.xstream.ReflectionConverter; import io.onedev.server.util.xstream.StringConverter; import io.onedev.server.util.xstream.VersionedDocumentConverter; import io.onedev.server.web.DefaultUrlManager; import io.onedev.server.web.DefaultWicketFilter; import io.onedev.server.web.DefaultWicketServlet; import io.onedev.server.web.ExpectedExceptionContribution; import io.onedev.server.web.ResourcePackScopeContribution; import io.onedev.server.web.WebApplication; import io.onedev.server.web.WebApplicationConfigurator; import io.onedev.server.web.avatar.AvatarManager; import io.onedev.server.web.avatar.DefaultAvatarManager; import io.onedev.server.web.component.diff.DiffRenderer; import io.onedev.server.web.component.markdown.SourcePositionTrackExtension; import io.onedev.server.web.component.markdown.emoji.EmojiExtension; import io.onedev.server.web.component.taskbutton.TaskButton; import io.onedev.server.web.editable.DefaultEditSupportRegistry; import io.onedev.server.web.editable.EditSupport; import io.onedev.server.web.editable.EditSupportLocator; import io.onedev.server.web.editable.EditSupportRegistry; import io.onedev.server.web.mapper.DynamicPathPageMapper; import io.onedev.server.web.page.layout.DefaultUICustomization; import io.onedev.server.web.page.layout.UICustomization; import io.onedev.server.web.page.project.blob.render.BlobRendererContribution; import io.onedev.server.web.page.test.TestPage; import io.onedev.server.web.websocket.BuildEventBroadcaster; import io.onedev.server.web.websocket.CodeCommentEventBroadcaster; import io.onedev.server.web.websocket.CommitIndexedBroadcaster; import io.onedev.server.web.websocket.DefaultWebSocketManager; import io.onedev.server.web.websocket.IssueEventBroadcaster; import io.onedev.server.web.websocket.PullRequestEventBroadcaster; import io.onedev.server.web.websocket.WebSocketManager; import io.onedev.server.web.websocket.WebSocketPolicyProvider; /** * NOTE: Do not forget to rename moduleClass property defined in the pom if you've renamed this class. * */ public class CoreModule extends AbstractPluginModule { @Override protected void configure() { super.configure(); bind(JettyLauncher.class).to(DefaultJettyLauncher.class); bind(ServletContextHandler.class).toProvider(DefaultJettyLauncher.class); bind(ObjectMapper.class).toProvider(ObjectMapperProvider.class).in(Singleton.class); bind(ValidatorFactory.class).toProvider(new com.google.inject.Provider<ValidatorFactory>() { @Override public ValidatorFactory get() { Configuration<?> configuration = Validation .byDefaultProvider() .configure() .messageInterpolator(new ParameterMessageInterpolator()); return configuration.buildValidatorFactory(); } }).in(Singleton.class); bind(Validator.class).toProvider(ValidatorProvider.class).in(Singleton.class); configurePersistence(); configureSecurity(); configureRestServices(); configureWeb(); configureSsh(); configureGit(); configureBuild(); /* * Declare bindings explicitly instead of using ImplementedBy annotation as * HK2 to guice bridge can only search in explicit bindings in Guice */ bind(MarkdownManager.class).to(DefaultMarkdownManager.class); bind(StorageManager.class).to(DefaultStorageManager.class); bind(SettingManager.class).to(DefaultSettingManager.class); bind(DataManager.class).to(DefaultDataManager.class); bind(TaskScheduler.class).to(DefaultTaskScheduler.class); bind(PullRequestCommentManager.class).to(DefaultPullRequestCommentManager.class); bind(CodeCommentManager.class).to(DefaultCodeCommentManager.class); bind(PullRequestManager.class).to(DefaultPullRequestManager.class); bind(PullRequestUpdateManager.class).to(DefaultPullRequestUpdateManager.class); bind(ProjectManager.class).to(DefaultProjectManager.class); bind(UserManager.class).to(DefaultUserManager.class); bind(PullRequestReviewManager.class).to(DefaultPullRequestReviewManager.class); bind(BuildManager.class).to(DefaultBuildManager.class); bind(BuildDependenceManager.class).to(DefaultBuildDependenceManager.class); bind(JobManager.class).to(DefaultJobManager.class); bind(LogManager.class).to(DefaultLogManager.class); bind(PullRequestVerificationManager.class).to(DefaultPullRequestVerificationManager.class); bind(MailManager.class).to(DefaultMailManager.class); bind(IssueManager.class).to(DefaultIssueManager.class); bind(IssueFieldManager.class).to(DefaultIssueFieldManager.class); bind(BuildParamManager.class).to(DefaultBuildParamManager.class); bind(UserAuthorizationManager.class).to(DefaultUserAuthorizationManager.class); bind(GroupAuthorizationManager.class).to(DefaultGroupAuthorizationManager.class); bind(PullRequestWatchManager.class).to(DefaultPullRequestWatchManager.class); bind(RoleManager.class).to(DefaultRoleManager.class); bind(CommitInfoManager.class).to(DefaultCommitInfoManager.class); bind(UserInfoManager.class).to(DefaultUserInfoManager.class); bind(BatchWorkManager.class).to(DefaultBatchWorkManager.class); bind(GroupManager.class).to(DefaultGroupManager.class); bind(MembershipManager.class).to(DefaultMembershipManager.class); bind(PullRequestChangeManager.class).to(DefaultPullRequestChangeManager.class); bind(CodeCommentReplyManager.class).to(DefaultCodeCommentReplyManager.class); bind(AttachmentStorageManager.class).to(DefaultAttachmentStorageManager.class); bind(PullRequestInfoManager.class).to(DefaultPullRequestInfoManager.class); bind(WorkExecutor.class).to(DefaultWorkExecutor.class); bind(PullRequestNotificationManager.class); bind(CommitNotificationManager.class); bind(BuildNotificationManager.class); bind(IssueNotificationManager.class); bind(EntityReferenceManager.class); bind(CodeCommentNotificationManager.class); bind(CodeCommentManager.class).to(DefaultCodeCommentManager.class); bind(IssueWatchManager.class).to(DefaultIssueWatchManager.class); bind(IssueChangeManager.class).to(DefaultIssueChangeManager.class); bind(IssueVoteManager.class).to(DefaultIssueVoteManager.class); bind(MilestoneManager.class).to(DefaultMilestoneManager.class); bind(Session.class).toProvider(SessionProvider.class); bind(EntityManager.class).toProvider(SessionProvider.class); bind(SessionFactory.class).toProvider(SessionFactoryProvider.class); bind(EntityManagerFactory.class).toProvider(SessionFactoryProvider.class); bind(IssueCommentManager.class).to(DefaultIssueCommentManager.class); bind(IssueQuerySettingManager.class).to(DefaultIssueQuerySettingManager.class); bind(PullRequestQuerySettingManager.class).to(DefaultPullRequestQuerySettingManager.class); bind(CodeCommentQuerySettingManager.class).to(DefaultCodeCommentQuerySettingManager.class); bind(CommitQuerySettingManager.class).to(DefaultCommitQuerySettingManager.class); bind(BuildQuerySettingManager.class).to(DefaultBuildQuerySettingManager.class); bind(PullRequestAssignmentManager.class).to(DefaultPullRequestAssignmentManager.class); bind(SshKeyManager.class).to(DefaultSshKeyManager.class); bind(WebHookManager.class); contribute(ImplementationProvider.class, new ImplementationProvider() { @Override public Class<?> getAbstractClass() { return JobExecutor.class; } @Override public Collection<Class<?>> getImplementations() { return Sets.newHashSet(AutoDiscoveredJobExecutor.class); } }); contribute(CodePullAuthorizationSource.class, DefaultJobManager.class); bind(IndexManager.class).to(DefaultIndexManager.class); bind(SearchManager.class).to(DefaultSearchManager.class); bind(EntityValidator.class).to(DefaultEntityValidator.class); bind(ExecutorService.class).toProvider(new Provider<ExecutorService>() { @Override public ExecutorService get() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()) { @Override public void execute(Runnable command) { try { super.execute(SecurityUtils.inheritSubject(command)); } catch (RejectedExecutionException e) { if (!isShutdown()) throw ExceptionUtils.unchecked(e); } } }; } }).in(Singleton.class); bind(ForkJoinPool.class).toInstance(new ForkJoinPool() { @Override public ForkJoinTask<?> submit(Runnable task) { return super.submit(SecurityUtils.inheritSubject(task)); } @Override public void execute(Runnable task) { super.execute(SecurityUtils.inheritSubject(task)); } @Override public <T> ForkJoinTask<T> submit(Callable<T> task) { return super.submit(SecurityUtils.inheritSubject(task)); } @Override public <T> ForkJoinTask<T> submit(Runnable task, T result) { return super.submit(SecurityUtils.inheritSubject(task), result); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return super.invokeAny(SecurityUtils.inheritSubject(tasks)); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return super.invokeAny(SecurityUtils.inheritSubject(tasks), timeout, unit); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return super.invokeAll(SecurityUtils.inheritSubject(tasks), timeout, unit); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) { return super.invokeAll(SecurityUtils.inheritSubject(tasks)); } }); } private void configureSsh() { bind(KeyPairProvider.class).to(DefaultKeyPairProvider.class); bind(SshAuthenticator.class).to(DefaultSshAuthenticator.class); bind(SshServerLauncher.class); } private void configureSecurity() { contributeFromPackage(Realm.class, AbstractAuthorizingRealm.class); bind(RememberMeManager.class).to(DefaultRememberMeManager.class); bind(WebSecurityManager.class).to(DefaultWebSecurityManager.class); bind(FilterChainResolver.class).to(DefaultFilterChainResolver.class); bind(BasicAuthenticationFilter.class); bind(BearerAuthenticationFilter.class); bind(PasswordService.class).to(DefaultPasswordService.class); bind(ShiroFilter.class); install(new ShiroAopModule()); contribute(FilterChainConfigurator.class, new FilterChainConfigurator() { @Override public void configure(FilterChainManager filterChainManager) { filterChainManager.createChain("/**/info/refs", "noSessionCreation, authcBasic, authcBearer"); filterChainManager.createChain("/**/git-upload-pack", "noSessionCreation, authcBasic, authcBearer"); filterChainManager.createChain("/**/git-receive-pack", "noSessionCreation, authcBasic, authcBearer"); } }); contributeFromPackage(Authenticator.class, Authenticator.class); } private void configureGit() { contribute(ObjectMapperConfigurator.class, GitObjectMapperConfigurator.class); bind(GitConfig.class).toProvider(GitConfigProvider.class); bind(GitFilter.class); bind(GitPreReceiveCallback.class); bind(GitPostReceiveCallback.class); contribute(SshCommandCreator.class, GitSshCommandCreator.class); } private void configureRestServices() { bind(ResourceConfig.class).toProvider(ResourceConfigProvider.class).in(Singleton.class); bind(ServletContainer.class).to(DefaultServletContainer.class); contribute(FilterChainConfigurator.class, new FilterChainConfigurator() { @Override public void configure(FilterChainManager filterChainManager) { filterChainManager.createChain("/rest/**", "noSessionCreation, authcBasic"); } }); contribute(JerseyConfigurator.class, new JerseyConfigurator() { @Override public void configure(ResourceConfig resourceConfig) { resourceConfig.packages(RestConstants.class.getPackage().getName()); } }); } private void configureWeb() { bind(WicketServlet.class).to(DefaultWicketServlet.class); bind(WicketFilter.class).to(DefaultWicketFilter.class); bind(WebSocketPolicy.class).toProvider(WebSocketPolicyProvider.class); bind(EditSupportRegistry.class).to(DefaultEditSupportRegistry.class); bind(WebSocketManager.class).to(DefaultWebSocketManager.class); contributeFromPackage(EditSupport.class, EditSupport.class); bind(org.apache.wicket.protocol.http.WebApplication.class).to(WebApplication.class); bind(Application.class).to(WebApplication.class); bind(AvatarManager.class).to(DefaultAvatarManager.class); bind(WebSocketManager.class).to(DefaultWebSocketManager.class); contributeFromPackage(EditSupport.class, EditSupportLocator.class); contribute(WebApplicationConfigurator.class, new WebApplicationConfigurator() { @Override public void configure(org.apache.wicket.protocol.http.WebApplication application) { application.mount(new DynamicPathPageMapper("/test", TestPage.class)); } }); bind(CommitIndexedBroadcaster.class); contributeFromPackage(DiffRenderer.class, DiffRenderer.class); contributeFromPackage(BlobRendererContribution.class, BlobRendererContribution.class); contribute(Extension.class, new EmojiExtension()); contribute(Extension.class, new SourcePositionTrackExtension()); contributeFromPackage(MarkdownProcessor.class, MarkdownProcessor.class); contribute(ResourcePackScopeContribution.class, new ResourcePackScopeContribution() { @Override public Collection<Class<?>> getResourcePackScopes() { return Lists.newArrayList(WebApplication.class); } }); contribute(ExpectedExceptionContribution.class, new ExpectedExceptionContribution() { @SuppressWarnings("unchecked") @Override public Collection<Class<? extends Exception>> getExpectedExceptionClasses() { return Sets.newHashSet(ConstraintViolationException.class, EntityNotFoundException.class, ObjectNotFoundException.class, StaleStateException.class, UnauthorizedException.class, GeneralException.class, PageExpiredException.class, StalePageException.class); } }); bind(UrlManager.class).to(DefaultUrlManager.class); bind(CodeCommentEventBroadcaster.class); bind(PullRequestEventBroadcaster.class); bind(IssueEventBroadcaster.class); bind(BuildEventBroadcaster.class); bind(TaskButton.TaskFutureManager.class); bind(UICustomization.class).toInstance(new DefaultUICustomization()); } private void configureBuild() { contribute(ScriptContribution.class, new ScriptContribution() { @Override public GroovyScript getScript() { GroovyScript script = new GroovyScript(); script.setName("determine-build-failure-investigator"); script.setContent(Lists.newArrayList("io.onedev.server.util.script.ScriptContribution.determineBuildFailureInvestigator()")); return script; } }); contribute(ScriptContribution.class, new ScriptContribution() { @Override public GroovyScript getScript() { GroovyScript script = new GroovyScript(); script.setName("get-build-number"); script.setContent(Lists.newArrayList("io.onedev.server.util.script.ScriptContribution.getBuildNumber()")); return script; } }); } private void configurePersistence() { contribute(ObjectMapperConfigurator.class, HibernateObjectMapperConfigurator.class); // Use an optional binding here in case our client does not like to // start persist service provided by this plugin bind(Interceptor.class).to(HibernateInterceptor.class); bind(PhysicalNamingStrategy.class).toInstance(new PrefixedNamingStrategy("o_")); bind(SessionManager.class).to(DefaultSessionManager.class); bind(TransactionManager.class).to(DefaultTransactionManager.class); bind(IdManager.class).to(DefaultIdManager.class); bind(Dao.class).to(DefaultDao.class); TransactionInterceptor transactionInterceptor = new TransactionInterceptor(); requestInjection(transactionInterceptor); bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() { @Override public boolean matches(AnnotatedElement element) { return element.isAnnotationPresent(Transactional.class) && !((Method) element).isSynthetic(); } }, transactionInterceptor); SessionInterceptor sessionInterceptor = new SessionInterceptor(); requestInjection(sessionInterceptor); bindInterceptor(Matchers.any(), new AbstractMatcher<AnnotatedElement>() { @Override public boolean matches(AnnotatedElement element) { return element.isAnnotationPresent(Sessional.class) && !((Method) element).isSynthetic(); } }, sessionInterceptor); contributeFromPackage(LogInstruction.class, LogInstruction.class); contribute(PersistListener.class, new PersistListener() { @Override public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { return false; } @Override public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { return false; } @Override public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException { return false; } @Override public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { } }); bind(XStream.class).toProvider(new com.google.inject.Provider<XStream>() { @SuppressWarnings("rawtypes") @Override public XStream get() { ReflectionProvider reflectionProvider = JVM.newReflectionProvider(); XStream xstream = new XStream(reflectionProvider) { @Override protected MapperWrapper wrapMapper(MapperWrapper next) { return new MapperWrapper(next) { @Override public boolean shouldSerializeMember(Class definedIn, String fieldName) { Field field = reflectionProvider.getField(definedIn, fieldName); return field.getAnnotation(XStreamOmitField.class) == null && field.getAnnotation(Transient.class) == null && field.getAnnotation(OneToMany.class) == null && field.getAnnotation(Version.class) == null; } @Override public String serializedClass(Class type) { if (type == null) return super.serializedClass(type); else if (type == PersistentBag.class) return super.serializedClass(ArrayList.class); else if (type.getName().contains("$HibernateProxy$")) return StringUtils.substringBefore(type.getName(), "$HibernateProxy$"); else return super.serializedClass(type); } }; } }; XStream.setupDefaultSecurity(xstream); xstream.allowTypesByWildcard(new String[] {"io.onedev.**"}); // register NullConverter as highest; otherwise NPE when unmarshal a map // containing an entry with value set to null. xstream.registerConverter(new NullConverter(), XStream.PRIORITY_VERY_HIGH); xstream.registerConverter(new StringConverter(), XStream.PRIORITY_VERY_HIGH); xstream.registerConverter(new VersionedDocumentConverter(), XStream.PRIORITY_VERY_HIGH); xstream.registerConverter(new HibernateProxyConverter(), XStream.PRIORITY_VERY_HIGH); xstream.registerConverter(new CollectionConverter(xstream.getMapper()), XStream.PRIORITY_VERY_HIGH); xstream.registerConverter(new MapConverter(xstream.getMapper()), XStream.PRIORITY_VERY_HIGH); xstream.registerConverter(new ISO8601DateConverter(), XStream.PRIORITY_VERY_HIGH); xstream.registerConverter(new ISO8601SqlTimestampConverter(), XStream.PRIORITY_VERY_HIGH); xstream.registerConverter(new ReflectionConverter(xstream.getMapper(), xstream.getReflectionProvider()), XStream.PRIORITY_VERY_LOW); xstream.autodetectAnnotations(true); return xstream; } }).in(Singleton.class); if (Bootstrap.command != null) { if (RestoreDatabase.COMMAND.equals(Bootstrap.command.getName())) bind(PersistManager.class).to(RestoreDatabase.class); else if (ApplyDatabaseConstraints.COMMAND.equals(Bootstrap.command.getName())) bind(PersistManager.class).to(ApplyDatabaseConstraints.class); else if (BackupDatabase.COMMAND.equals(Bootstrap.command.getName())) bind(PersistManager.class).to(BackupDatabase.class); else if (CheckDataVersion.COMMAND.equals(Bootstrap.command.getName())) bind(PersistManager.class).to(CheckDataVersion.class); else if (Upgrade.COMMAND.equals(Bootstrap.command.getName())) bind(PersistManager.class).to(Upgrade.class); else if (CleanDatabase.COMMAND.equals(Bootstrap.command.getName())) bind(PersistManager.class).to(CleanDatabase.class); else if (ResetAdminPassword.COMMAND.equals(Bootstrap.command.getName())) bind(PersistManager.class).to(ResetAdminPassword.class); else throw new RuntimeException("Unrecognized command: " + Bootstrap.command.getName()); } else { bind(PersistManager.class).to(DefaultPersistManager.class); } } @Override protected Class<? extends AbstractPlugin> getPluginClass() { return OneDev.class; } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_1893_0
crossvul-java_data_bad_42_6
package org.bouncycastle.pqc.crypto.test; import java.io.IOException; import java.security.SecureRandom; import junit.framework.TestCase; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.pqc.crypto.xmss.XMSSMT; import org.bouncycastle.pqc.crypto.xmss.XMSSMTParameters; import org.bouncycastle.util.Arrays; /** * Test cases for XMSSMTPrivateKey class. */ public class XMSSMTPrivateKeyTest extends TestCase { public void testPrivateKeyParsingSHA256() throws IOException, ClassNotFoundException { XMSSMTParameters params = new XMSSMTParameters(20, 10, new SHA256Digest()); XMSSMT mt = new XMSSMT(params, new SecureRandom()); mt.generateKeys(); byte[] privateKey = mt.exportPrivateKey(); byte[] publicKey = mt.exportPublicKey(); mt.importState(privateKey, publicKey); assertTrue(Arrays.areEqual(privateKey, mt.exportPrivateKey())); } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_42_6
crossvul-java_data_good_280_1
package com.fasterxml.jackson.databind.deser; import java.lang.reflect.Type; import java.util.*; import com.fasterxml.jackson.annotation.ObjectIdGenerator; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.fasterxml.jackson.annotation.ObjectIdResolver; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig; import com.fasterxml.jackson.databind.deser.impl.*; import com.fasterxml.jackson.databind.deser.std.ThrowableDeserializer; import com.fasterxml.jackson.databind.introspect.*; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import com.fasterxml.jackson.databind.util.ArrayBuilders; import com.fasterxml.jackson.databind.util.ClassUtil; import com.fasterxml.jackson.databind.util.SimpleBeanPropertyDefinition; /** * Concrete deserializer factory class that adds full Bean deserializer * construction logic using class introspection. * Note that factories specifically do not implement any form of caching: * aside from configuration they are stateless; caching is implemented * by other components. *<p> * Instances of this class are fully immutable as all configuration is * done by using "fluent factories" (methods that construct new factory * instances with different configuration, instead of modifying instance). */ public class BeanDeserializerFactory extends BasicDeserializerFactory implements java.io.Serializable // since 2.1 { private static final long serialVersionUID = 1; /** * Signature of <b>Throwable.initCause</b> method. */ private final static Class<?>[] INIT_CAUSE_PARAMS = new Class<?>[] { Throwable.class }; private final static Class<?>[] NO_VIEWS = new Class<?>[0]; /** * Set of well-known "nasty classes", deserialization of which is considered dangerous * and should (and is) prevented by default. */ private final static Set<String> DEFAULT_NO_DESER_CLASS_NAMES; static { Set<String> s = new HashSet<String>(); // Courtesy of [https://github.com/kantega/notsoserial]: // (and wrt [databind#1599]) s.add("org.apache.commons.collections.functors.InvokerTransformer"); s.add("org.apache.commons.collections.functors.InstantiateTransformer"); s.add("org.apache.commons.collections4.functors.InvokerTransformer"); s.add("org.apache.commons.collections4.functors.InstantiateTransformer"); s.add("org.codehaus.groovy.runtime.ConvertedClosure"); s.add("org.codehaus.groovy.runtime.MethodClosure"); s.add("org.springframework.beans.factory.ObjectFactory"); s.add("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl"); // [databind#1737]; JDK provided s.add("java.util.logging.FileHandler"); s.add("java.rmi.server.UnicastRemoteObject"); // [databind#1737]; 3rd party s.add("org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor"); s.add("org.springframework.beans.factory.config.PropertyPathFactoryBean"); s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource"); s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource"); // [databind#2097]: some 3rd party, one JDK-bundled s.add("org.slf4j.ext.EventData"); s.add("flex.messaging.util.concurrent.AsynchBeansWorkManagerExecutor"); s.add("com.sun.deploy.security.ruleset.DRSHelper"); s.add("org.apache.axis2.jaxws.spi.handler.HandlerResolverImpl"); DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s); } /** * Set of class names of types that are never to be deserialized. */ private Set<String> _cfgIllegalClassNames = DEFAULT_NO_DESER_CLASS_NAMES; /* /********************************************************** /* Life-cycle /********************************************************** */ /** * Globally shareable thread-safe instance which has no additional custom deserializers * registered */ public final static BeanDeserializerFactory instance = new BeanDeserializerFactory( new DeserializerFactoryConfig()); public BeanDeserializerFactory(DeserializerFactoryConfig config) { super(config); } /** * Method used by module registration functionality, to construct a new bean * deserializer factory * with different configuration settings. */ @Override public DeserializerFactory withConfig(DeserializerFactoryConfig config) { if (_factoryConfig == config) { return this; } /* 22-Nov-2010, tatu: Handling of subtypes is tricky if we do immutable-with-copy-ctor; * and we pretty much have to here either choose between losing subtype instance * when registering additional deserializers, or losing deserializers. * Instead, let's actually just throw an error if this method is called when subtype * has not properly overridden this method; this to indicate problem as soon as possible. */ if (getClass() != BeanDeserializerFactory.class) { throw new IllegalStateException("Subtype of BeanDeserializerFactory ("+getClass().getName() +") has not properly overridden method 'withAdditionalDeserializers': can not instantiate subtype with " +"additional deserializer definitions"); } return new BeanDeserializerFactory(config); } /* /********************************************************** /* DeserializerFactory API implementation /********************************************************** */ /** * Method that {@link DeserializerCache}s call to create a new * deserializer for types other than Collections, Maps, arrays and * enums. */ @Override public JsonDeserializer<Object> createBeanDeserializer(DeserializationContext ctxt, JavaType type, BeanDescription beanDesc) throws JsonMappingException { final DeserializationConfig config = ctxt.getConfig(); // We may also have custom overrides: JsonDeserializer<Object> custom = _findCustomBeanDeserializer(type, config, beanDesc); if (custom != null) { return custom; } /* One more thing to check: do we have an exception type * (Throwable or its sub-classes)? If so, need slightly * different handling. */ if (type.isThrowable()) { return buildThrowableDeserializer(ctxt, type, beanDesc); } /* Or, for abstract types, may have alternate means for resolution * (defaulting, materialization) */ if (type.isAbstract()) { // [JACKSON-41] (v1.6): Let's make it possible to materialize abstract types. JavaType concreteType = materializeAbstractType(ctxt, type, beanDesc); if (concreteType != null) { /* important: introspect actual implementation (abstract class or * interface doesn't have constructors, for one) */ beanDesc = config.introspect(concreteType); return buildBeanDeserializer(ctxt, concreteType, beanDesc); } } // Otherwise, may want to check handlers for standard types, from superclass: @SuppressWarnings("unchecked") JsonDeserializer<Object> deser = (JsonDeserializer<Object>) findStdDeserializer(ctxt, type, beanDesc); if (deser != null) { return deser; } // Otherwise: could the class be a Bean class? If not, bail out if (!isPotentialBeanType(type.getRawClass())) { return null; } // For checks like [databind#1599] checkIllegalTypes(ctxt, type, beanDesc); // Use generic bean introspection to build deserializer return buildBeanDeserializer(ctxt, type, beanDesc); } @Override public JsonDeserializer<Object> createBuilderBasedDeserializer( DeserializationContext ctxt, JavaType valueType, BeanDescription beanDesc, Class<?> builderClass) throws JsonMappingException { // First: need a BeanDescription for builder class JavaType builderType = ctxt.constructType(builderClass); BeanDescription builderDesc = ctxt.getConfig().introspectForBuilder(builderType); return buildBuilderBasedDeserializer(ctxt, valueType, builderDesc); } /** * Method called by {@link BeanDeserializerFactory} to see if there might be a standard * deserializer registered for given type. */ protected JsonDeserializer<?> findStdDeserializer(DeserializationContext ctxt, JavaType type, BeanDescription beanDesc) throws JsonMappingException { // note: we do NOT check for custom deserializers here, caller has already // done that JsonDeserializer<?> deser = findDefaultDeserializer(ctxt, type, beanDesc); // Also: better ensure these are post-processable? if (deser != null) { if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { deser = mod.modifyDeserializer(ctxt.getConfig(), beanDesc, deser); } } } return deser; } protected JavaType materializeAbstractType(DeserializationContext ctxt, JavaType type, BeanDescription beanDesc) throws JsonMappingException { final JavaType abstractType = beanDesc.getType(); // [JACKSON-502]: Now it is possible to have multiple resolvers too, // as they are registered via module interface. for (AbstractTypeResolver r : _factoryConfig.abstractTypeResolvers()) { JavaType concrete = r.resolveAbstractType(ctxt.getConfig(), abstractType); if (concrete != null) { return concrete; } } return null; } /* /********************************************************** /* Public construction method beyond DeserializerFactory API: /* can be called from outside as well as overridden by /* sub-classes /********************************************************** */ /** * Method that is to actually build a bean deserializer instance. * All basic sanity checks have been done to know that what we have * may be a valid bean type, and that there are no default simple * deserializers. */ @SuppressWarnings("unchecked") public JsonDeserializer<Object> buildBeanDeserializer(DeserializationContext ctxt, JavaType type, BeanDescription beanDesc) throws JsonMappingException { // First: check what creators we can use, if any ValueInstantiator valueInstantiator; /* 04-Jun-2015, tatu: To work around [databind#636], need to catch the * issue, defer; this seems like a reasonable good place for now. * Note, however, that for non-Bean types (Collections, Maps) this * probably won't work and needs to be added elsewhere. */ try { valueInstantiator = findValueInstantiator(ctxt, beanDesc); } catch (NoClassDefFoundError error) { return new NoClassDefFoundDeserializer<Object>(error); } BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, beanDesc); builder.setValueInstantiator(valueInstantiator); // And then setters for deserializing from JSON Object addBeanProps(ctxt, beanDesc, builder); addObjectIdReader(ctxt, beanDesc, builder); // managed/back reference fields/setters need special handling... first part addReferenceProperties(ctxt, beanDesc, builder); addInjectables(ctxt, beanDesc, builder); final DeserializationConfig config = ctxt.getConfig(); // [JACKSON-440]: update builder now that all information is in? if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { builder = mod.updateBuilder(config, beanDesc, builder); } } JsonDeserializer<?> deserializer; /* 19-Mar-2012, tatu: This check used to be done earlier; but we have to defer * it a bit to collect information on ObjectIdReader, for example. */ if (type.isAbstract() && !valueInstantiator.canInstantiate()) { deserializer = builder.buildAbstract(); } else { deserializer = builder.build(); } // [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built: if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { deserializer = mod.modifyDeserializer(config, beanDesc, deserializer); } } return (JsonDeserializer<Object>) deserializer; } /** * Method for constructing a bean deserializer that uses specified * intermediate Builder for binding data, and construction of the * value instance. * Note that implementation is mostly copied from the regular * BeanDeserializer build method. */ @SuppressWarnings("unchecked") protected JsonDeserializer<Object> buildBuilderBasedDeserializer( DeserializationContext ctxt, JavaType valueType, BeanDescription builderDesc) throws JsonMappingException { // Creators, anyone? (to create builder itself) ValueInstantiator valueInstantiator = findValueInstantiator(ctxt, builderDesc); final DeserializationConfig config = ctxt.getConfig(); BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, builderDesc); builder.setValueInstantiator(valueInstantiator); // And then "with methods" for deserializing from JSON Object addBeanProps(ctxt, builderDesc, builder); addObjectIdReader(ctxt, builderDesc, builder); // managed/back reference fields/setters need special handling... first part addReferenceProperties(ctxt, builderDesc, builder); addInjectables(ctxt, builderDesc, builder); JsonPOJOBuilder.Value builderConfig = builderDesc.findPOJOBuilderConfig(); final String buildMethodName = (builderConfig == null) ? "build" : builderConfig.buildMethodName; // and lastly, find build method to use: AnnotatedMethod buildMethod = builderDesc.findMethod(buildMethodName, null); if (buildMethod != null) { // note: can't yet throw error; may be given build method if (config.canOverrideAccessModifiers()) { ClassUtil.checkAndFixAccess(buildMethod.getMember()); } } builder.setPOJOBuilder(buildMethod, builderConfig); // this may give us more information... if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { builder = mod.updateBuilder(config, builderDesc, builder); } } JsonDeserializer<?> deserializer = builder.buildBuilderBased( valueType, buildMethodName); // [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built: if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { deserializer = mod.modifyDeserializer(config, builderDesc, deserializer); } } return (JsonDeserializer<Object>) deserializer; } protected void addObjectIdReader(DeserializationContext ctxt, BeanDescription beanDesc, BeanDeserializerBuilder builder) throws JsonMappingException { ObjectIdInfo objectIdInfo = beanDesc.getObjectIdInfo(); if (objectIdInfo == null) { return; } Class<?> implClass = objectIdInfo.getGeneratorType(); JavaType idType; SettableBeanProperty idProp; ObjectIdGenerator<?> gen; ObjectIdResolver resolver = ctxt.objectIdResolverInstance(beanDesc.getClassInfo(), objectIdInfo); // Just one special case: Property-based generator is trickier if (implClass == ObjectIdGenerators.PropertyGenerator.class) { // most special one, needs extra work PropertyName propName = objectIdInfo.getPropertyName(); idProp = builder.findProperty(propName); if (idProp == null) { throw new IllegalArgumentException("Invalid Object Id definition for " +beanDesc.getBeanClass().getName()+": can not find property with name '"+propName+"'"); } idType = idProp.getType(); gen = new PropertyBasedObjectIdGenerator(objectIdInfo.getScope()); } else { JavaType type = ctxt.constructType(implClass); idType = ctxt.getTypeFactory().findTypeParameters(type, ObjectIdGenerator.class)[0]; idProp = null; gen = ctxt.objectIdGeneratorInstance(beanDesc.getClassInfo(), objectIdInfo); } // also: unlike with value deserializers, let's just resolve one we need here JsonDeserializer<?> deser = ctxt.findRootValueDeserializer(idType); builder.setObjectIdReader(ObjectIdReader.construct(idType, objectIdInfo.getPropertyName(), gen, deser, idProp, resolver)); } @SuppressWarnings("unchecked") public JsonDeserializer<Object> buildThrowableDeserializer(DeserializationContext ctxt, JavaType type, BeanDescription beanDesc) throws JsonMappingException { final DeserializationConfig config = ctxt.getConfig(); // first: construct like a regular bean deserializer... BeanDeserializerBuilder builder = constructBeanDeserializerBuilder(ctxt, beanDesc); builder.setValueInstantiator(findValueInstantiator(ctxt, beanDesc)); addBeanProps(ctxt, beanDesc, builder); // (and assume there won't be any back references) // But then let's decorate things a bit /* To resolve [JACKSON-95], need to add "initCause" as setter * for exceptions (sub-classes of Throwable). */ AnnotatedMethod am = beanDesc.findMethod("initCause", INIT_CAUSE_PARAMS); if (am != null) { // should never be null SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct(ctxt.getConfig(), am, new PropertyName("cause")); SettableBeanProperty prop = constructSettableProperty(ctxt, beanDesc, propDef, am.getGenericParameterType(0)); if (prop != null) { /* 21-Aug-2011, tatus: We may actually have found 'cause' property * to set (with new 1.9 code)... but let's replace it just in case, * otherwise can end up with odd errors. */ builder.addOrReplaceProperty(prop, true); } } // And also need to ignore "localizedMessage" builder.addIgnorable("localizedMessage"); // [JACKSON-794]: JDK 7 also added "getSuppressed", skip if we have such data: builder.addIgnorable("suppressed"); /* As well as "message": it will be passed via constructor, * as there's no 'setMessage()' method */ builder.addIgnorable("message"); // [JACKSON-440]: update builder now that all information is in? if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { builder = mod.updateBuilder(config, beanDesc, builder); } } JsonDeserializer<?> deserializer = builder.build(); /* At this point it ought to be a BeanDeserializer; if not, must assume * it's some other thing that can handle deserialization ok... */ if (deserializer instanceof BeanDeserializer) { deserializer = new ThrowableDeserializer((BeanDeserializer) deserializer); } // [JACKSON-440]: may have modifier(s) that wants to modify or replace serializer we just built: if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { deserializer = mod.modifyDeserializer(config, beanDesc, deserializer); } } return (JsonDeserializer<Object>) deserializer; } /* /********************************************************** /* Helper methods for Bean deserializer construction, /* overridable by sub-classes /********************************************************** */ /** * Overridable method that constructs a {@link BeanDeserializerBuilder} * which is used to accumulate information needed to create deserializer * instance. */ protected BeanDeserializerBuilder constructBeanDeserializerBuilder(DeserializationContext ctxt, BeanDescription beanDesc) { return new BeanDeserializerBuilder(beanDesc, ctxt.getConfig()); } /** * Method called to figure out settable properties for the * bean deserializer to use. *<p> * Note: designed to be overridable, and effort is made to keep interface * similar between versions. */ protected void addBeanProps(DeserializationContext ctxt, BeanDescription beanDesc, BeanDeserializerBuilder builder) throws JsonMappingException { final SettableBeanProperty[] creatorProps = builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig()); final boolean isConcrete = !beanDesc.getType().isAbstract(); // Things specified as "ok to ignore"? [JACKSON-77] AnnotationIntrospector intr = ctxt.getAnnotationIntrospector(); boolean ignoreAny = false; { Boolean B = intr.findIgnoreUnknownProperties(beanDesc.getClassInfo()); if (B != null) { ignoreAny = B.booleanValue(); builder.setIgnoreUnknownProperties(ignoreAny); } } // Or explicit/implicit definitions? Set<String> ignored = ArrayBuilders.arrayToSet(intr.findPropertiesToIgnore(beanDesc.getClassInfo(), false)); for (String propName : ignored) { builder.addIgnorable(propName); } // Also, do we have a fallback "any" setter? AnnotatedMethod anySetter = beanDesc.findAnySetter(); if (anySetter != null) { builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetter)); } // NOTE: we do NOT add @JsonIgnore'd properties into blocked ones if there's any-setter // Implicit ones via @JsonIgnore and equivalent? if (anySetter == null) { Collection<String> ignored2 = beanDesc.getIgnoredPropertyNames(); if (ignored2 != null) { for (String propName : ignored2) { // allow ignoral of similarly named JSON property, but do not force; // latter means NOT adding this to 'ignored': builder.addIgnorable(propName); } } } final boolean useGettersAsSetters = (ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS) && ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS)); // Ok: let's then filter out property definitions List<BeanPropertyDefinition> propDefs = filterBeanProps(ctxt, beanDesc, builder, beanDesc.findProperties(), ignored); // After which we can let custom code change the set if (_factoryConfig.hasDeserializerModifiers()) { for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) { propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs); } } // At which point we still have all kinds of properties; not all with mutators: for (BeanPropertyDefinition propDef : propDefs) { SettableBeanProperty prop = null; /* 18-Oct-2013, tatu: Although constructor parameters have highest precedence, * we need to do linkage (as per [Issue#318]), and so need to start with * other types, and only then create constructor parameter, if any. */ if (propDef.hasSetter()) { Type propertyType = propDef.getSetter().getGenericParameterType(0); prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType); } else if (propDef.hasField()) { Type propertyType = propDef.getField().getGenericType(); prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType); } else if (useGettersAsSetters && propDef.hasGetter()) { /* As per [JACKSON-88], may also need to consider getters * for Map/Collection properties; but with lowest precedence */ AnnotatedMethod getter = propDef.getGetter(); // should only consider Collections and Maps, for now? Class<?> rawPropertyType = getter.getRawType(); if (Collection.class.isAssignableFrom(rawPropertyType) || Map.class.isAssignableFrom(rawPropertyType)) { prop = constructSetterlessProperty(ctxt, beanDesc, propDef); } } // 25-Sep-2014, tatu: No point in finding constructor parameters for abstract types // (since they are never used anyway) if (isConcrete && propDef.hasConstructorParameter()) { /* [JACKSON-700] If property is passed via constructor parameter, we must * handle things in special way. Not sure what is the most optimal way... * for now, let's just call a (new) method in builder, which does nothing. */ // but let's call a method just to allow custom builders to be aware... final String name = propDef.getName(); CreatorProperty cprop = null; if (creatorProps != null) { for (SettableBeanProperty cp : creatorProps) { if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) { cprop = (CreatorProperty) cp; break; } } } if (cprop == null) { throw ctxt.mappingException("Could not find creator property with name '%s' (in class %s)", name, beanDesc.getBeanClass().getName()); } if (prop != null) { cprop.setFallbackSetter(prop); } prop = cprop; builder.addCreatorProperty(cprop); continue; } if (prop != null) { Class<?>[] views = propDef.findViews(); if (views == null) { // one more twist: if default inclusion disabled, need to force empty set of views if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) { views = NO_VIEWS; } } // one more thing before adding to builder: copy any metadata prop.setViews(views); builder.addProperty(prop); } } } /** * Helper method called to filter out explicit ignored properties, * as well as properties that have "ignorable types". * Note that this will not remove properties that have no * setters. */ protected List<BeanPropertyDefinition> filterBeanProps(DeserializationContext ctxt, BeanDescription beanDesc, BeanDeserializerBuilder builder, List<BeanPropertyDefinition> propDefsIn, Set<String> ignored) throws JsonMappingException { ArrayList<BeanPropertyDefinition> result = new ArrayList<BeanPropertyDefinition>( Math.max(4, propDefsIn.size())); HashMap<Class<?>,Boolean> ignoredTypes = new HashMap<Class<?>,Boolean>(); // These are all valid setters, but we do need to introspect bit more for (BeanPropertyDefinition property : propDefsIn) { String name = property.getName(); if (ignored.contains(name)) { // explicit ignoral using @JsonIgnoreProperties needs to block entries continue; } if (!property.hasConstructorParameter()) { // never skip constructor params Class<?> rawPropertyType = null; if (property.hasSetter()) { rawPropertyType = property.getSetter().getRawParameterType(0); } else if (property.hasField()) { rawPropertyType = property.getField().getRawType(); } // [JACKSON-429] Some types are declared as ignorable as well if ((rawPropertyType != null) && (isIgnorableType(ctxt.getConfig(), beanDesc, rawPropertyType, ignoredTypes))) { // important: make ignorable, to avoid errors if value is actually seen builder.addIgnorable(name); continue; } } result.add(property); } return result; } /** * Method that will find if bean has any managed- or back-reference properties, * and if so add them to bean, to be linked during resolution phase. */ protected void addReferenceProperties(DeserializationContext ctxt, BeanDescription beanDesc, BeanDeserializerBuilder builder) throws JsonMappingException { // and then back references, not necessarily found as regular properties Map<String,AnnotatedMember> refs = beanDesc.findBackReferenceProperties(); if (refs != null) { for (Map.Entry<String, AnnotatedMember> en : refs.entrySet()) { String name = en.getKey(); AnnotatedMember m = en.getValue(); Type genericType; if (m instanceof AnnotatedMethod) { genericType = ((AnnotatedMethod) m).getGenericParameterType(0); } else { genericType = m.getRawType(); } SimpleBeanPropertyDefinition propDef = SimpleBeanPropertyDefinition.construct( ctxt.getConfig(), m); builder.addBackReferenceProperty(name, constructSettableProperty( ctxt, beanDesc, propDef, genericType)); } } } /** * Method called locate all members used for value injection (if any), * constructor {@link com.fasterxml.jackson.databind.deser.impl.ValueInjector} instances, and add them to builder. */ protected void addInjectables(DeserializationContext ctxt, BeanDescription beanDesc, BeanDeserializerBuilder builder) throws JsonMappingException { Map<Object, AnnotatedMember> raw = beanDesc.findInjectables(); if (raw != null) { boolean fixAccess = ctxt.canOverrideAccessModifiers(); for (Map.Entry<Object, AnnotatedMember> entry : raw.entrySet()) { AnnotatedMember m = entry.getValue(); if (fixAccess) { m.fixAccess(); // to ensure we can call it } builder.addInjectable(PropertyName.construct(m.getName()), beanDesc.resolveType(m.getGenericType()), beanDesc.getClassAnnotations(), m, entry.getKey()); } } } /** * Method called to construct fallback {@link SettableAnyProperty} * for handling unknown bean properties, given a method that * has been designated as such setter. */ protected SettableAnyProperty constructAnySetter(DeserializationContext ctxt, BeanDescription beanDesc, AnnotatedMethod setter) throws JsonMappingException { if (ctxt.canOverrideAccessModifiers()) { setter.fixAccess(); // to ensure we can call it } // we know it's a 2-arg method, second arg is the value JavaType type = beanDesc.bindingsForBeanType().resolveType(setter.getGenericParameterType(1)); BeanProperty.Std property = new BeanProperty.Std(PropertyName.construct(setter.getName()), type, null, beanDesc.getClassAnnotations(), setter, PropertyMetadata.STD_OPTIONAL); type = resolveType(ctxt, beanDesc, type, setter); /* AnySetter can be annotated with @JsonClass (etc) just like a * regular setter... so let's see if those are used. * Returns null if no annotations, in which case binding will * be done at a later point. */ JsonDeserializer<Object> deser = findDeserializerFromAnnotation(ctxt, setter); /* Otherwise, method may specify more specific (sub-)class for * value (no need to check if explicit deser was specified): */ type = modifyTypeByAnnotation(ctxt, setter, type); if (deser == null) { deser = type.getValueHandler(); } TypeDeserializer typeDeser = type.getTypeHandler(); return new SettableAnyProperty(property, setter, type, deser, typeDeser); } /** * Method that will construct a regular bean property setter using * the given setter method. * * @return Property constructed, if any; or null to indicate that * there should be no property based on given definitions. */ protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt, BeanDescription beanDesc, BeanPropertyDefinition propDef, Type jdkType) throws JsonMappingException { // need to ensure method is callable (for non-public) AnnotatedMember mutator = propDef.getNonConstructorMutator(); if (ctxt.canOverrideAccessModifiers()) { mutator.fixAccess(); } // note: this works since we know there's exactly one argument for methods JavaType t0 = beanDesc.resolveType(jdkType); BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(), t0, propDef.getWrapperName(), beanDesc.getClassAnnotations(), mutator, propDef.getMetadata()); JavaType type = resolveType(ctxt, beanDesc, t0, mutator); // did type change? if (type != t0) { property = property.withType(type); } /* First: does the Method specify the deserializer to use? * If so, let's use it. */ JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, mutator); type = modifyTypeByAnnotation(ctxt, mutator, type); TypeDeserializer typeDeser = type.getTypeHandler(); SettableBeanProperty prop; if (mutator instanceof AnnotatedMethod) { prop = new MethodProperty(propDef, type, typeDeser, beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator); } else { prop = new FieldProperty(propDef, type, typeDeser, beanDesc.getClassAnnotations(), (AnnotatedField) mutator); } if (propDeser != null) { prop = prop.withValueDeserializer(propDeser); } // [JACKSON-235]: need to retain name of managed forward references: AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType(); if (ref != null && ref.isManagedReference()) { prop.setManagedReferenceName(ref.getName()); } ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo(); if(objectIdInfo != null){ prop.setObjectIdInfo(objectIdInfo); } return prop; } /** * Method that will construct a regular bean property setter using * the given setter method. */ protected SettableBeanProperty constructSetterlessProperty(DeserializationContext ctxt, BeanDescription beanDesc, BeanPropertyDefinition propDef) throws JsonMappingException { final AnnotatedMethod getter = propDef.getGetter(); // need to ensure it is callable now: if (ctxt.canOverrideAccessModifiers()) { getter.fixAccess(); } /* 26-Jan-2012, tatu: Alas, this complication is still needed to handle * (or at least work around) local type declarations... */ JavaType type = getter.getType(beanDesc.bindingsForBeanType()); /* First: does the Method specify the deserializer to use? * If so, let's use it. */ JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, getter); type = modifyTypeByAnnotation(ctxt, getter, type); // As per [Issue#501], need full resolution: type = resolveType(ctxt, beanDesc, type, getter); TypeDeserializer typeDeser = type.getTypeHandler(); SettableBeanProperty prop = new SetterlessProperty(propDef, type, typeDeser, beanDesc.getClassAnnotations(), getter); if (propDeser != null) { prop = prop.withValueDeserializer(propDeser); } return prop; } /* /********************************************************** /* Helper methods for Bean deserializer, other /********************************************************** */ /** * Helper method used to skip processing for types that we know * can not be (i.e. are never consider to be) beans: * things like primitives, Arrays, Enums, and proxy types. *<p> * Note that usually we shouldn't really be getting these sort of * types anyway; but better safe than sorry. */ protected boolean isPotentialBeanType(Class<?> type) { String typeStr = ClassUtil.canBeABeanType(type); if (typeStr != null) { throw new IllegalArgumentException("Can not deserialize Class "+type.getName()+" (of type "+typeStr+") as a Bean"); } if (ClassUtil.isProxyType(type)) { throw new IllegalArgumentException("Can not deserialize Proxy class "+type.getName()+" as a Bean"); } /* also: can't deserialize some local classes: static are ok; in-method not; * and with [JACKSON-594], other non-static inner classes are ok */ typeStr = ClassUtil.isLocalType(type, true); if (typeStr != null) { throw new IllegalArgumentException("Can not deserialize Class "+type.getName()+" (of type "+typeStr+") as a Bean"); } return true; } /** * Helper method that will check whether given raw type is marked as always ignorable * (for purpose of ignoring properties with type) */ protected boolean isIgnorableType(DeserializationConfig config, BeanDescription beanDesc, Class<?> type, Map<Class<?>,Boolean> ignoredTypes) { Boolean status = ignoredTypes.get(type); if (status != null) { return status.booleanValue(); } BeanDescription desc = config.introspectClassAnnotations(type); status = config.getAnnotationIntrospector().isIgnorableType(desc.getClassInfo()); // We default to 'false', i.e. not ignorable return (status == null) ? false : status.booleanValue(); } private void checkIllegalTypes(DeserializationContext ctxt, JavaType type, BeanDescription beanDesc) throws JsonMappingException { // There are certain nasty classes that could cause problems, mostly // via default typing -- catch them here. String full = type.getRawClass().getName(); if (_cfgIllegalClassNames.contains(full)) { String message = String.format("Illegal type (%s) to deserialize: prevented for security reasons", full); throw ctxt.mappingException("Invalid type definition for type %s: %s", beanDesc, message); } } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_280_1
crossvul-java_data_good_5761_2
/** * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc. and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. **/ package org.ajax4jsf.resource; /** * A marker interface, used to indicate that the class implementing this interfaces is cleared for deserialisation by * the LookAheadObjectInputStream * * @author <a href="http://community.jboss.org/people/bleathem">Brian Leathem</a> */ public interface SerializableResource extends java.io.Serializable { }
./CrossVul/dataset_final_sorted/CWE-502/java/good_5761_2
crossvul-java_data_good_1893_2
package io.onedev.server.web.component.markdown; import java.io.IOException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.SerializationUtils; import org.apache.wicket.util.crypt.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.onedev.server.persistence.annotation.Sessional; @SuppressWarnings("serial") @Singleton public class AttachmentUploadServlet extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(AttachmentUploadServlet.class); @Sessional @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = URLDecoder.decode(request.getHeader("File-Name"), StandardCharsets.UTF_8.name()); AttachmentSupport attachmentSuppport = (AttachmentSupport) SerializationUtils .deserialize(Base64.decodeBase64(request.getHeader("Attachment-Support"))); try { String attachmentName = attachmentSuppport.saveAttachment(fileName, request.getInputStream()); response.getWriter().print(URLEncoder.encode(attachmentName, StandardCharsets.UTF_8.name())); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { logger.error("Error uploading attachment.", e); if (e.getMessage() != null) response.getWriter().print(e.getMessage()); else response.getWriter().print("Internal server error"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_1893_2
crossvul-java_data_bad_43_0
package org.bouncycastle.pqc.crypto.xmss; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InvalidClassException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import org.bouncycastle.crypto.Digest; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; /** * Utils for XMSS implementation. */ public class XMSSUtil { /** * Calculates the logarithm base 2 for a given Integer. * * @param n Number. * @return Logarithm to base 2 of {@code n}. */ public static int log2(int n) { int log = 0; while ((n >>= 1) != 0) { log++; } return log; } /** * Convert int/long to n-byte array. * * @param value int/long value. * @param sizeInByte Size of byte array in byte. * @return int/long as big-endian byte array of size {@code sizeInByte}. */ public static byte[] toBytesBigEndian(long value, int sizeInByte) { byte[] out = new byte[sizeInByte]; for (int i = (sizeInByte - 1); i >= 0; i--) { out[i] = (byte)value; value >>>= 8; } return out; } /* * Copy long to byte array in big-endian at specific offset. */ public static void longToBigEndian(long value, byte[] in, int offset) { if (in == null) { throw new NullPointerException("in == null"); } if ((in.length - offset) < 8) { throw new IllegalArgumentException("not enough space in array"); } in[offset] = (byte)((value >> 56) & 0xff); in[offset + 1] = (byte)((value >> 48) & 0xff); in[offset + 2] = (byte)((value >> 40) & 0xff); in[offset + 3] = (byte)((value >> 32) & 0xff); in[offset + 4] = (byte)((value >> 24) & 0xff); in[offset + 5] = (byte)((value >> 16) & 0xff); in[offset + 6] = (byte)((value >> 8) & 0xff); in[offset + 7] = (byte)((value) & 0xff); } /* * Generic convert from big endian byte array to long. */ public static long bytesToXBigEndian(byte[] in, int offset, int size) { if (in == null) { throw new NullPointerException("in == null"); } long res = 0; for (int i = offset; i < (offset + size); i++) { res = (res << 8) | (in[i] & 0xff); } return res; } /** * Clone a byte array. * * @param in byte array. * @return Copy of byte array. */ public static byte[] cloneArray(byte[] in) { if (in == null) { throw new NullPointerException("in == null"); } byte[] out = new byte[in.length]; for (int i = 0; i < in.length; i++) { out[i] = in[i]; } return out; } /** * Clone a 2d byte array. * * @param in 2d byte array. * @return Copy of 2d byte array. */ public static byte[][] cloneArray(byte[][] in) { if (hasNullPointer(in)) { throw new NullPointerException("in has null pointers"); } byte[][] out = new byte[in.length][]; for (int i = 0; i < in.length; i++) { out[i] = new byte[in[i].length]; for (int j = 0; j < in[i].length; j++) { out[i][j] = in[i][j]; } } return out; } /** * Compares two 2d-byte arrays. * * @param a 2d-byte array 1. * @param b 2d-byte array 2. * @return true if all values in 2d-byte array are equal false else. */ public static boolean areEqual(byte[][] a, byte[][] b) { if (hasNullPointer(a) || hasNullPointer(b)) { throw new NullPointerException("a or b == null"); } for (int i = 0; i < a.length; i++) { if (!Arrays.areEqual(a[i], b[i])) { return false; } } return true; } /** * Dump content of 2d byte array. * * @param x byte array. */ public static void dumpByteArray(byte[][] x) { if (hasNullPointer(x)) { throw new NullPointerException("x has null pointers"); } for (int i = 0; i < x.length; i++) { System.out.println(Hex.toHexString(x[i])); } } /** * Checks whether 2d byte array has null pointers. * * @param in 2d byte array. * @return true if at least one null pointer is found false else. */ public static boolean hasNullPointer(byte[][] in) { if (in == null) { return true; } for (int i = 0; i < in.length; i++) { if (in[i] == null) { return true; } } return false; } /** * Copy src byte array to dst byte array at offset. * * @param dst Destination. * @param src Source. * @param offset Destination offset. */ public static void copyBytesAtOffset(byte[] dst, byte[] src, int offset) { if (dst == null) { throw new NullPointerException("dst == null"); } if (src == null) { throw new NullPointerException("src == null"); } if (offset < 0) { throw new IllegalArgumentException("offset hast to be >= 0"); } if ((src.length + offset) > dst.length) { throw new IllegalArgumentException("src length + offset must not be greater than size of destination"); } for (int i = 0; i < src.length; i++) { dst[offset + i] = src[i]; } } /** * Copy length bytes at position offset from src. * * @param src Source byte array. * @param offset Offset in source byte array. * @param length Length of bytes to copy. * @return New byte array. */ public static byte[] extractBytesAtOffset(byte[] src, int offset, int length) { if (src == null) { throw new NullPointerException("src == null"); } if (offset < 0) { throw new IllegalArgumentException("offset hast to be >= 0"); } if (length < 0) { throw new IllegalArgumentException("length hast to be >= 0"); } if ((offset + length) > src.length) { throw new IllegalArgumentException("offset + length must not be greater then size of source array"); } byte[] out = new byte[length]; for (int i = 0; i < out.length; i++) { out[i] = src[offset + i]; } return out; } /** * Check whether an index is valid or not. * * @param height Height of binary tree. * @param index Index to validate. * @return true if index is valid false else. */ public static boolean isIndexValid(int height, long index) { if (index < 0) { throw new IllegalStateException("index must not be negative"); } return index < (1L << height); } /** * Determine digest size of digest. * * @param digest Digest. * @return Digest size. */ public static int getDigestSize(Digest digest) { if (digest == null) { throw new NullPointerException("digest == null"); } String algorithmName = digest.getAlgorithmName(); if (algorithmName.equals("SHAKE128")) { return 32; } if (algorithmName.equals("SHAKE256")) { return 64; } return digest.getDigestSize(); } public static long getTreeIndex(long index, int xmssTreeHeight) { return index >> xmssTreeHeight; } public static int getLeafIndex(long index, int xmssTreeHeight) { return (int)(index & ((1L << xmssTreeHeight) - 1L)); } public static byte[] serialize(Object obj) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(obj); oos.flush(); return out.toByteArray(); } public static Object deserialize(byte[] data, final Class clazz) throws IOException, ClassNotFoundException { ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new CheckingStream(clazz, in); Object obj = is.readObject(); if (is.available() != 0) { throw new IOException("unexpected data found at end of ObjectInputStream"); } // you'd hope this would always succeed! if (clazz.isInstance(obj)) { return obj; } else { throw new IOException("unexpected class found in ObjectInputStream"); } } public static int calculateTau(int index, int height) { int tau = 0; for (int i = 0; i < height; i++) { if (((index >> i) & 1) == 0) { tau = i; break; } } return tau; } public static boolean isNewBDSInitNeeded(long globalIndex, int xmssHeight, int layer) { if (globalIndex == 0) { return false; } return (globalIndex % (long)Math.pow((1 << xmssHeight), layer + 1) == 0) ? true : false; } public static boolean isNewAuthenticationPathNeeded(long globalIndex, int xmssHeight, int layer) { if (globalIndex == 0) { return false; } return ((globalIndex + 1) % (long)Math.pow((1 << xmssHeight), layer) == 0) ? true : false; } private static class CheckingStream extends ObjectInputStream { private final Class mainClass; private boolean found = false; CheckingStream(Class mainClass, InputStream in) throws IOException { super(in); this.mainClass = mainClass; } protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (!found) { if (!desc.getName().equals(mainClass.getName())) { throw new InvalidClassException( "unexpected class: ", desc.getName()); } else { found = true; } } return super.resolveClass(desc); } } }
./CrossVul/dataset_final_sorted/CWE-502/java/bad_43_0
crossvul-java_data_good_590_3
/* * Copyright 2017-present Facebook, 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.facebook.buck.cli; import static org.hamcrest.junit.MatcherAssert.assertThat; import static org.junit.Assume.assumeTrue; import com.facebook.buck.apple.AppleNativeIntegrationTestUtils; import com.facebook.buck.apple.toolchain.ApplePlatform; import com.facebook.buck.testutil.ProcessResult; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestContext; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.NamedTemporaryFile; import java.io.FileOutputStream; import java.io.IOException; import java.io.InvalidClassException; import java.io.ObjectOutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class ParserCacheCommandIntegrationTest { @Rule public TemporaryPaths tmp = new TemporaryPaths(); @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testSaveAndLoad() throws IOException { assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "parser_with_cell", tmp); workspace.setUp(); // Warm the parser cache. TestContext context = new TestContext(); ProcessResult runBuckResult = workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); runBuckResult.assertSuccess(); assertThat( runBuckResult.getStdout(), Matchers.containsString( "//Apps:TestAppsLibrary\n" + "//Libraries/Dep1:Dep1_1\n" + "//Libraries/Dep1:Dep1_2\n" + "bar//Dep2:Dep2")); // Save the parser cache to a file. NamedTemporaryFile tempFile = new NamedTemporaryFile("parser_data", null); runBuckResult = workspace.runBuckdCommand(context, "parser-cache", "--save", tempFile.get().toString()); runBuckResult.assertSuccess(); // Write an empty content to Apps/BUCK. Path path = tmp.getRoot().resolve("Apps/BUCK"); byte[] data = {}; Files.write(path, data); context = new TestContext(); // Load the parser cache to a new buckd context. runBuckResult = workspace.runBuckdCommand(context, "parser-cache", "--load", tempFile.get().toString()); runBuckResult.assertSuccess(); // Perform the query again. If we didn't load the parser cache, this call would fail because // Apps/BUCK is empty. runBuckResult = workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); runBuckResult.assertSuccess(); assertThat( runBuckResult.getStdout(), Matchers.containsString( "//Apps:TestAppsLibrary\n" + "//Libraries/Dep1:Dep1_1\n" + "//Libraries/Dep1:Dep1_2\n" + "bar//Dep2:Dep2")); } @Test public void testInvalidate() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "parser_with_cell", tmp); workspace.setUp(); // Warm the parser cache. TestContext context = new TestContext(); ProcessResult runBuckResult = workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); runBuckResult.assertSuccess(); assertThat( runBuckResult.getStdout(), Matchers.containsString( "//Apps:TestAppsLibrary\n" + "//Libraries/Dep1:Dep1_1\n" + "//Libraries/Dep1:Dep1_2\n" + "bar//Dep2:Dep2")); // Save the parser cache to a file. NamedTemporaryFile tempFile = new NamedTemporaryFile("parser_data", null); runBuckResult = workspace.runBuckdCommand(context, "parser-cache", "--save", tempFile.get().toString()); runBuckResult.assertSuccess(); // Write an empty content to Apps/BUCK. Path path = tmp.getRoot().resolve("Apps/BUCK"); byte[] data = {}; Files.write(path, data); // Write an empty content to Apps/BUCK. Path invalidationJsonPath = tmp.getRoot().resolve("invalidation-data.json"); String jsonData = "[{\"path\":\"Apps/BUCK\",\"status\":\"M\"}]"; Files.write(invalidationJsonPath, jsonData.getBytes(StandardCharsets.UTF_8)); context = new TestContext(); // Load the parser cache to a new buckd context. runBuckResult = workspace.runBuckdCommand( context, "parser-cache", "--load", tempFile.get().toString(), "--changes", invalidationJsonPath.toString()); runBuckResult.assertSuccess(); // Perform the query again. try { workspace.runBuckdCommand(context, "query", "deps(//Apps:TestAppsLibrary)"); } catch (HumanReadableException e) { assertThat( e.getMessage(), Matchers.containsString("//Apps:TestAppsLibrary could not be found")); } } @Test public void testInvalidData() throws IOException { Map<String, String> invalidData = new HashMap(); invalidData.put("foo", "bar"); NamedTemporaryFile tempFile = new NamedTemporaryFile("invalid_parser_data", null); try (FileOutputStream fos = new FileOutputStream(tempFile.get().toString()); ZipOutputStream zipos = new ZipOutputStream(fos)) { zipos.putNextEntry(new ZipEntry("parser_data")); try (ObjectOutputStream oos = new ObjectOutputStream(zipos)) { oos.writeObject(invalidData); } } ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "parser_with_cell", tmp); workspace.setUp(); // Load the invalid parser cache data. thrown.expect(InvalidClassException.class); thrown.expectMessage("Can't deserialize this class"); workspace.runBuckCommand("parser-cache", "--load", tempFile.get().toString()); } }
./CrossVul/dataset_final_sorted/CWE-502/java/good_590_3
crossvul-java_data_good_2139_0
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.jboss.netty.handler.ssl; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelDownstreamHandler; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.DefaultChannelFuture; import org.jboss.netty.channel.DownstreamMessageEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.frame.FrameDecoder; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.Timeout; import org.jboss.netty.util.Timer; import org.jboss.netty.util.TimerTask; import org.jboss.netty.util.internal.DetectionUtil; import org.jboss.netty.util.internal.NonReentrantLock; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.DatagramChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.regex.Pattern; import static org.jboss.netty.channel.Channels.*; /** * Adds <a href="http://en.wikipedia.org/wiki/Transport_Layer_Security">SSL * &middot; TLS</a> and StartTLS support to a {@link Channel}. Please refer * to the <strong>"SecureChat"</strong> example in the distribution or the web * site for the detailed usage. * * <h3>Beginning the handshake</h3> * <p> * You must make sure not to write a message while the * {@linkplain #handshake() handshake} is in progress unless you are * renegotiating. You will be notified by the {@link ChannelFuture} which is * returned by the {@link #handshake()} method when the handshake * process succeeds or fails. * * <h3>Handshake</h3> * <p> * If {@link #isIssueHandshake()} is {@code false} * (default) you will need to take care of calling {@link #handshake()} by your own. In most * situations were {@link SslHandler} is used in 'client mode' you want to issue a handshake once * the connection was established. if {@link #setIssueHandshake(boolean)} is set to {@code true} * you don't need to worry about this as the {@link SslHandler} will take care of it. * <p> * * <h3>Renegotiation</h3> * <p> * If {@link #isEnableRenegotiation() enableRenegotiation} is {@code true} * (default) and the initial handshake has been done successfully, you can call * {@link #handshake()} to trigger the renegotiation. * <p> * If {@link #isEnableRenegotiation() enableRenegotiation} is {@code false}, * an attempt to trigger renegotiation will result in the connection closure. * <p> * Please note that TLS renegotiation had a security issue before. If your * runtime environment did not fix it, please make sure to disable TLS * renegotiation by calling {@link #setEnableRenegotiation(boolean)} with * {@code false}. For more information, please refer to the following documents: * <ul> * <li><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3555">CVE-2009-3555</a></li> * <li><a href="http://www.ietf.org/rfc/rfc5746.txt">RFC5746</a></li> * <li><a href="http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html">Phased * Approach to Fixing the TLS Renegotiation Issue</a></li> * </ul> * * <h3>Closing the session</h3> * <p> * To close the SSL session, the {@link #close()} method should be * called to send the {@code close_notify} message to the remote peer. One * exception is when you close the {@link Channel} - {@link SslHandler} * intercepts the close request and send the {@code close_notify} message * before the channel closure automatically. Once the SSL session is closed, * it is not reusable, and consequently you should create a new * {@link SslHandler} with a new {@link SSLEngine} as explained in the * following section. * * <h3>Restarting the session</h3> * <p> * To restart the SSL session, you must remove the existing closed * {@link SslHandler} from the {@link ChannelPipeline}, insert a new * {@link SslHandler} with a new {@link SSLEngine} into the pipeline, * and start the handshake process as described in the first section. * * <h3>Implementing StartTLS</h3> * <p> * <a href="http://en.wikipedia.org/wiki/STARTTLS">StartTLS</a> is the * communication pattern that secures the wire in the middle of the plaintext * connection. Please note that it is different from SSL &middot; TLS, that * secures the wire from the beginning of the connection. Typically, StartTLS * is composed of three steps: * <ol> * <li>Client sends a StartTLS request to server.</li> * <li>Server sends a StartTLS response to client.</li> * <li>Client begins SSL handshake.</li> * </ol> * If you implement a server, you need to: * <ol> * <li>create a new {@link SslHandler} instance with {@code startTls} flag set * to {@code true},</li> * <li>insert the {@link SslHandler} to the {@link ChannelPipeline}, and</li> * <li>write a StartTLS response.</li> * </ol> * Please note that you must insert {@link SslHandler} <em>before</em> sending * the StartTLS response. Otherwise the client can send begin SSL handshake * before {@link SslHandler} is inserted to the {@link ChannelPipeline}, causing * data corruption. * <p> * The client-side implementation is much simpler. * <ol> * <li>Write a StartTLS request,</li> * <li>wait for the StartTLS response,</li> * <li>create a new {@link SslHandler} instance with {@code startTls} flag set * to {@code false},</li> * <li>insert the {@link SslHandler} to the {@link ChannelPipeline}, and</li> * <li>Initiate SSL handshake by calling {@link SslHandler#handshake()}.</li> * </ol> * * <h3>Known issues</h3> * <p> * Because of a known issue with the current implementation of the SslEngine that comes * with Java it may be possible that you see blocked IO-Threads while a full GC is done. * <p> * So if you are affected you can workaround this problem by adjust the cache settings * like shown below: * * <pre> * SslContext context = ...; * context.getServerSessionContext().setSessionCacheSize(someSaneSize); * context.getServerSessionContext().setSessionTime(someSameTimeout); * </pre> * <p> * What values to use here depends on the nature of your application and should be set * based on monitoring and debugging of it. * For more details see * <a href="https://github.com/netty/netty/issues/832">#832</a> in our issue tracker. * @apiviz.landmark * @apiviz.uses org.jboss.netty.handler.ssl.SslBufferPool */ public class SslHandler extends FrameDecoder implements ChannelDownstreamHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(SslHandler.class); private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); private static final Pattern IGNORABLE_CLASS_IN_STACK = Pattern.compile( "^.*(?:Socket|Datagram|Sctp|Udt)Channel.*$"); private static final Pattern IGNORABLE_ERROR_MESSAGE = Pattern.compile( "^.*(?:connection.*(?:reset|closed|abort|broken)|broken.*pipe).*$", Pattern.CASE_INSENSITIVE); private static SslBufferPool defaultBufferPool; /** * Returns the default {@link SslBufferPool} used when no pool is * specified in the constructor. */ public static synchronized SslBufferPool getDefaultBufferPool() { if (defaultBufferPool == null) { defaultBufferPool = new SslBufferPool(); } return defaultBufferPool; } private volatile ChannelHandlerContext ctx; private final SSLEngine engine; private final SslBufferPool bufferPool; private final Executor delegatedTaskExecutor; private final boolean startTls; private volatile boolean enableRenegotiation = true; final Object handshakeLock = new Object(); private boolean handshaking; private volatile boolean handshaken; private volatile ChannelFuture handshakeFuture; @SuppressWarnings("UnusedDeclaration") private volatile int sentFirstMessage; @SuppressWarnings("UnusedDeclaration") private volatile int sentCloseNotify; @SuppressWarnings("UnusedDeclaration") private volatile int closedOutboundAndChannel; private static final AtomicIntegerFieldUpdater<SslHandler> SENT_FIRST_MESSAGE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(SslHandler.class, "sentFirstMessage"); private static final AtomicIntegerFieldUpdater<SslHandler> SENT_CLOSE_NOTIFY_UPDATER = AtomicIntegerFieldUpdater.newUpdater(SslHandler.class, "sentCloseNotify"); private static final AtomicIntegerFieldUpdater<SslHandler> CLOSED_OUTBOUND_AND_CHANNEL_UPDATER = AtomicIntegerFieldUpdater.newUpdater(SslHandler.class, "closedOutboundAndChannel"); int ignoreClosedChannelException; final Object ignoreClosedChannelExceptionLock = new Object(); private final Queue<PendingWrite> pendingUnencryptedWrites = new LinkedList<PendingWrite>(); private final NonReentrantLock pendingUnencryptedWritesLock = new NonReentrantLock(); private final Queue<MessageEvent> pendingEncryptedWrites = new ConcurrentLinkedQueue<MessageEvent>(); private final NonReentrantLock pendingEncryptedWritesLock = new NonReentrantLock(); private volatile boolean issueHandshake; private volatile boolean writeBeforeHandshakeDone; private final SSLEngineInboundCloseFuture sslEngineCloseFuture = new SSLEngineInboundCloseFuture(); private boolean closeOnSslException; private int packetLength; private final Timer timer; private final long handshakeTimeoutInMillis; private Timeout handshakeTimeout; /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use */ public SslHandler(SSLEngine engine) { this(engine, getDefaultBufferPool(), false, null, 0); } /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use * @param bufferPool the {@link SslBufferPool} where this handler will * acquire the buffers required by the {@link SSLEngine} */ public SslHandler(SSLEngine engine, SslBufferPool bufferPool) { this(engine, bufferPool, false, null, 0); } /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use * @param startTls {@code true} if the first write request shouldn't be * encrypted by the {@link SSLEngine} */ public SslHandler(SSLEngine engine, boolean startTls) { this(engine, getDefaultBufferPool(), startTls); } /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use * @param bufferPool the {@link SslBufferPool} where this handler will * acquire the buffers required by the {@link SSLEngine} * @param startTls {@code true} if the first write request shouldn't be * encrypted by the {@link SSLEngine} */ public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls) { this(engine, bufferPool, startTls, null, 0); } /** * Creates a new instance. * * @param engine * the {@link SSLEngine} this handler will use * @param bufferPool * the {@link SslBufferPool} where this handler will acquire * the buffers required by the {@link SSLEngine} * @param startTls * {@code true} if the first write request shouldn't be encrypted * by the {@link SSLEngine} * @param timer * the {@link Timer} which will be used to process the timeout of the {@link #handshake()}. * Be aware that the given {@link Timer} will not get stopped automaticly, so it is up to you to cleanup * once you not need it anymore * @param handshakeTimeoutInMillis * the time in milliseconds after whic the {@link #handshake()} will be failed, and so the future notified */ @SuppressWarnings("deprecation") public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Timer timer, long handshakeTimeoutInMillis) { this(engine, bufferPool, startTls, ImmediateExecutor.INSTANCE, timer, handshakeTimeoutInMillis); } /** * @deprecated Use {@link #SslHandler(SSLEngine)} instead. */ @Deprecated public SslHandler(SSLEngine engine, Executor delegatedTaskExecutor) { this(engine, getDefaultBufferPool(), delegatedTaskExecutor); } /** * @deprecated Use {@link #SslHandler(SSLEngine, boolean)} instead. */ @Deprecated public SslHandler(SSLEngine engine, SslBufferPool bufferPool, Executor delegatedTaskExecutor) { this(engine, bufferPool, false, delegatedTaskExecutor); } /** * @deprecated Use {@link #SslHandler(SSLEngine, boolean)} instead. */ @Deprecated public SslHandler(SSLEngine engine, boolean startTls, Executor delegatedTaskExecutor) { this(engine, getDefaultBufferPool(), startTls, delegatedTaskExecutor); } /** * @deprecated Use {@link #SslHandler(SSLEngine, SslBufferPool, boolean)} instead. */ @Deprecated public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Executor delegatedTaskExecutor) { this(engine, bufferPool, startTls, delegatedTaskExecutor, null, 0); } /** * @deprecated Use {@link #SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Timer timer, * long handshakeTimeoutInMillis)} instead. */ @Deprecated public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Executor delegatedTaskExecutor, Timer timer, long handshakeTimeoutInMillis) { if (engine == null) { throw new NullPointerException("engine"); } if (bufferPool == null) { throw new NullPointerException("bufferPool"); } if (delegatedTaskExecutor == null) { throw new NullPointerException("delegatedTaskExecutor"); } if (timer == null && handshakeTimeoutInMillis > 0) { throw new IllegalArgumentException("No Timer was given but a handshakeTimeoutInMillis, need both or none"); } this.engine = engine; this.bufferPool = bufferPool; this.delegatedTaskExecutor = delegatedTaskExecutor; this.startTls = startTls; this.timer = timer; this.handshakeTimeoutInMillis = handshakeTimeoutInMillis; } /** * Returns the {@link SSLEngine} which is used by this handler. */ public SSLEngine getEngine() { return engine; } /** * Starts an SSL / TLS handshake for the specified channel. * * @return a {@link ChannelFuture} which is notified when the handshake * succeeds or fails. */ public ChannelFuture handshake() { synchronized (handshakeLock) { if (handshaken && !isEnableRenegotiation()) { throw new IllegalStateException("renegotiation disabled"); } final ChannelHandlerContext ctx = this.ctx; final Channel channel = ctx.getChannel(); ChannelFuture handshakeFuture; Exception exception = null; if (handshaking) { return this.handshakeFuture; } handshaking = true; try { engine.beginHandshake(); runDelegatedTasks(); handshakeFuture = this.handshakeFuture = future(channel); if (handshakeTimeoutInMillis > 0) { handshakeTimeout = timer.newTimeout(new TimerTask() { public void run(Timeout timeout) throws Exception { ChannelFuture future = SslHandler.this.handshakeFuture; if (future != null && future.isDone()) { return; } setHandshakeFailure(channel, new SSLException("Handshake did not complete within " + handshakeTimeoutInMillis + "ms")); } }, handshakeTimeoutInMillis, TimeUnit.MILLISECONDS); } } catch (Exception e) { handshakeFuture = this.handshakeFuture = failedFuture(channel, e); exception = e; } if (exception == null) { // Began handshake successfully. try { final ChannelFuture hsFuture = handshakeFuture; wrapNonAppData(ctx, channel).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { Throwable cause = future.getCause(); hsFuture.setFailure(cause); fireExceptionCaught(ctx, cause); if (closeOnSslException) { Channels.close(ctx, future(channel)); } } } }); } catch (SSLException e) { handshakeFuture.setFailure(e); fireExceptionCaught(ctx, e); if (closeOnSslException) { Channels.close(ctx, future(channel)); } } } else { // Failed to initiate handshake. fireExceptionCaught(ctx, exception); if (closeOnSslException) { Channels.close(ctx, future(channel)); } } return handshakeFuture; } } /** * @deprecated Use {@link #handshake()} instead. */ @Deprecated public ChannelFuture handshake(@SuppressWarnings("unused") Channel channel) { return handshake(); } /** * Sends an SSL {@code close_notify} message to the specified channel and * destroys the underlying {@link SSLEngine}. */ public ChannelFuture close() { ChannelHandlerContext ctx = this.ctx; Channel channel = ctx.getChannel(); try { engine.closeOutbound(); return wrapNonAppData(ctx, channel); } catch (SSLException e) { fireExceptionCaught(ctx, e); if (closeOnSslException) { Channels.close(ctx, future(channel)); } return failedFuture(channel, e); } } /** * @deprecated Use {@link #close()} instead. */ @Deprecated public ChannelFuture close(@SuppressWarnings("unused") Channel channel) { return close(); } /** * Returns {@code true} if and only if TLS renegotiation is enabled. */ public boolean isEnableRenegotiation() { return enableRenegotiation; } /** * Enables or disables TLS renegotiation. */ public void setEnableRenegotiation(boolean enableRenegotiation) { this.enableRenegotiation = enableRenegotiation; } /** * Enables or disables the automatic handshake once the {@link Channel} is * connected. The value will only have affect if its set before the * {@link Channel} is connected. */ public void setIssueHandshake(boolean issueHandshake) { this.issueHandshake = issueHandshake; } /** * Returns {@code true} if the automatic handshake is enabled */ public boolean isIssueHandshake() { return issueHandshake; } /** * Return the {@link ChannelFuture} that will get notified if the inbound of the {@link SSLEngine} will get closed. * * This method will return the same {@link ChannelFuture} all the time. * * For more informations see the apidocs of {@link SSLEngine} * */ public ChannelFuture getSSLEngineInboundCloseFuture() { return sslEngineCloseFuture; } /** * Return the timeout (in ms) after which the {@link ChannelFuture} of {@link #handshake()} will be failed, while * a handshake is in progress */ public long getHandshakeTimeout() { return handshakeTimeoutInMillis; } /** * If set to {@code true}, the {@link Channel} will automatically get closed * one a {@link SSLException} was caught. This is most times what you want, as after this * its almost impossible to recover. * * Anyway the default is {@code false} to not break compatibility with older releases. This * will be changed to {@code true} in the next major release. * */ public void setCloseOnSSLException(boolean closeOnSslException) { if (ctx != null) { throw new IllegalStateException("Can only get changed before attached to ChannelPipeline"); } this.closeOnSslException = closeOnSslException; } public boolean getCloseOnSSLException() { return closeOnSslException; } public void handleDownstream( final ChannelHandlerContext context, final ChannelEvent evt) throws Exception { if (evt instanceof ChannelStateEvent) { ChannelStateEvent e = (ChannelStateEvent) evt; switch (e.getState()) { case OPEN: case CONNECTED: case BOUND: if (Boolean.FALSE.equals(e.getValue()) || e.getValue() == null) { closeOutboundAndChannel(context, e); return; } } } if (!(evt instanceof MessageEvent)) { context.sendDownstream(evt); return; } MessageEvent e = (MessageEvent) evt; if (!(e.getMessage() instanceof ChannelBuffer)) { context.sendDownstream(evt); return; } // Do not encrypt the first write request if this handler is // created with startTLS flag turned on. if (startTls && SENT_FIRST_MESSAGE_UPDATER.compareAndSet(this, 0, 1)) { context.sendDownstream(evt); return; } // Otherwise, all messages are encrypted. ChannelBuffer msg = (ChannelBuffer) e.getMessage(); PendingWrite pendingWrite; if (msg.readable()) { pendingWrite = new PendingWrite(evt.getFuture(), msg.toByteBuffer(msg.readerIndex(), msg.readableBytes())); } else { pendingWrite = new PendingWrite(evt.getFuture(), null); } pendingUnencryptedWritesLock.lock(); try { pendingUnencryptedWrites.add(pendingWrite); } finally { pendingUnencryptedWritesLock.unlock(); } if (handshakeFuture == null || !handshakeFuture.isDone()) { writeBeforeHandshakeDone = true; } wrap(context, evt.getChannel()); } private void cancelHandshakeTimeout() { if (handshakeTimeout != null) { // cancel the task as we will fail the handshake future now handshakeTimeout.cancel(); } } @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Make sure the handshake future is notified when a connection has // been closed during handshake. synchronized (handshakeLock) { if (handshaking) { cancelHandshakeTimeout(); handshakeFuture.setFailure(new ClosedChannelException()); } } try { super.channelDisconnected(ctx, e); } finally { unwrapNonAppData(ctx, e.getChannel()); closeEngine(); } } private void closeEngine() { engine.closeOutbound(); if (sentCloseNotify == 0 && handshaken) { try { engine.closeInbound(); } catch (SSLException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to clean up SSLEngine.", ex); } } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Throwable cause = e.getCause(); if (cause instanceof IOException) { if (cause instanceof ClosedChannelException) { synchronized (ignoreClosedChannelExceptionLock) { if (ignoreClosedChannelException > 0) { ignoreClosedChannelException --; if (logger.isDebugEnabled()) { logger.debug( "Swallowing an exception raised while " + "writing non-app data", cause); } return; } } } else { if (ignoreException(cause)) { return; } } } ctx.sendUpstream(e); } /** * Checks if the given {@link Throwable} can be ignore and just "swallowed" * * When an ssl connection is closed a close_notify message is sent. * After that the peer also sends close_notify however, it's not mandatory to receive * the close_notify. The party who sent the initial close_notify can close the connection immediately * then the peer will get connection reset error. * */ private boolean ignoreException(Throwable t) { if (!(t instanceof SSLException) && t instanceof IOException && engine.isOutboundDone()) { String message = String.valueOf(t.getMessage()).toLowerCase(); // first try to match connection reset / broke peer based on the regex. This is the fastest way // but may fail on different jdk impls or OS's if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) { return true; } // Inspect the StackTraceElements to see if it was a connection reset / broken pipe or not StackTraceElement[] elements = t.getStackTrace(); for (StackTraceElement element: elements) { String classname = element.getClassName(); String methodname = element.getMethodName(); // skip all classes that belong to the io.netty package if (classname.startsWith("org.jboss.netty.")) { continue; } // check if the method name is read if not skip it if (!"read".equals(methodname)) { continue; } // This will also match against SocketInputStream which is used by openjdk 7 and maybe // also others if (IGNORABLE_CLASS_IN_STACK.matcher(classname).matches()) { return true; } try { // No match by now.. Try to load the class via classloader and inspect it. // This is mainly done as other JDK implementations may differ in name of // the impl. Class<?> clazz = getClass().getClassLoader().loadClass(classname); if (SocketChannel.class.isAssignableFrom(clazz) || DatagramChannel.class.isAssignableFrom(clazz)) { return true; } // also match against SctpChannel via String matching as it may not present. if (DetectionUtil.javaVersion() >= 7 && "com.sun.nio.sctp.SctpChannel".equals(clazz.getSuperclass().getName())) { return true; } } catch (ClassNotFoundException e) { // This should not happen just ignore } } } return false; } /** * Returns {@code true} if the given {@link ChannelBuffer} is encrypted. Be aware that this method * will not increase the readerIndex of the given {@link ChannelBuffer}. * * @param buffer * The {@link ChannelBuffer} to read from. Be aware that it must have at least 5 bytes to read, * otherwise it will throw an {@link IllegalArgumentException}. * @return encrypted * {@code true} if the {@link ChannelBuffer} is encrypted, {@code false} otherwise. * @throws IllegalArgumentException * Is thrown if the given {@link ChannelBuffer} has not at least 5 bytes to read. */ public static boolean isEncrypted(ChannelBuffer buffer) { return getEncryptedPacketLength(buffer, buffer.readerIndex()) != -1; } /** * Return how much bytes can be read out of the encrypted data. Be aware that this method will not increase * the readerIndex of the given {@link ChannelBuffer}. * * @param buffer * The {@link ChannelBuffer} to read from. Be aware that it must have at least 5 bytes to read, * otherwise it will throw an {@link IllegalArgumentException}. * @return length * The length of the encrypted packet that is included in the buffer. This will * return {@code -1} if the given {@link ChannelBuffer} is not encrypted at all. * @throws IllegalArgumentException * Is thrown if the given {@link ChannelBuffer} has not at least 5 bytes to read. */ private static int getEncryptedPacketLength(ChannelBuffer buffer, int offset) { int packetLength = 0; // SSLv3 or TLS - Check ContentType boolean tls; switch (buffer.getUnsignedByte(offset)) { case 20: // change_cipher_spec case 21: // alert case 22: // handshake case 23: // application_data tls = true; break; default: // SSLv2 or bad data tls = false; } if (tls) { // SSLv3 or TLS - Check ProtocolVersion int majorVersion = buffer.getUnsignedByte(offset + 1); if (majorVersion == 3) { // SSLv3 or TLS packetLength = (getShort(buffer, offset + 3) & 0xFFFF) + 5; if (packetLength <= 5) { // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data) tls = false; } } else { // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data) tls = false; } } if (!tls) { // SSLv2 or bad data - Check the version boolean sslv2 = true; int headerLength = (buffer.getUnsignedByte(offset) & 0x80) != 0 ? 2 : 3; int majorVersion = buffer.getUnsignedByte(offset + headerLength + 1); if (majorVersion == 2 || majorVersion == 3) { // SSLv2 if (headerLength == 2) { packetLength = (getShort(buffer, offset) & 0x7FFF) + 2; } else { packetLength = (getShort(buffer, offset) & 0x3FFF) + 3; } if (packetLength <= headerLength) { sslv2 = false; } } else { sslv2 = false; } if (!sslv2) { return -1; } } return packetLength; } @Override protected Object decode( final ChannelHandlerContext ctx, Channel channel, ChannelBuffer in) throws Exception { final int startOffset = in.readerIndex(); final int endOffset = in.writerIndex(); int offset = startOffset; int totalLength = 0; // If we calculated the length of the current SSL record before, use that information. if (packetLength > 0) { if (endOffset - startOffset < packetLength) { return null; } else { offset += packetLength; totalLength = packetLength; packetLength = 0; } } boolean nonSslRecord = false; while (totalLength < OpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) { final int readableBytes = endOffset - offset; if (readableBytes < 5) { break; } final int packetLength = getEncryptedPacketLength(in, offset); if (packetLength == -1) { nonSslRecord = true; break; } assert packetLength > 0; if (packetLength > readableBytes) { // wait until the whole packet can be read this.packetLength = packetLength; break; } int newTotalLength = totalLength + packetLength; if (newTotalLength > OpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) { // Don't read too much. break; } // We have a whole packet. // Increment the offset to handle the next packet. offset += packetLength; totalLength = newTotalLength; } ChannelBuffer unwrapped = null; if (totalLength > 0) { // The buffer contains one or more full SSL records. // Slice out the whole packet so unwrap will only be called with complete packets. // Also directly reset the packetLength. This is needed as unwrap(..) may trigger // decode(...) again via: // 1) unwrap(..) is called // 2) wrap(...) is called from within unwrap(...) // 3) wrap(...) calls unwrapLater(...) // 4) unwrapLater(...) calls decode(...) // // See https://github.com/netty/netty/issues/1534 final ByteBuffer inNetBuf = in.toByteBuffer(in.readerIndex(), totalLength); unwrapped = unwrap(ctx, channel, in, inNetBuf, totalLength); assert !inNetBuf.hasRemaining() || engine.isInboundDone(); } if (nonSslRecord) { // Not an SSL/TLS packet NotSslRecordException e = new NotSslRecordException( "not an SSL/TLS record: " + ChannelBuffers.hexDump(in)); in.skipBytes(in.readableBytes()); if (closeOnSslException) { // first trigger the exception and then close the channel fireExceptionCaught(ctx, e); Channels.close(ctx, future(channel)); // just return null as we closed the channel before, that // will take care of cleanup etc return null; } else { throw e; } } return unwrapped; } /** * Reads a big-endian short integer from the buffer. Please note that we do not use * {@link ChannelBuffer#getShort(int)} because it might be a little-endian buffer. */ private static short getShort(ChannelBuffer buf, int offset) { return (short) (buf.getByte(offset) << 8 | buf.getByte(offset + 1) & 0xFF); } private void wrap(ChannelHandlerContext context, Channel channel) throws SSLException { ChannelBuffer msg; ByteBuffer outNetBuf = bufferPool.acquireBuffer(); boolean success = true; boolean offered = false; boolean needsUnwrap = false; PendingWrite pendingWrite = null; try { loop: for (;;) { // Acquire a lock to make sure unencrypted data is polled // in order and their encrypted counterpart is offered in // order. pendingUnencryptedWritesLock.lock(); try { pendingWrite = pendingUnencryptedWrites.peek(); if (pendingWrite == null) { break; } ByteBuffer outAppBuf = pendingWrite.outAppBuf; if (outAppBuf == null) { // A write request with an empty buffer pendingUnencryptedWrites.remove(); offerEncryptedWriteRequest( new DownstreamMessageEvent( channel, pendingWrite.future, ChannelBuffers.EMPTY_BUFFER, channel.getRemoteAddress())); offered = true; } else { synchronized (handshakeLock) { SSLEngineResult result = null; try { result = engine.wrap(outAppBuf, outNetBuf); } finally { if (!outAppBuf.hasRemaining()) { pendingUnencryptedWrites.remove(); } } if (result.bytesProduced() > 0) { outNetBuf.flip(); int remaining = outNetBuf.remaining(); msg = ctx.getChannel().getConfig().getBufferFactory().getBuffer(remaining); // Transfer the bytes to the new ChannelBuffer using some safe method that will also // work with "non" heap buffers // // See https://github.com/netty/netty/issues/329 msg.writeBytes(outNetBuf); outNetBuf.clear(); ChannelFuture future; if (pendingWrite.outAppBuf.hasRemaining()) { // pendingWrite's future shouldn't be notified if // only partial data is written. future = succeededFuture(channel); } else { future = pendingWrite.future; } MessageEvent encryptedWrite = new DownstreamMessageEvent( channel, future, msg, channel.getRemoteAddress()); offerEncryptedWriteRequest(encryptedWrite); offered = true; } else if (result.getStatus() == Status.CLOSED) { // SSLEngine has been closed already. // Any further write attempts should be denied. success = false; break; } else { final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); handleRenegotiation(handshakeStatus); switch (handshakeStatus) { case NEED_WRAP: if (outAppBuf.hasRemaining()) { break; } else { break loop; } case NEED_UNWRAP: needsUnwrap = true; break loop; case NEED_TASK: runDelegatedTasks(); break; case FINISHED: setHandshakeSuccess(channel); if (result.getStatus() == Status.CLOSED) { success = false; } break loop; case NOT_HANDSHAKING: setHandshakeSuccessIfStillHandshaking(channel); if (result.getStatus() == Status.CLOSED) { success = false; } break loop; default: throw new IllegalStateException( "Unknown handshake status: " + handshakeStatus); } } } } } finally { pendingUnencryptedWritesLock.unlock(); } } } catch (SSLException e) { success = false; setHandshakeFailure(channel, e); throw e; } finally { bufferPool.releaseBuffer(outNetBuf); if (offered) { flushPendingEncryptedWrites(context); } if (!success) { IllegalStateException cause = new IllegalStateException("SSLEngine already closed"); // Check if we had a pendingWrite in process, if so we need to also notify as otherwise // the ChannelFuture will never get notified if (pendingWrite != null) { pendingWrite.future.setFailure(cause); } // Mark all remaining pending writes as failure if anything // wrong happened before the write requests are wrapped. // Please note that we do not call setFailure while a lock is // acquired, to avoid a potential dead lock. for (;;) { pendingUnencryptedWritesLock.lock(); try { pendingWrite = pendingUnencryptedWrites.poll(); if (pendingWrite == null) { break; } } finally { pendingUnencryptedWritesLock.unlock(); } pendingWrite.future.setFailure(cause); } } } if (needsUnwrap) { unwrapNonAppData(ctx, channel); } } private void offerEncryptedWriteRequest(MessageEvent encryptedWrite) { final boolean locked = pendingEncryptedWritesLock.tryLock(); try { pendingEncryptedWrites.add(encryptedWrite); } finally { if (locked) { pendingEncryptedWritesLock.unlock(); } } } private void flushPendingEncryptedWrites(ChannelHandlerContext ctx) { while (!pendingEncryptedWrites.isEmpty()) { // Avoid possible dead lock and data integrity issue // which is caused by cross communication between more than one channel // in the same VM. if (!pendingEncryptedWritesLock.tryLock()) { return; } try { MessageEvent e; while ((e = pendingEncryptedWrites.poll()) != null) { ctx.sendDownstream(e); } } finally { pendingEncryptedWritesLock.unlock(); } // Other thread might have added more elements at this point, so we loop again if the queue got unempty. } } private ChannelFuture wrapNonAppData(ChannelHandlerContext ctx, Channel channel) throws SSLException { ChannelFuture future = null; ByteBuffer outNetBuf = bufferPool.acquireBuffer(); SSLEngineResult result; try { for (;;) { synchronized (handshakeLock) { result = engine.wrap(EMPTY_BUFFER, outNetBuf); } if (result.bytesProduced() > 0) { outNetBuf.flip(); ChannelBuffer msg = ctx.getChannel().getConfig().getBufferFactory().getBuffer(outNetBuf.remaining()); // Transfer the bytes to the new ChannelBuffer using some safe method that will also // work with "non" heap buffers // // See https://github.com/netty/netty/issues/329 msg.writeBytes(outNetBuf); outNetBuf.clear(); future = future(channel); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.getCause() instanceof ClosedChannelException) { synchronized (ignoreClosedChannelExceptionLock) { ignoreClosedChannelException ++; } } } }); write(ctx, future, msg); } final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); handleRenegotiation(handshakeStatus); switch (handshakeStatus) { case FINISHED: setHandshakeSuccess(channel); runDelegatedTasks(); break; case NEED_TASK: runDelegatedTasks(); break; case NEED_UNWRAP: if (!Thread.holdsLock(handshakeLock)) { // unwrap shouldn't be called when this method was // called by unwrap - unwrap will keep running after // this method returns. unwrapNonAppData(ctx, channel); } break; case NOT_HANDSHAKING: if (setHandshakeSuccessIfStillHandshaking(channel)) { runDelegatedTasks(); } break; case NEED_WRAP: break; default: throw new IllegalStateException( "Unexpected handshake status: " + handshakeStatus); } if (result.bytesProduced() == 0) { break; } } } catch (SSLException e) { setHandshakeFailure(channel, e); throw e; } finally { bufferPool.releaseBuffer(outNetBuf); } if (future == null) { future = succeededFuture(channel); } return future; } /** * Calls {@link SSLEngine#unwrap(ByteBuffer, ByteBuffer)} with an empty buffer to handle handshakes, etc. */ private void unwrapNonAppData(ChannelHandlerContext ctx, Channel channel) throws SSLException { unwrap(ctx, channel, ChannelBuffers.EMPTY_BUFFER, EMPTY_BUFFER, -1); } /** * Unwraps inbound SSL records. */ private ChannelBuffer unwrap( ChannelHandlerContext ctx, Channel channel, ChannelBuffer nettyInNetBuf, ByteBuffer nioInNetBuf, int initialNettyOutAppBufCapacity) throws SSLException { final int nettyInNetBufStartOffset = nettyInNetBuf.readerIndex(); final int nioInNetBufStartOffset = nioInNetBuf.position(); final ByteBuffer nioOutAppBuf = bufferPool.acquireBuffer(); ChannelBuffer nettyOutAppBuf = null; try { boolean needsWrap = false; for (;;) { SSLEngineResult result; boolean needsHandshake = false; synchronized (handshakeLock) { if (!handshaken && !handshaking && !engine.getUseClientMode() && !engine.isInboundDone() && !engine.isOutboundDone()) { needsHandshake = true; } } if (needsHandshake) { handshake(); } synchronized (handshakeLock) { // Decrypt at least one record in the inbound network buffer. // It is impossible to consume no record here because we made sure the inbound network buffer // always contain at least one record in decode(). Therefore, if SSLEngine.unwrap() returns // BUFFER_OVERFLOW, it is always resolved by retrying after emptying the application buffer. for (;;) { final int outAppBufSize = engine.getSession().getApplicationBufferSize(); final ByteBuffer outAppBuf; if (nioOutAppBuf.capacity() < outAppBufSize) { // SSLEngine wants a buffer larger than what the pool can provide. // Allocate a temporary heap buffer. outAppBuf = ByteBuffer.allocate(outAppBufSize); } else { outAppBuf = nioOutAppBuf; } try { result = engine.unwrap(nioInNetBuf, outAppBuf); switch (result.getStatus()) { case CLOSED: // notify about the CLOSED state of the SSLEngine. See #137 sslEngineCloseFuture.setClosed(); break; case BUFFER_OVERFLOW: // Flush the unwrapped data in the outAppBuf into frame and try again. // See the finally block. continue; } break; } finally { outAppBuf.flip(); // Sync the offset of the inbound buffer. nettyInNetBuf.readerIndex( nettyInNetBufStartOffset + nioInNetBuf.position() - nioInNetBufStartOffset); // Copy the unwrapped data into a smaller buffer. if (outAppBuf.hasRemaining()) { if (nettyOutAppBuf == null) { ChannelBufferFactory factory = ctx.getChannel().getConfig().getBufferFactory(); nettyOutAppBuf = factory.getBuffer(initialNettyOutAppBufCapacity); } nettyOutAppBuf.writeBytes(outAppBuf); } outAppBuf.clear(); } } final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); handleRenegotiation(handshakeStatus); switch (handshakeStatus) { case NEED_UNWRAP: break; case NEED_WRAP: wrapNonAppData(ctx, channel); break; case NEED_TASK: runDelegatedTasks(); break; case FINISHED: setHandshakeSuccess(channel); needsWrap = true; continue; case NOT_HANDSHAKING: if (setHandshakeSuccessIfStillHandshaking(channel)) { needsWrap = true; continue; } if (writeBeforeHandshakeDone) { // We need to call wrap(...) in case there was a flush done before the handshake completed. // // See https://github.com/netty/netty/pull/2437 writeBeforeHandshakeDone = false; needsWrap = true; } break; default: throw new IllegalStateException( "Unknown handshake status: " + handshakeStatus); } if (result.getStatus() == Status.BUFFER_UNDERFLOW || result.bytesConsumed() == 0 && result.bytesProduced() == 0) { break; } } } if (needsWrap) { // wrap() acquires pendingUnencryptedWrites first and then // handshakeLock. If handshakeLock is already hold by the // current thread, calling wrap() will lead to a dead lock // i.e. pendingUnencryptedWrites -> handshakeLock vs. // handshakeLock -> pendingUnencryptedLock -> handshakeLock // // There is also the same issue between pendingEncryptedWrites // and pendingUnencryptedWrites. if (!Thread.holdsLock(handshakeLock) && !pendingEncryptedWritesLock.isHeldByCurrentThread()) { wrap(ctx, channel); } } } catch (SSLException e) { setHandshakeFailure(channel, e); throw e; } finally { bufferPool.releaseBuffer(nioOutAppBuf); } if (nettyOutAppBuf != null && nettyOutAppBuf.readable()) { return nettyOutAppBuf; } else { return null; } } private void handleRenegotiation(HandshakeStatus handshakeStatus) { synchronized (handshakeLock) { if (handshakeStatus == HandshakeStatus.NOT_HANDSHAKING || handshakeStatus == HandshakeStatus.FINISHED) { // Not handshaking return; } if (!handshaken) { // Not renegotiation return; } final boolean renegotiate; if (handshaking) { // Renegotiation in progress or failed already. // i.e. Renegotiation check has been done already below. return; } if (engine.isInboundDone() || engine.isOutboundDone()) { // Not handshaking but closing. return; } if (isEnableRenegotiation()) { // Continue renegotiation. renegotiate = true; } else { // Do not renegotiate. renegotiate = false; // Prevent reentrance of this method. handshaking = true; } if (renegotiate) { // Renegotiate. handshake(); } else { // Raise an exception. fireExceptionCaught( ctx, new SSLException( "renegotiation attempted by peer; " + "closing the connection")); // Close the connection to stop renegotiation. Channels.close(ctx, succeededFuture(ctx.getChannel())); } } } /** * Fetches all delegated tasks from the {@link SSLEngine} and runs them via the {@link #delegatedTaskExecutor}. * If the {@link #delegatedTaskExecutor} is {@link ImmediateExecutor}, just call {@link Runnable#run()} directly * instead of using {@link Executor#execute(Runnable)}. Otherwise, run the tasks via * the {@link #delegatedTaskExecutor} and wait until the tasks are finished. */ private void runDelegatedTasks() { if (delegatedTaskExecutor == ImmediateExecutor.INSTANCE) { for (;;) { final Runnable task; synchronized (handshakeLock) { task = engine.getDelegatedTask(); } if (task == null) { break; } delegatedTaskExecutor.execute(task); } } else { final List<Runnable> tasks = new ArrayList<Runnable>(2); for (;;) { final Runnable task; synchronized (handshakeLock) { task = engine.getDelegatedTask(); } if (task == null) { break; } tasks.add(task); } if (tasks.isEmpty()) { return; } final CountDownLatch latch = new CountDownLatch(1); delegatedTaskExecutor.execute(new Runnable() { public void run() { try { for (Runnable task: tasks) { task.run(); } } catch (Exception e) { fireExceptionCaught(ctx, e); } finally { latch.countDown(); } } }); boolean interrupted = false; while (latch.getCount() != 0) { try { latch.await(); } catch (InterruptedException e) { // Interrupt later. interrupted = true; } } if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Works around some Android {@link SSLEngine} implementations that skip {@link HandshakeStatus#FINISHED} and * go straight into {@link HandshakeStatus#NOT_HANDSHAKING} when handshake is finished. * * @return {@code true} if and only if the workaround has been applied and thus {@link #handshakeFuture} has been * marked as success by this method */ private boolean setHandshakeSuccessIfStillHandshaking(Channel channel) { if (handshaking && !handshakeFuture.isDone()) { setHandshakeSuccess(channel); return true; } return false; } private void setHandshakeSuccess(Channel channel) { synchronized (handshakeLock) { handshaking = false; handshaken = true; if (handshakeFuture == null) { handshakeFuture = future(channel); } cancelHandshakeTimeout(); } if (logger.isDebugEnabled()) { logger.debug(channel + " HANDSHAKEN: " + engine.getSession().getCipherSuite()); } handshakeFuture.setSuccess(); } private void setHandshakeFailure(Channel channel, SSLException cause) { synchronized (handshakeLock) { if (!handshaking) { return; } handshaking = false; handshaken = false; if (handshakeFuture == null) { handshakeFuture = future(channel); } // cancel the timeout now cancelHandshakeTimeout(); // Release all resources such as internal buffers that SSLEngine // is managing. engine.closeOutbound(); try { engine.closeInbound(); } catch (SSLException e) { if (logger.isDebugEnabled()) { logger.debug( "SSLEngine.closeInbound() raised an exception after " + "a handshake failure.", e); } } } handshakeFuture.setFailure(cause); if (closeOnSslException) { Channels.close(ctx, future(channel)); } } private void closeOutboundAndChannel( final ChannelHandlerContext context, final ChannelStateEvent e) { if (!e.getChannel().isConnected()) { context.sendDownstream(e); return; } // Ensure that the tear-down logic beyond this point is never invoked concurrently nor multiple times. if (!CLOSED_OUTBOUND_AND_CHANNEL_UPDATER.compareAndSet(this, 0, 1)) { // The other thread called this method already, and thus the connection will be closed eventually. // So, just wait until the connection is closed, and then forward the event so that the sink handles // the duplicate close attempt. e.getChannel().getCloseFuture().addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { context.sendDownstream(e); } }); return; } boolean passthrough = true; try { try { unwrapNonAppData(ctx, e.getChannel()); } catch (SSLException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to unwrap before sending a close_notify message", ex); } } if (!engine.isOutboundDone()) { if (SENT_CLOSE_NOTIFY_UPDATER.compareAndSet(this, 0, 1)) { engine.closeOutbound(); try { ChannelFuture closeNotifyFuture = wrapNonAppData(context, e.getChannel()); closeNotifyFuture.addListener( new ClosingChannelFutureListener(context, e)); passthrough = false; } catch (SSLException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to encode a close_notify message", ex); } } } } } finally { if (passthrough) { context.sendDownstream(e); } } } private static final class PendingWrite { final ChannelFuture future; final ByteBuffer outAppBuf; PendingWrite(ChannelFuture future, ByteBuffer outAppBuf) { this.future = future; this.outAppBuf = outAppBuf; } } private static final class ClosingChannelFutureListener implements ChannelFutureListener { private final ChannelHandlerContext context; private final ChannelStateEvent e; ClosingChannelFutureListener( ChannelHandlerContext context, ChannelStateEvent e) { this.context = context; this.e = e; } public void operationComplete(ChannelFuture closeNotifyFuture) throws Exception { if (!(closeNotifyFuture.getCause() instanceof ClosedChannelException)) { Channels.close(context, e.getFuture()); } else { e.getFuture().setSuccess(); } } } @Override public void beforeAdd(ChannelHandlerContext ctx) throws Exception { super.beforeAdd(ctx); this.ctx = ctx; } /** * Fail all pending writes which we were not able to flush out */ @Override public void afterRemove(ChannelHandlerContext ctx) throws Exception { closeEngine(); // there is no need for synchronization here as we do not receive downstream events anymore Throwable cause = null; for (;;) { PendingWrite pw = pendingUnencryptedWrites.poll(); if (pw == null) { break; } if (cause == null) { cause = new IOException("Unable to write data"); } pw.future.setFailure(cause); } for (;;) { MessageEvent ev = pendingEncryptedWrites.poll(); if (ev == null) { break; } if (cause == null) { cause = new IOException("Unable to write data"); } ev.getFuture().setFailure(cause); } if (cause != null) { fireExceptionCaughtLater(ctx, cause); } } /** * Calls {@link #handshake()} once the {@link Channel} is connected */ @Override public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception { if (issueHandshake) { // issue and handshake and add a listener to it which will fire an exception event if // an exception was thrown while doing the handshake handshake().addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Send the event upstream after the handshake was completed without an error. // // See https://github.com/netty/netty/issues/358 ctx.sendUpstream(e); } } }); } else { super.channelConnected(ctx, e); } } /** * Loop over all the pending writes and fail them. * * See <a href="https://github.com/netty/netty/issues/305">#305</a> for more details. */ @Override public void channelClosed(final ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Move the fail of the writes to the IO-Thread to prevent possible deadlock // See https://github.com/netty/netty/issues/989 ctx.getPipeline().execute(new Runnable() { public void run() { if (!pendingUnencryptedWritesLock.tryLock()) { return; } Throwable cause = null; try { for (;;) { PendingWrite pw = pendingUnencryptedWrites.poll(); if (pw == null) { break; } if (cause == null) { cause = new ClosedChannelException(); } pw.future.setFailure(cause); } for (;;) { MessageEvent ev = pendingEncryptedWrites.poll(); if (ev == null) { break; } if (cause == null) { cause = new ClosedChannelException(); } ev.getFuture().setFailure(cause); } } finally { pendingUnencryptedWritesLock.unlock(); } if (cause != null) { fireExceptionCaught(ctx, cause); } } }); super.channelClosed(ctx, e); } private final class SSLEngineInboundCloseFuture extends DefaultChannelFuture { SSLEngineInboundCloseFuture() { super(null, true); } void setClosed() { super.setSuccess(); } @Override public Channel getChannel() { if (ctx == null) { // Maybe we should better throw an IllegalStateException() ? return null; } else { return ctx.getChannel(); } } @Override public boolean setSuccess() { return false; } @Override public boolean setFailure(Throwable cause) { return false; } } }
./CrossVul/dataset_final_sorted/CWE-119/java/good_2139_0
crossvul-java_data_good_4291_4
/* * Copyright (C) 2016 Southern Storm Software, Pty Ltd. * * 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 com.southernstorm.noise.protocol; import javax.crypto.BadPaddingException; import javax.crypto.ShortBufferException; /** * Interface to an authenticated cipher for use in the Noise protocol. * * CipherState objects are used to encrypt or decrypt data during a * session. Once the handshake has completed, HandshakeState.split() * will create two CipherState objects for encrypting packets sent to * the other party, and decrypting packets received from the other party. */ public interface CipherState extends Destroyable { /** * Gets the Noise protocol name for this cipher. * * @return The cipher name. */ String getCipherName(); /** * Gets the length of the key values for this cipher. * * @return The length of the key in bytes; usually 32. */ int getKeyLength(); /** * Gets the length of the MAC values for this cipher. * * @return The length of MAC values in bytes, or zero if the * key has not yet been initialized. */ int getMACLength(); /** * Initializes the key on this cipher object. * * @param key Points to a buffer that contains the key. * @param offset The offset of the key in the key buffer. * * The key buffer must contain at least getKeyLength() bytes * starting at offset. * * @see #hasKey() */ void initializeKey(byte[] key, int offset); /** * Determine if this cipher object has been configured with a key. * * @return true if this cipher object has a key; false if the * key has not yet been set with initializeKey(). * * @see #initializeKey(byte[], int) */ boolean hasKey(); /** * Encrypts a plaintext buffer using the cipher and a block of associated data. * * @param ad The associated data, or null if there is none. * @param plaintext The buffer containing the plaintext to encrypt. * @param plaintextOffset The offset within the plaintext buffer of the * first byte or plaintext data. * @param ciphertext The buffer to place the ciphertext in. This can * be the same as the plaintext buffer. * @param ciphertextOffset The first offset within the ciphertext buffer * to place the ciphertext and the MAC tag. * @param length The length of the plaintext. * @return The length of the ciphertext plus the MAC tag, or -1 if the * ciphertext buffer is not large enough to hold the result. * * @throws ShortBufferException The ciphertext buffer does not have * enough space to hold the ciphertext plus MAC. * * @throws IllegalStateException The nonce has wrapped around. * * @throws IllegalArgumentException One of the parameters is out of range. * * The plaintext and ciphertext buffers can be the same for in-place * encryption. In that case, plaintextOffset must be identical to * ciphertextOffset. * * There must be enough space in the ciphertext buffer to accomodate * length + getMACLength() bytes of data starting at ciphertextOffset. */ int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException; /** * Decrypts a ciphertext buffer using the cipher and a block of associated data. * * @param ad The associated data, or null if there is none. * @param ciphertext The buffer containing the ciphertext to decrypt. * @param ciphertextOffset The offset within the ciphertext buffer of * the first byte of ciphertext data. * @param plaintext The buffer to place the plaintext in. This can be * the same as the ciphertext buffer. * @param plaintextOffset The first offset within the plaintext buffer * to place the plaintext. * @param length The length of the incoming ciphertext plus the MAC tag. * @return The length of the plaintext with the MAC tag stripped off. * * @throws ShortBufferException The plaintext buffer does not have * enough space to store the decrypted data. * * @throws BadPaddingException The MAC value failed to verify. * * @throws IllegalStateException The nonce has wrapped around. * * @throws IllegalArgumentException One of the parameters is out of range. * * The plaintext and ciphertext buffers can be the same for in-place * decryption. In that case, ciphertextOffset must be identical to * plaintextOffset. */ int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException; /** * Creates a new instance of this cipher and initializes it with a key. * * @param key The buffer containing the key. * @param offset The offset into the key buffer of the first key byte. * @return A new CipherState of the same class as this one. */ CipherState fork(byte[] key, int offset); /** * Sets the nonce value. * * @param nonce The new nonce value, which must be greater than or equal * to the current value. * * This function is intended for testing purposes only. If the nonce * value goes backwards then security may be compromised. */ void setNonce(long nonce); }
./CrossVul/dataset_final_sorted/CWE-119/java/good_4291_4
crossvul-java_data_good_4291_2
/* * Copyright (C) 2016 Southern Storm Software, Pty Ltd. * * 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 com.southernstorm.noise.protocol; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import com.southernstorm.noise.crypto.GHASH; /** * Emulates the "AESGCM" cipher for Noise using the "AES/CTR/NoPadding" * transformation from JCA/JCE. * * This class is used on platforms that don't have "AES/GCM/NoPadding", * but which do have the older "AES/CTR/NoPadding". */ class AESGCMOnCtrCipherState implements CipherState { private Cipher cipher; private SecretKeySpec keySpec; private long n; private byte[] iv; private byte[] hashKey; private GHASH ghash; /** * Constructs a new cipher state for the "AESGCM" algorithm. * * @throws NoSuchAlgorithmException The system does not have a * provider for this algorithm. */ public AESGCMOnCtrCipherState() throws NoSuchAlgorithmException { try { cipher = Cipher.getInstance("AES/CTR/NoPadding"); } catch (NoSuchPaddingException e) { // AES/CTR is available, but not the unpadded version? Huh? throw new NoSuchAlgorithmException("AES/CTR/NoPadding not available", e); } keySpec = null; n = 0; iv = new byte [16]; hashKey = new byte [16]; ghash = new GHASH(); // Try to set a 256-bit key on the cipher. Some JCE's are // configured to disallow 256-bit AES if an extra policy // file has not been installed. try { SecretKeySpec spec = new SecretKeySpec(new byte [32], "AES"); IvParameterSpec params = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, spec, params); } catch (InvalidKeyException e) { throw new NoSuchAlgorithmException("AES/CTR/NoPadding does not support 256-bit keys", e); } catch (InvalidAlgorithmParameterException e) { throw new NoSuchAlgorithmException("AES/CTR/NoPadding does not support 256-bit keys", e); } } @Override public void destroy() { // There doesn't seem to be a standard API to clean out a Cipher. // So we instead set the key and IV to all-zeroes to hopefully // destroy the sensitive data in the cipher instance. ghash.destroy(); Noise.destroy(hashKey); Noise.destroy(iv); keySpec = new SecretKeySpec(new byte [32], "AES"); IvParameterSpec params = new IvParameterSpec(iv); try { cipher.init(Cipher.ENCRYPT_MODE, keySpec, params); } catch (InvalidKeyException e) { // Shouldn't happen. } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. } } @Override public String getCipherName() { return "AESGCM"; } @Override public int getKeyLength() { return 32; } @Override public int getMACLength() { return keySpec != null ? 16 : 0; } @Override public void initializeKey(byte[] key, int offset) { // Set the encryption key. keySpec = new SecretKeySpec(key, offset, 32, "AES"); // Generate the hashing key by encrypting a block of zeroes. Arrays.fill(iv, (byte)0); Arrays.fill(hashKey, (byte)0); try { cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv)); } catch (InvalidKeyException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. throw new IllegalStateException(e); } try { int result = cipher.update(hashKey, 0, 16, hashKey, 0); cipher.doFinal(hashKey, result); } catch (ShortBufferException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (IllegalBlockSizeException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (BadPaddingException e) { // Shouldn't happen. throw new IllegalStateException(e); } ghash.reset(hashKey, 0); // Reset the nonce. n = 0; } @Override public boolean hasKey() { return keySpec != null; } /** * Set up to encrypt or decrypt the next packet. * * @param ad The associated data for the packet. */ private void setup(byte[] ad) throws InvalidKeyException, InvalidAlgorithmParameterException { // Check for nonce wrap-around. if (n == -1L) throw new IllegalStateException("Nonce has wrapped around"); // Format the counter/IV block for AES/CTR/NoPadding. iv[0] = 0; iv[1] = 0; iv[2] = 0; iv[3] = 0; iv[4] = (byte)(n >> 56); iv[5] = (byte)(n >> 48); iv[6] = (byte)(n >> 40); iv[7] = (byte)(n >> 32); iv[8] = (byte)(n >> 24); iv[9] = (byte)(n >> 16); iv[10] = (byte)(n >> 8); iv[11] = (byte)n; iv[12] = 0; iv[13] = 0; iv[14] = 0; iv[15] = 1; ++n; // Initialize the CTR mode cipher with the key and IV. cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv)); // Encrypt a block of zeroes to generate the hash key to XOR // the GHASH tag with at the end of the encrypt/decrypt operation. Arrays.fill(hashKey, (byte)0); try { cipher.update(hashKey, 0, 16, hashKey, 0); } catch (ShortBufferException e) { // Shouldn't happen. throw new IllegalStateException(e); } // Initialize the GHASH with the associated data value. ghash.reset(); if (ad != null) { ghash.update(ad, 0, ad.length); ghash.pad(); } } @Override public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length) throw new IllegalArgumentException(); if (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length) throw new IllegalArgumentException(); space = ciphertext.length - ciphertextOffset; if (keySpec == null) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); try { setup(ad); int result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset); cipher.doFinal(ciphertext, ciphertextOffset + result); } catch (InvalidKeyException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (IllegalBlockSizeException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (BadPaddingException e) { // Shouldn't happen. throw new IllegalStateException(e); } ghash.update(ciphertext, ciphertextOffset, length); ghash.pad(ad != null ? ad.length : 0, length); ghash.finish(ciphertext, ciphertextOffset + length, 16); for (int index = 0; index < 16; ++index) ciphertext[ciphertextOffset + length + index] ^= hashKey[index]; return length + 16; } @Override public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length) throw new IllegalArgumentException(); else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length) throw new IllegalArgumentException(); space = plaintext.length - plaintextOffset; if (keySpec == null) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); try { setup(ad); } catch (InvalidKeyException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. throw new IllegalStateException(e); } ghash.update(ciphertext, ciphertextOffset, dataLen); ghash.pad(ad != null ? ad.length : 0, dataLen); ghash.finish(iv, 0, 16); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); try { int result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset); cipher.doFinal(plaintext, plaintextOffset + result); } catch (IllegalBlockSizeException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (BadPaddingException e) { // Shouldn't happen. throw new IllegalStateException(e); } return dataLen; } @Override public CipherState fork(byte[] key, int offset) { CipherState cipher; try { cipher = new AESGCMOnCtrCipherState(); } catch (NoSuchAlgorithmException e) { // Shouldn't happen. return null; } cipher.initializeKey(key, offset); return cipher; } @Override public void setNonce(long nonce) { n = nonce; } }
./CrossVul/dataset_final_sorted/CWE-119/java/good_4291_2
crossvul-java_data_bad_4291_3
/* * Copyright (C) 2016 Southern Storm Software, Pty Ltd. * * 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 com.southernstorm.noise.protocol; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.ShortBufferException; import com.southernstorm.noise.crypto.ChaChaCore; import com.southernstorm.noise.crypto.Poly1305; /** * Implements the ChaChaPoly cipher for Noise. */ class ChaChaPolyCipherState implements CipherState { private Poly1305 poly; private int[] input; private int[] output; private byte[] polyKey; long n; private boolean haskey; /** * Constructs a new cipher state for the "ChaChaPoly" algorithm. */ public ChaChaPolyCipherState() { poly = new Poly1305(); input = new int [16]; output = new int [16]; polyKey = new byte [32]; n = 0; haskey = false; } @Override public void destroy() { poly.destroy(); Arrays.fill(input, 0); Arrays.fill(output, 0); Noise.destroy(polyKey); } @Override public String getCipherName() { return "ChaChaPoly"; } @Override public int getKeyLength() { return 32; } @Override public int getMACLength() { return haskey ? 16 : 0; } @Override public void initializeKey(byte[] key, int offset) { ChaChaCore.initKey256(input, key, offset); n = 0; haskey = true; } @Override public boolean hasKey() { return haskey; } /** * XOR's the output of ChaCha20 with a byte buffer. * * @param input The input byte buffer. * @param inputOffset The offset of the first input byte. * @param output The output byte buffer (can be the same as the input). * @param outputOffset The offset of the first output byte. * @param length The number of bytes to XOR between 1 and 64. * @param block The ChaCha20 output block. */ private static void xorBlock(byte[] input, int inputOffset, byte[] output, int outputOffset, int length, int[] block) { int posn = 0; int value; while (length >= 4) { value = block[posn++]; output[outputOffset] = (byte)(input[inputOffset] ^ value); output[outputOffset + 1] = (byte)(input[inputOffset + 1] ^ (value >> 8)); output[outputOffset + 2] = (byte)(input[inputOffset + 2] ^ (value >> 16)); output[outputOffset + 3] = (byte)(input[inputOffset + 3] ^ (value >> 24)); inputOffset += 4; outputOffset += 4; length -= 4; } if (length == 3) { value = block[posn]; output[outputOffset] = (byte)(input[inputOffset] ^ value); output[outputOffset + 1] = (byte)(input[inputOffset + 1] ^ (value >> 8)); output[outputOffset + 2] = (byte)(input[inputOffset + 2] ^ (value >> 16)); } else if (length == 2) { value = block[posn]; output[outputOffset] = (byte)(input[inputOffset] ^ value); output[outputOffset + 1] = (byte)(input[inputOffset + 1] ^ (value >> 8)); } else if (length == 1) { value = block[posn]; output[outputOffset] = (byte)(input[inputOffset] ^ value); } } /** * Set up to encrypt or decrypt the next packet. * * @param ad The associated data for the packet. */ private void setup(byte[] ad) { if (n == -1L) throw new IllegalStateException("Nonce has wrapped around"); ChaChaCore.initIV(input, n++); ChaChaCore.hash(output, input); Arrays.fill(polyKey, (byte)0); xorBlock(polyKey, 0, polyKey, 0, 32, output); poly.reset(polyKey, 0); if (ad != null) { poly.update(ad, 0, ad.length); poly.pad(); } if (++(input[12]) == 0) ++(input[13]); } /** * Puts a 64-bit integer into a buffer in little-endian order. * * @param output The output buffer. * @param offset The offset into the output buffer. * @param value The 64-bit integer value. */ private static void putLittleEndian64(byte[] output, int offset, long value) { output[offset] = (byte)value; output[offset + 1] = (byte)(value >> 8); output[offset + 2] = (byte)(value >> 16); output[offset + 3] = (byte)(value >> 24); output[offset + 4] = (byte)(value >> 32); output[offset + 5] = (byte)(value >> 40); output[offset + 6] = (byte)(value >> 48); output[offset + 7] = (byte)(value >> 56); } /** * Finishes up the authentication tag for a packet. * * @param ad The associated data. * @param length The length of the plaintext data. */ private void finish(byte[] ad, int length) { poly.pad(); putLittleEndian64(polyKey, 0, ad != null ? ad.length : 0); putLittleEndian64(polyKey, 8, length); poly.update(polyKey, 0, 16); poly.finish(polyKey, 0); } /** * Encrypts or decrypts a buffer of bytes for the active packet. * * @param plaintext The plaintext data to be encrypted. * @param plaintextOffset The offset to the first plaintext byte. * @param ciphertext The ciphertext data that results from encryption. * @param ciphertextOffset The offset to the first ciphertext byte. * @param length The number of bytes to encrypt. */ private void encrypt(byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) { while (length > 0) { int tempLen = 64; if (tempLen > length) tempLen = length; ChaChaCore.hash(output, input); xorBlock(plaintext, plaintextOffset, ciphertext, ciphertextOffset, tempLen, output); if (++(input[12]) == 0) ++(input[13]); plaintextOffset += tempLen; ciphertextOffset += tempLen; length -= tempLen; } } @Override public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (!haskey) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); setup(ad); encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); poly.update(ciphertext, ciphertextOffset, length); finish(ad, length); System.arraycopy(polyKey, 0, ciphertext, ciphertextOffset + length, 16); return length + 16; } @Override public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (plaintextOffset > plaintext.length) space = 0; else space = plaintext.length - plaintextOffset; if (!haskey) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); setup(ad); poly.update(ciphertext, ciphertextOffset, dataLen); finish(ad, dataLen); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; } @Override public CipherState fork(byte[] key, int offset) { CipherState cipher = new ChaChaPolyCipherState(); cipher.initializeKey(key, offset); return cipher; } @Override public void setNonce(long nonce) { n = nonce; } }
./CrossVul/dataset_final_sorted/CWE-119/java/bad_4291_3
crossvul-java_data_bad_4291_4
/* * Copyright (C) 2016 Southern Storm Software, Pty Ltd. * * 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 com.southernstorm.noise.protocol; import javax.crypto.BadPaddingException; import javax.crypto.ShortBufferException; /** * Interface to an authenticated cipher for use in the Noise protocol. * * CipherState objects are used to encrypt or decrypt data during a * session. Once the handshake has completed, HandshakeState.split() * will create two CipherState objects for encrypting packets sent to * the other party, and decrypting packets received from the other party. */ public interface CipherState extends Destroyable { /** * Gets the Noise protocol name for this cipher. * * @return The cipher name. */ String getCipherName(); /** * Gets the length of the key values for this cipher. * * @return The length of the key in bytes; usually 32. */ int getKeyLength(); /** * Gets the length of the MAC values for this cipher. * * @return The length of MAC values in bytes, or zero if the * key has not yet been initialized. */ int getMACLength(); /** * Initializes the key on this cipher object. * * @param key Points to a buffer that contains the key. * @param offset The offset of the key in the key buffer. * * The key buffer must contain at least getKeyLength() bytes * starting at offset. * * @see #hasKey() */ void initializeKey(byte[] key, int offset); /** * Determine if this cipher object has been configured with a key. * * @return true if this cipher object has a key; false if the * key has not yet been set with initializeKey(). * * @see #initializeKey(byte[], int) */ boolean hasKey(); /** * Encrypts a plaintext buffer using the cipher and a block of associated data. * * @param ad The associated data, or null if there is none. * @param plaintext The buffer containing the plaintext to encrypt. * @param plaintextOffset The offset within the plaintext buffer of the * first byte or plaintext data. * @param ciphertext The buffer to place the ciphertext in. This can * be the same as the plaintext buffer. * @param ciphertextOffset The first offset within the ciphertext buffer * to place the ciphertext and the MAC tag. * @param length The length of the plaintext. * @return The length of the ciphertext plus the MAC tag, or -1 if the * ciphertext buffer is not large enough to hold the result. * * @throws ShortBufferException The ciphertext buffer does not have * enough space to hold the ciphertext plus MAC. * * @throws IllegalStateException The nonce has wrapped around. * * The plaintext and ciphertext buffers can be the same for in-place * encryption. In that case, plaintextOffset must be identical to * ciphertextOffset. * * There must be enough space in the ciphertext buffer to accomodate * length + getMACLength() bytes of data starting at ciphertextOffset. */ int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException; /** * Decrypts a ciphertext buffer using the cipher and a block of associated data. * * @param ad The associated data, or null if there is none. * @param ciphertext The buffer containing the ciphertext to decrypt. * @param ciphertextOffset The offset within the ciphertext buffer of * the first byte of ciphertext data. * @param plaintext The buffer to place the plaintext in. This can be * the same as the ciphertext buffer. * @param plaintextOffset The first offset within the plaintext buffer * to place the plaintext. * @param length The length of the incoming ciphertext plus the MAC tag. * @return The length of the plaintext with the MAC tag stripped off. * * @throws ShortBufferException The plaintext buffer does not have * enough space to store the decrypted data. * * @throws BadPaddingException The MAC value failed to verify. * * @throws IllegalStateException The nonce has wrapped around. * * The plaintext and ciphertext buffers can be the same for in-place * decryption. In that case, ciphertextOffset must be identical to * plaintextOffset. */ int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException; /** * Creates a new instance of this cipher and initializes it with a key. * * @param key The buffer containing the key. * @param offset The offset into the key buffer of the first key byte. * @return A new CipherState of the same class as this one. */ CipherState fork(byte[] key, int offset); /** * Sets the nonce value. * * @param nonce The new nonce value, which must be greater than or equal * to the current value. * * This function is intended for testing purposes only. If the nonce * value goes backwards then security may be compromised. */ void setNonce(long nonce); }
./CrossVul/dataset_final_sorted/CWE-119/java/bad_4291_4
crossvul-java_data_bad_4291_2
/* * Copyright (C) 2016 Southern Storm Software, Pty Ltd. * * 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 com.southernstorm.noise.protocol; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import com.southernstorm.noise.crypto.GHASH; /** * Emulates the "AESGCM" cipher for Noise using the "AES/CTR/NoPadding" * transformation from JCA/JCE. * * This class is used on platforms that don't have "AES/GCM/NoPadding", * but which do have the older "AES/CTR/NoPadding". */ class AESGCMOnCtrCipherState implements CipherState { private Cipher cipher; private SecretKeySpec keySpec; private long n; private byte[] iv; private byte[] hashKey; private GHASH ghash; /** * Constructs a new cipher state for the "AESGCM" algorithm. * * @throws NoSuchAlgorithmException The system does not have a * provider for this algorithm. */ public AESGCMOnCtrCipherState() throws NoSuchAlgorithmException { try { cipher = Cipher.getInstance("AES/CTR/NoPadding"); } catch (NoSuchPaddingException e) { // AES/CTR is available, but not the unpadded version? Huh? throw new NoSuchAlgorithmException("AES/CTR/NoPadding not available", e); } keySpec = null; n = 0; iv = new byte [16]; hashKey = new byte [16]; ghash = new GHASH(); // Try to set a 256-bit key on the cipher. Some JCE's are // configured to disallow 256-bit AES if an extra policy // file has not been installed. try { SecretKeySpec spec = new SecretKeySpec(new byte [32], "AES"); IvParameterSpec params = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, spec, params); } catch (InvalidKeyException e) { throw new NoSuchAlgorithmException("AES/CTR/NoPadding does not support 256-bit keys", e); } catch (InvalidAlgorithmParameterException e) { throw new NoSuchAlgorithmException("AES/CTR/NoPadding does not support 256-bit keys", e); } } @Override public void destroy() { // There doesn't seem to be a standard API to clean out a Cipher. // So we instead set the key and IV to all-zeroes to hopefully // destroy the sensitive data in the cipher instance. ghash.destroy(); Noise.destroy(hashKey); Noise.destroy(iv); keySpec = new SecretKeySpec(new byte [32], "AES"); IvParameterSpec params = new IvParameterSpec(iv); try { cipher.init(Cipher.ENCRYPT_MODE, keySpec, params); } catch (InvalidKeyException e) { // Shouldn't happen. } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. } } @Override public String getCipherName() { return "AESGCM"; } @Override public int getKeyLength() { return 32; } @Override public int getMACLength() { return keySpec != null ? 16 : 0; } @Override public void initializeKey(byte[] key, int offset) { // Set the encryption key. keySpec = new SecretKeySpec(key, offset, 32, "AES"); // Generate the hashing key by encrypting a block of zeroes. Arrays.fill(iv, (byte)0); Arrays.fill(hashKey, (byte)0); try { cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv)); } catch (InvalidKeyException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. throw new IllegalStateException(e); } try { int result = cipher.update(hashKey, 0, 16, hashKey, 0); cipher.doFinal(hashKey, result); } catch (ShortBufferException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (IllegalBlockSizeException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (BadPaddingException e) { // Shouldn't happen. throw new IllegalStateException(e); } ghash.reset(hashKey, 0); // Reset the nonce. n = 0; } @Override public boolean hasKey() { return keySpec != null; } /** * Set up to encrypt or decrypt the next packet. * * @param ad The associated data for the packet. */ private void setup(byte[] ad) throws InvalidKeyException, InvalidAlgorithmParameterException { // Check for nonce wrap-around. if (n == -1L) throw new IllegalStateException("Nonce has wrapped around"); // Format the counter/IV block for AES/CTR/NoPadding. iv[0] = 0; iv[1] = 0; iv[2] = 0; iv[3] = 0; iv[4] = (byte)(n >> 56); iv[5] = (byte)(n >> 48); iv[6] = (byte)(n >> 40); iv[7] = (byte)(n >> 32); iv[8] = (byte)(n >> 24); iv[9] = (byte)(n >> 16); iv[10] = (byte)(n >> 8); iv[11] = (byte)n; iv[12] = 0; iv[13] = 0; iv[14] = 0; iv[15] = 1; ++n; // Initialize the CTR mode cipher with the key and IV. cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv)); // Encrypt a block of zeroes to generate the hash key to XOR // the GHASH tag with at the end of the encrypt/decrypt operation. Arrays.fill(hashKey, (byte)0); try { cipher.update(hashKey, 0, 16, hashKey, 0); } catch (ShortBufferException e) { // Shouldn't happen. throw new IllegalStateException(e); } // Initialize the GHASH with the associated data value. ghash.reset(); if (ad != null) { ghash.update(ad, 0, ad.length); ghash.pad(); } } @Override public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (keySpec == null) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); try { setup(ad); int result = cipher.update(plaintext, plaintextOffset, length, ciphertext, ciphertextOffset); cipher.doFinal(ciphertext, ciphertextOffset + result); } catch (InvalidKeyException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (IllegalBlockSizeException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (BadPaddingException e) { // Shouldn't happen. throw new IllegalStateException(e); } ghash.update(ciphertext, ciphertextOffset, length); ghash.pad(ad != null ? ad.length : 0, length); ghash.finish(ciphertext, ciphertextOffset + length, 16); for (int index = 0; index < 16; ++index) ciphertext[ciphertextOffset + length + index] ^= hashKey[index]; return length + 16; } @Override public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (plaintextOffset > plaintext.length) space = 0; else space = plaintext.length - plaintextOffset; if (keySpec == null) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); try { setup(ad); } catch (InvalidKeyException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (InvalidAlgorithmParameterException e) { // Shouldn't happen. throw new IllegalStateException(e); } ghash.update(ciphertext, ciphertextOffset, dataLen); ghash.pad(ad != null ? ad.length : 0, dataLen); ghash.finish(iv, 0, 16); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (hashKey[index] ^ iv[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); try { int result = cipher.update(ciphertext, ciphertextOffset, dataLen, plaintext, plaintextOffset); cipher.doFinal(plaintext, plaintextOffset + result); } catch (IllegalBlockSizeException e) { // Shouldn't happen. throw new IllegalStateException(e); } catch (BadPaddingException e) { // Shouldn't happen. throw new IllegalStateException(e); } return dataLen; } @Override public CipherState fork(byte[] key, int offset) { CipherState cipher; try { cipher = new AESGCMOnCtrCipherState(); } catch (NoSuchAlgorithmException e) { // Shouldn't happen. return null; } cipher.initializeKey(key, offset); return cipher; } @Override public void setNonce(long nonce) { n = nonce; } }
./CrossVul/dataset_final_sorted/CWE-119/java/bad_4291_2
crossvul-java_data_bad_2139_0
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.jboss.netty.handler.ssl; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelDownstreamHandler; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.DefaultChannelFuture; import org.jboss.netty.channel.DownstreamMessageEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.frame.FrameDecoder; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.Timeout; import org.jboss.netty.util.Timer; import org.jboss.netty.util.TimerTask; import org.jboss.netty.util.internal.DetectionUtil; import org.jboss.netty.util.internal.NonReentrantLock; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.DatagramChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.regex.Pattern; import static org.jboss.netty.channel.Channels.*; /** * Adds <a href="http://en.wikipedia.org/wiki/Transport_Layer_Security">SSL * &middot; TLS</a> and StartTLS support to a {@link Channel}. Please refer * to the <strong>"SecureChat"</strong> example in the distribution or the web * site for the detailed usage. * * <h3>Beginning the handshake</h3> * <p> * You must make sure not to write a message while the * {@linkplain #handshake() handshake} is in progress unless you are * renegotiating. You will be notified by the {@link ChannelFuture} which is * returned by the {@link #handshake()} method when the handshake * process succeeds or fails. * * <h3>Handshake</h3> * <p> * If {@link #isIssueHandshake()} is {@code false} * (default) you will need to take care of calling {@link #handshake()} by your own. In most * situations were {@link SslHandler} is used in 'client mode' you want to issue a handshake once * the connection was established. if {@link #setIssueHandshake(boolean)} is set to {@code true} * you don't need to worry about this as the {@link SslHandler} will take care of it. * <p> * * <h3>Renegotiation</h3> * <p> * If {@link #isEnableRenegotiation() enableRenegotiation} is {@code true} * (default) and the initial handshake has been done successfully, you can call * {@link #handshake()} to trigger the renegotiation. * <p> * If {@link #isEnableRenegotiation() enableRenegotiation} is {@code false}, * an attempt to trigger renegotiation will result in the connection closure. * <p> * Please note that TLS renegotiation had a security issue before. If your * runtime environment did not fix it, please make sure to disable TLS * renegotiation by calling {@link #setEnableRenegotiation(boolean)} with * {@code false}. For more information, please refer to the following documents: * <ul> * <li><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3555">CVE-2009-3555</a></li> * <li><a href="http://www.ietf.org/rfc/rfc5746.txt">RFC5746</a></li> * <li><a href="http://www.oracle.com/technetwork/java/javase/documentation/tlsreadme2-176330.html">Phased * Approach to Fixing the TLS Renegotiation Issue</a></li> * </ul> * * <h3>Closing the session</h3> * <p> * To close the SSL session, the {@link #close()} method should be * called to send the {@code close_notify} message to the remote peer. One * exception is when you close the {@link Channel} - {@link SslHandler} * intercepts the close request and send the {@code close_notify} message * before the channel closure automatically. Once the SSL session is closed, * it is not reusable, and consequently you should create a new * {@link SslHandler} with a new {@link SSLEngine} as explained in the * following section. * * <h3>Restarting the session</h3> * <p> * To restart the SSL session, you must remove the existing closed * {@link SslHandler} from the {@link ChannelPipeline}, insert a new * {@link SslHandler} with a new {@link SSLEngine} into the pipeline, * and start the handshake process as described in the first section. * * <h3>Implementing StartTLS</h3> * <p> * <a href="http://en.wikipedia.org/wiki/STARTTLS">StartTLS</a> is the * communication pattern that secures the wire in the middle of the plaintext * connection. Please note that it is different from SSL &middot; TLS, that * secures the wire from the beginning of the connection. Typically, StartTLS * is composed of three steps: * <ol> * <li>Client sends a StartTLS request to server.</li> * <li>Server sends a StartTLS response to client.</li> * <li>Client begins SSL handshake.</li> * </ol> * If you implement a server, you need to: * <ol> * <li>create a new {@link SslHandler} instance with {@code startTls} flag set * to {@code true},</li> * <li>insert the {@link SslHandler} to the {@link ChannelPipeline}, and</li> * <li>write a StartTLS response.</li> * </ol> * Please note that you must insert {@link SslHandler} <em>before</em> sending * the StartTLS response. Otherwise the client can send begin SSL handshake * before {@link SslHandler} is inserted to the {@link ChannelPipeline}, causing * data corruption. * <p> * The client-side implementation is much simpler. * <ol> * <li>Write a StartTLS request,</li> * <li>wait for the StartTLS response,</li> * <li>create a new {@link SslHandler} instance with {@code startTls} flag set * to {@code false},</li> * <li>insert the {@link SslHandler} to the {@link ChannelPipeline}, and</li> * <li>Initiate SSL handshake by calling {@link SslHandler#handshake()}.</li> * </ol> * * <h3>Known issues</h3> * <p> * Because of a known issue with the current implementation of the SslEngine that comes * with Java it may be possible that you see blocked IO-Threads while a full GC is done. * <p> * So if you are affected you can workaround this problem by adjust the cache settings * like shown below: * * <pre> * SslContext context = ...; * context.getServerSessionContext().setSessionCacheSize(someSaneSize); * context.getServerSessionContext().setSessionTime(someSameTimeout); * </pre> * <p> * What values to use here depends on the nature of your application and should be set * based on monitoring and debugging of it. * For more details see * <a href="https://github.com/netty/netty/issues/832">#832</a> in our issue tracker. * @apiviz.landmark * @apiviz.uses org.jboss.netty.handler.ssl.SslBufferPool */ public class SslHandler extends FrameDecoder implements ChannelDownstreamHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(SslHandler.class); private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); private static final Pattern IGNORABLE_CLASS_IN_STACK = Pattern.compile( "^.*(?:Socket|Datagram|Sctp|Udt)Channel.*$"); private static final Pattern IGNORABLE_ERROR_MESSAGE = Pattern.compile( "^.*(?:connection.*(?:reset|closed|abort|broken)|broken.*pipe).*$", Pattern.CASE_INSENSITIVE); private static SslBufferPool defaultBufferPool; /** * Returns the default {@link SslBufferPool} used when no pool is * specified in the constructor. */ public static synchronized SslBufferPool getDefaultBufferPool() { if (defaultBufferPool == null) { defaultBufferPool = new SslBufferPool(); } return defaultBufferPool; } private volatile ChannelHandlerContext ctx; private final SSLEngine engine; private final SslBufferPool bufferPool; private final Executor delegatedTaskExecutor; private final boolean startTls; private volatile boolean enableRenegotiation = true; final Object handshakeLock = new Object(); private boolean handshaking; private volatile boolean handshaken; private volatile ChannelFuture handshakeFuture; @SuppressWarnings("UnusedDeclaration") private volatile int sentFirstMessage; @SuppressWarnings("UnusedDeclaration") private volatile int sentCloseNotify; @SuppressWarnings("UnusedDeclaration") private volatile int closedOutboundAndChannel; private static final AtomicIntegerFieldUpdater<SslHandler> SENT_FIRST_MESSAGE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(SslHandler.class, "sentFirstMessage"); private static final AtomicIntegerFieldUpdater<SslHandler> SENT_CLOSE_NOTIFY_UPDATER = AtomicIntegerFieldUpdater.newUpdater(SslHandler.class, "sentCloseNotify"); private static final AtomicIntegerFieldUpdater<SslHandler> CLOSED_OUTBOUND_AND_CHANNEL_UPDATER = AtomicIntegerFieldUpdater.newUpdater(SslHandler.class, "closedOutboundAndChannel"); int ignoreClosedChannelException; final Object ignoreClosedChannelExceptionLock = new Object(); private final Queue<PendingWrite> pendingUnencryptedWrites = new LinkedList<PendingWrite>(); private final NonReentrantLock pendingUnencryptedWritesLock = new NonReentrantLock(); private final Queue<MessageEvent> pendingEncryptedWrites = new ConcurrentLinkedQueue<MessageEvent>(); private final NonReentrantLock pendingEncryptedWritesLock = new NonReentrantLock(); private volatile boolean issueHandshake; private volatile boolean writeBeforeHandshakeDone; private final SSLEngineInboundCloseFuture sslEngineCloseFuture = new SSLEngineInboundCloseFuture(); private boolean closeOnSslException; private int packetLength; private final Timer timer; private final long handshakeTimeoutInMillis; private Timeout handshakeTimeout; /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use */ public SslHandler(SSLEngine engine) { this(engine, getDefaultBufferPool(), false, null, 0); } /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use * @param bufferPool the {@link SslBufferPool} where this handler will * acquire the buffers required by the {@link SSLEngine} */ public SslHandler(SSLEngine engine, SslBufferPool bufferPool) { this(engine, bufferPool, false, null, 0); } /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use * @param startTls {@code true} if the first write request shouldn't be * encrypted by the {@link SSLEngine} */ public SslHandler(SSLEngine engine, boolean startTls) { this(engine, getDefaultBufferPool(), startTls); } /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use * @param bufferPool the {@link SslBufferPool} where this handler will * acquire the buffers required by the {@link SSLEngine} * @param startTls {@code true} if the first write request shouldn't be * encrypted by the {@link SSLEngine} */ public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls) { this(engine, bufferPool, startTls, null, 0); } /** * Creates a new instance. * * @param engine * the {@link SSLEngine} this handler will use * @param bufferPool * the {@link SslBufferPool} where this handler will acquire * the buffers required by the {@link SSLEngine} * @param startTls * {@code true} if the first write request shouldn't be encrypted * by the {@link SSLEngine} * @param timer * the {@link Timer} which will be used to process the timeout of the {@link #handshake()}. * Be aware that the given {@link Timer} will not get stopped automaticly, so it is up to you to cleanup * once you not need it anymore * @param handshakeTimeoutInMillis * the time in milliseconds after whic the {@link #handshake()} will be failed, and so the future notified */ @SuppressWarnings("deprecation") public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Timer timer, long handshakeTimeoutInMillis) { this(engine, bufferPool, startTls, ImmediateExecutor.INSTANCE, timer, handshakeTimeoutInMillis); } /** * @deprecated Use {@link #SslHandler(SSLEngine)} instead. */ @Deprecated public SslHandler(SSLEngine engine, Executor delegatedTaskExecutor) { this(engine, getDefaultBufferPool(), delegatedTaskExecutor); } /** * @deprecated Use {@link #SslHandler(SSLEngine, boolean)} instead. */ @Deprecated public SslHandler(SSLEngine engine, SslBufferPool bufferPool, Executor delegatedTaskExecutor) { this(engine, bufferPool, false, delegatedTaskExecutor); } /** * @deprecated Use {@link #SslHandler(SSLEngine, boolean)} instead. */ @Deprecated public SslHandler(SSLEngine engine, boolean startTls, Executor delegatedTaskExecutor) { this(engine, getDefaultBufferPool(), startTls, delegatedTaskExecutor); } /** * @deprecated Use {@link #SslHandler(SSLEngine, SslBufferPool, boolean)} instead. */ @Deprecated public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Executor delegatedTaskExecutor) { this(engine, bufferPool, startTls, delegatedTaskExecutor, null, 0); } /** * @deprecated Use {@link #SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Timer timer, * long handshakeTimeoutInMillis)} instead. */ @Deprecated public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Executor delegatedTaskExecutor, Timer timer, long handshakeTimeoutInMillis) { if (engine == null) { throw new NullPointerException("engine"); } if (bufferPool == null) { throw new NullPointerException("bufferPool"); } if (delegatedTaskExecutor == null) { throw new NullPointerException("delegatedTaskExecutor"); } if (timer == null && handshakeTimeoutInMillis > 0) { throw new IllegalArgumentException("No Timer was given but a handshakeTimeoutInMillis, need both or none"); } this.engine = engine; this.bufferPool = bufferPool; this.delegatedTaskExecutor = delegatedTaskExecutor; this.startTls = startTls; this.timer = timer; this.handshakeTimeoutInMillis = handshakeTimeoutInMillis; } /** * Returns the {@link SSLEngine} which is used by this handler. */ public SSLEngine getEngine() { return engine; } /** * Starts an SSL / TLS handshake for the specified channel. * * @return a {@link ChannelFuture} which is notified when the handshake * succeeds or fails. */ public ChannelFuture handshake() { synchronized (handshakeLock) { if (handshaken && !isEnableRenegotiation()) { throw new IllegalStateException("renegotiation disabled"); } final ChannelHandlerContext ctx = this.ctx; final Channel channel = ctx.getChannel(); ChannelFuture handshakeFuture; Exception exception = null; if (handshaking) { return this.handshakeFuture; } handshaking = true; try { engine.beginHandshake(); runDelegatedTasks(); handshakeFuture = this.handshakeFuture = future(channel); if (handshakeTimeoutInMillis > 0) { handshakeTimeout = timer.newTimeout(new TimerTask() { public void run(Timeout timeout) throws Exception { ChannelFuture future = SslHandler.this.handshakeFuture; if (future != null && future.isDone()) { return; } setHandshakeFailure(channel, new SSLException("Handshake did not complete within " + handshakeTimeoutInMillis + "ms")); } }, handshakeTimeoutInMillis, TimeUnit.MILLISECONDS); } } catch (Exception e) { handshakeFuture = this.handshakeFuture = failedFuture(channel, e); exception = e; } if (exception == null) { // Began handshake successfully. try { final ChannelFuture hsFuture = handshakeFuture; wrapNonAppData(ctx, channel).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { Throwable cause = future.getCause(); hsFuture.setFailure(cause); fireExceptionCaught(ctx, cause); if (closeOnSslException) { Channels.close(ctx, future(channel)); } } } }); } catch (SSLException e) { handshakeFuture.setFailure(e); fireExceptionCaught(ctx, e); if (closeOnSslException) { Channels.close(ctx, future(channel)); } } } else { // Failed to initiate handshake. fireExceptionCaught(ctx, exception); if (closeOnSslException) { Channels.close(ctx, future(channel)); } } return handshakeFuture; } } /** * @deprecated Use {@link #handshake()} instead. */ @Deprecated public ChannelFuture handshake(@SuppressWarnings("unused") Channel channel) { return handshake(); } /** * Sends an SSL {@code close_notify} message to the specified channel and * destroys the underlying {@link SSLEngine}. */ public ChannelFuture close() { ChannelHandlerContext ctx = this.ctx; Channel channel = ctx.getChannel(); try { engine.closeOutbound(); return wrapNonAppData(ctx, channel); } catch (SSLException e) { fireExceptionCaught(ctx, e); if (closeOnSslException) { Channels.close(ctx, future(channel)); } return failedFuture(channel, e); } } /** * @deprecated Use {@link #close()} instead. */ @Deprecated public ChannelFuture close(@SuppressWarnings("unused") Channel channel) { return close(); } /** * Returns {@code true} if and only if TLS renegotiation is enabled. */ public boolean isEnableRenegotiation() { return enableRenegotiation; } /** * Enables or disables TLS renegotiation. */ public void setEnableRenegotiation(boolean enableRenegotiation) { this.enableRenegotiation = enableRenegotiation; } /** * Enables or disables the automatic handshake once the {@link Channel} is * connected. The value will only have affect if its set before the * {@link Channel} is connected. */ public void setIssueHandshake(boolean issueHandshake) { this.issueHandshake = issueHandshake; } /** * Returns {@code true} if the automatic handshake is enabled */ public boolean isIssueHandshake() { return issueHandshake; } /** * Return the {@link ChannelFuture} that will get notified if the inbound of the {@link SSLEngine} will get closed. * * This method will return the same {@link ChannelFuture} all the time. * * For more informations see the apidocs of {@link SSLEngine} * */ public ChannelFuture getSSLEngineInboundCloseFuture() { return sslEngineCloseFuture; } /** * Return the timeout (in ms) after which the {@link ChannelFuture} of {@link #handshake()} will be failed, while * a handshake is in progress */ public long getHandshakeTimeout() { return handshakeTimeoutInMillis; } /** * If set to {@code true}, the {@link Channel} will automatically get closed * one a {@link SSLException} was caught. This is most times what you want, as after this * its almost impossible to recover. * * Anyway the default is {@code false} to not break compatibility with older releases. This * will be changed to {@code true} in the next major release. * */ public void setCloseOnSSLException(boolean closeOnSslException) { if (ctx != null) { throw new IllegalStateException("Can only get changed before attached to ChannelPipeline"); } this.closeOnSslException = closeOnSslException; } public boolean getCloseOnSSLException() { return closeOnSslException; } public void handleDownstream( final ChannelHandlerContext context, final ChannelEvent evt) throws Exception { if (evt instanceof ChannelStateEvent) { ChannelStateEvent e = (ChannelStateEvent) evt; switch (e.getState()) { case OPEN: case CONNECTED: case BOUND: if (Boolean.FALSE.equals(e.getValue()) || e.getValue() == null) { closeOutboundAndChannel(context, e); return; } } } if (!(evt instanceof MessageEvent)) { context.sendDownstream(evt); return; } MessageEvent e = (MessageEvent) evt; if (!(e.getMessage() instanceof ChannelBuffer)) { context.sendDownstream(evt); return; } // Do not encrypt the first write request if this handler is // created with startTLS flag turned on. if (startTls && SENT_FIRST_MESSAGE_UPDATER.compareAndSet(this, 0, 1)) { context.sendDownstream(evt); return; } // Otherwise, all messages are encrypted. ChannelBuffer msg = (ChannelBuffer) e.getMessage(); PendingWrite pendingWrite; if (msg.readable()) { pendingWrite = new PendingWrite(evt.getFuture(), msg.toByteBuffer(msg.readerIndex(), msg.readableBytes())); } else { pendingWrite = new PendingWrite(evt.getFuture(), null); } pendingUnencryptedWritesLock.lock(); try { pendingUnencryptedWrites.add(pendingWrite); } finally { pendingUnencryptedWritesLock.unlock(); } if (handshakeFuture == null || !handshakeFuture.isDone()) { writeBeforeHandshakeDone = true; } wrap(context, evt.getChannel()); } private void cancelHandshakeTimeout() { if (handshakeTimeout != null) { // cancel the task as we will fail the handshake future now handshakeTimeout.cancel(); } } @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Make sure the handshake future is notified when a connection has // been closed during handshake. synchronized (handshakeLock) { if (handshaking) { cancelHandshakeTimeout(); handshakeFuture.setFailure(new ClosedChannelException()); } } try { super.channelDisconnected(ctx, e); } finally { unwrapNonAppData(ctx, e.getChannel()); closeEngine(); } } private void closeEngine() { engine.closeOutbound(); if (sentCloseNotify == 0 && handshaken) { try { engine.closeInbound(); } catch (SSLException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to clean up SSLEngine.", ex); } } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Throwable cause = e.getCause(); if (cause instanceof IOException) { if (cause instanceof ClosedChannelException) { synchronized (ignoreClosedChannelExceptionLock) { if (ignoreClosedChannelException > 0) { ignoreClosedChannelException --; if (logger.isDebugEnabled()) { logger.debug( "Swallowing an exception raised while " + "writing non-app data", cause); } return; } } } else { if (ignoreException(cause)) { return; } } } ctx.sendUpstream(e); } /** * Checks if the given {@link Throwable} can be ignore and just "swallowed" * * When an ssl connection is closed a close_notify message is sent. * After that the peer also sends close_notify however, it's not mandatory to receive * the close_notify. The party who sent the initial close_notify can close the connection immediately * then the peer will get connection reset error. * */ private boolean ignoreException(Throwable t) { if (!(t instanceof SSLException) && t instanceof IOException && engine.isOutboundDone()) { String message = String.valueOf(t.getMessage()).toLowerCase(); // first try to match connection reset / broke peer based on the regex. This is the fastest way // but may fail on different jdk impls or OS's if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) { return true; } // Inspect the StackTraceElements to see if it was a connection reset / broken pipe or not StackTraceElement[] elements = t.getStackTrace(); for (StackTraceElement element: elements) { String classname = element.getClassName(); String methodname = element.getMethodName(); // skip all classes that belong to the io.netty package if (classname.startsWith("org.jboss.netty.")) { continue; } // check if the method name is read if not skip it if (!"read".equals(methodname)) { continue; } // This will also match against SocketInputStream which is used by openjdk 7 and maybe // also others if (IGNORABLE_CLASS_IN_STACK.matcher(classname).matches()) { return true; } try { // No match by now.. Try to load the class via classloader and inspect it. // This is mainly done as other JDK implementations may differ in name of // the impl. Class<?> clazz = getClass().getClassLoader().loadClass(classname); if (SocketChannel.class.isAssignableFrom(clazz) || DatagramChannel.class.isAssignableFrom(clazz)) { return true; } // also match against SctpChannel via String matching as it may not present. if (DetectionUtil.javaVersion() >= 7 && "com.sun.nio.sctp.SctpChannel".equals(clazz.getSuperclass().getName())) { return true; } } catch (ClassNotFoundException e) { // This should not happen just ignore } } } return false; } /** * Returns {@code true} if the given {@link ChannelBuffer} is encrypted. Be aware that this method * will not increase the readerIndex of the given {@link ChannelBuffer}. * * @param buffer * The {@link ChannelBuffer} to read from. Be aware that it must have at least 5 bytes to read, * otherwise it will throw an {@link IllegalArgumentException}. * @return encrypted * {@code true} if the {@link ChannelBuffer} is encrypted, {@code false} otherwise. * @throws IllegalArgumentException * Is thrown if the given {@link ChannelBuffer} has not at least 5 bytes to read. */ public static boolean isEncrypted(ChannelBuffer buffer) { return getEncryptedPacketLength(buffer, buffer.readerIndex()) != -1; } /** * Return how much bytes can be read out of the encrypted data. Be aware that this method will not increase * the readerIndex of the given {@link ChannelBuffer}. * * @param buffer * The {@link ChannelBuffer} to read from. Be aware that it must have at least 5 bytes to read, * otherwise it will throw an {@link IllegalArgumentException}. * @return length * The length of the encrypted packet that is included in the buffer. This will * return {@code -1} if the given {@link ChannelBuffer} is not encrypted at all. * @throws IllegalArgumentException * Is thrown if the given {@link ChannelBuffer} has not at least 5 bytes to read. */ private static int getEncryptedPacketLength(ChannelBuffer buffer, int offset) { int packetLength = 0; // SSLv3 or TLS - Check ContentType boolean tls; switch (buffer.getUnsignedByte(offset)) { case 20: // change_cipher_spec case 21: // alert case 22: // handshake case 23: // application_data tls = true; break; default: // SSLv2 or bad data tls = false; } if (tls) { // SSLv3 or TLS - Check ProtocolVersion int majorVersion = buffer.getUnsignedByte(offset + 1); if (majorVersion == 3) { // SSLv3 or TLS packetLength = (getShort(buffer, offset + 3) & 0xFFFF) + 5; if (packetLength <= 5) { // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data) tls = false; } } else { // Neither SSLv3 or TLSv1 (i.e. SSLv2 or bad data) tls = false; } } if (!tls) { // SSLv2 or bad data - Check the version boolean sslv2 = true; int headerLength = (buffer.getUnsignedByte(offset) & 0x80) != 0 ? 2 : 3; int majorVersion = buffer.getUnsignedByte(offset + headerLength + 1); if (majorVersion == 2 || majorVersion == 3) { // SSLv2 if (headerLength == 2) { packetLength = (getShort(buffer, offset) & 0x7FFF) + 2; } else { packetLength = (getShort(buffer, offset) & 0x3FFF) + 3; } if (packetLength <= headerLength) { sslv2 = false; } } else { sslv2 = false; } if (!sslv2) { return -1; } } return packetLength; } @Override protected Object decode( final ChannelHandlerContext ctx, Channel channel, ChannelBuffer in) throws Exception { final int startOffset = in.readerIndex(); final int endOffset = in.writerIndex(); int offset = startOffset; int totalLength = 0; // If we calculated the length of the current SSL record before, use that information. if (packetLength > 0) { if (endOffset - startOffset < packetLength) { return null; } else { offset += packetLength; totalLength = packetLength; packetLength = 0; } } boolean nonSslRecord = false; while (totalLength < OpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) { final int readableBytes = endOffset - offset; if (readableBytes < 5) { break; } final int packetLength = getEncryptedPacketLength(in, offset); if (packetLength == -1) { nonSslRecord = true; break; } assert packetLength > 0; if (packetLength > readableBytes) { // wait until the whole packet can be read this.packetLength = packetLength; break; } int newTotalLength = totalLength + packetLength; if (newTotalLength > OpenSslEngine.MAX_ENCRYPTED_PACKET_LENGTH) { // Don't read too much. break; } // We have a whole packet. // Increment the offset to handle the next packet. offset += packetLength; totalLength = newTotalLength; } ChannelBuffer unwrapped = null; if (totalLength > 0) { // The buffer contains one or more full SSL records. // Slice out the whole packet so unwrap will only be called with complete packets. // Also directly reset the packetLength. This is needed as unwrap(..) may trigger // decode(...) again via: // 1) unwrap(..) is called // 2) wrap(...) is called from within unwrap(...) // 3) wrap(...) calls unwrapLater(...) // 4) unwrapLater(...) calls decode(...) // // See https://github.com/netty/netty/issues/1534 final ByteBuffer inNetBuf = in.toByteBuffer(in.readerIndex(), totalLength); unwrapped = unwrap(ctx, channel, in, inNetBuf, totalLength); assert !inNetBuf.hasRemaining() || engine.isInboundDone(); } if (nonSslRecord) { // Not an SSL/TLS packet NotSslRecordException e = new NotSslRecordException( "not an SSL/TLS record: " + ChannelBuffers.hexDump(in)); in.skipBytes(in.readableBytes()); if (closeOnSslException) { // first trigger the exception and then close the channel fireExceptionCaught(ctx, e); Channels.close(ctx, future(channel)); // just return null as we closed the channel before, that // will take care of cleanup etc return null; } else { throw e; } } return unwrapped; } /** * Reads a big-endian short integer from the buffer. Please note that we do not use * {@link ChannelBuffer#getShort(int)} because it might be a little-endian buffer. */ private static short getShort(ChannelBuffer buf, int offset) { return (short) (buf.getByte(offset) << 8 | buf.getByte(offset + 1) & 0xFF); } private void wrap(ChannelHandlerContext context, Channel channel) throws SSLException { ChannelBuffer msg; ByteBuffer outNetBuf = bufferPool.acquireBuffer(); boolean success = true; boolean offered = false; boolean needsUnwrap = false; PendingWrite pendingWrite = null; try { loop: for (;;) { // Acquire a lock to make sure unencrypted data is polled // in order and their encrypted counterpart is offered in // order. pendingUnencryptedWritesLock.lock(); try { pendingWrite = pendingUnencryptedWrites.peek(); if (pendingWrite == null) { break; } ByteBuffer outAppBuf = pendingWrite.outAppBuf; if (outAppBuf == null) { // A write request with an empty buffer pendingUnencryptedWrites.remove(); offerEncryptedWriteRequest( new DownstreamMessageEvent( channel, pendingWrite.future, ChannelBuffers.EMPTY_BUFFER, channel.getRemoteAddress())); offered = true; } else { synchronized (handshakeLock) { SSLEngineResult result = null; try { result = engine.wrap(outAppBuf, outNetBuf); } finally { if (!outAppBuf.hasRemaining()) { pendingUnencryptedWrites.remove(); } } if (result.bytesProduced() > 0) { outNetBuf.flip(); int remaining = outNetBuf.remaining(); msg = ctx.getChannel().getConfig().getBufferFactory().getBuffer(remaining); // Transfer the bytes to the new ChannelBuffer using some safe method that will also // work with "non" heap buffers // // See https://github.com/netty/netty/issues/329 msg.writeBytes(outNetBuf); outNetBuf.clear(); ChannelFuture future; if (pendingWrite.outAppBuf.hasRemaining()) { // pendingWrite's future shouldn't be notified if // only partial data is written. future = succeededFuture(channel); } else { future = pendingWrite.future; } MessageEvent encryptedWrite = new DownstreamMessageEvent( channel, future, msg, channel.getRemoteAddress()); offerEncryptedWriteRequest(encryptedWrite); offered = true; } else if (result.getStatus() == Status.CLOSED) { // SSLEngine has been closed already. // Any further write attempts should be denied. success = false; break; } else { final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); handleRenegotiation(handshakeStatus); switch (handshakeStatus) { case NEED_WRAP: if (outAppBuf.hasRemaining()) { break; } else { break loop; } case NEED_UNWRAP: needsUnwrap = true; break loop; case NEED_TASK: runDelegatedTasks(); break; case FINISHED: setHandshakeSuccess(channel); if (result.getStatus() == Status.CLOSED) { success = false; } break loop; case NOT_HANDSHAKING: setHandshakeSuccessIfStillHandshaking(channel); if (result.getStatus() == Status.CLOSED) { success = false; } break loop; default: throw new IllegalStateException( "Unknown handshake status: " + handshakeStatus); } } } } } finally { pendingUnencryptedWritesLock.unlock(); } } } catch (SSLException e) { success = false; setHandshakeFailure(channel, e); throw e; } finally { bufferPool.releaseBuffer(outNetBuf); if (offered) { flushPendingEncryptedWrites(context); } if (!success) { IllegalStateException cause = new IllegalStateException("SSLEngine already closed"); // Check if we had a pendingWrite in process, if so we need to also notify as otherwise // the ChannelFuture will never get notified if (pendingWrite != null) { pendingWrite.future.setFailure(cause); } // Mark all remaining pending writes as failure if anything // wrong happened before the write requests are wrapped. // Please note that we do not call setFailure while a lock is // acquired, to avoid a potential dead lock. for (;;) { pendingUnencryptedWritesLock.lock(); try { pendingWrite = pendingUnencryptedWrites.poll(); if (pendingWrite == null) { break; } } finally { pendingUnencryptedWritesLock.unlock(); } pendingWrite.future.setFailure(cause); } } } if (needsUnwrap) { unwrapNonAppData(ctx, channel); } } private void offerEncryptedWriteRequest(MessageEvent encryptedWrite) { final boolean locked = pendingEncryptedWritesLock.tryLock(); try { pendingEncryptedWrites.add(encryptedWrite); } finally { if (locked) { pendingEncryptedWritesLock.unlock(); } } } private void flushPendingEncryptedWrites(ChannelHandlerContext ctx) { while (!pendingEncryptedWrites.isEmpty()) { // Avoid possible dead lock and data integrity issue // which is caused by cross communication between more than one channel // in the same VM. if (!pendingEncryptedWritesLock.tryLock()) { return; } try { MessageEvent e; while ((e = pendingEncryptedWrites.poll()) != null) { ctx.sendDownstream(e); } } finally { pendingEncryptedWritesLock.unlock(); } // Other thread might have added more elements at this point, so we loop again if the queue got unempty. } } private ChannelFuture wrapNonAppData(ChannelHandlerContext ctx, Channel channel) throws SSLException { ChannelFuture future = null; ByteBuffer outNetBuf = bufferPool.acquireBuffer(); SSLEngineResult result; try { for (;;) { synchronized (handshakeLock) { result = engine.wrap(EMPTY_BUFFER, outNetBuf); } if (result.bytesProduced() > 0) { outNetBuf.flip(); ChannelBuffer msg = ctx.getChannel().getConfig().getBufferFactory().getBuffer(outNetBuf.remaining()); // Transfer the bytes to the new ChannelBuffer using some safe method that will also // work with "non" heap buffers // // See https://github.com/netty/netty/issues/329 msg.writeBytes(outNetBuf); outNetBuf.clear(); future = future(channel); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.getCause() instanceof ClosedChannelException) { synchronized (ignoreClosedChannelExceptionLock) { ignoreClosedChannelException ++; } } } }); write(ctx, future, msg); } final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); handleRenegotiation(handshakeStatus); switch (handshakeStatus) { case FINISHED: setHandshakeSuccess(channel); runDelegatedTasks(); break; case NEED_TASK: runDelegatedTasks(); break; case NEED_UNWRAP: if (!Thread.holdsLock(handshakeLock)) { // unwrap shouldn't be called when this method was // called by unwrap - unwrap will keep running after // this method returns. unwrapNonAppData(ctx, channel); } break; case NOT_HANDSHAKING: if (setHandshakeSuccessIfStillHandshaking(channel)) { runDelegatedTasks(); } break; case NEED_WRAP: break; default: throw new IllegalStateException( "Unexpected handshake status: " + handshakeStatus); } if (result.bytesProduced() == 0) { break; } } } catch (SSLException e) { setHandshakeFailure(channel, e); throw e; } finally { bufferPool.releaseBuffer(outNetBuf); } if (future == null) { future = succeededFuture(channel); } return future; } /** * Calls {@link SSLEngine#unwrap(ByteBuffer, ByteBuffer)} with an empty buffer to handle handshakes, etc. */ private void unwrapNonAppData(ChannelHandlerContext ctx, Channel channel) throws SSLException { unwrap(ctx, channel, ChannelBuffers.EMPTY_BUFFER, EMPTY_BUFFER, -1); } /** * Unwraps inbound SSL records. */ private ChannelBuffer unwrap( ChannelHandlerContext ctx, Channel channel, ChannelBuffer nettyInNetBuf, ByteBuffer nioInNetBuf, int initialNettyOutAppBufCapacity) throws SSLException { final int nettyInNetBufStartOffset = nettyInNetBuf.readerIndex(); final int nioInNetBufStartOffset = nioInNetBuf.position(); final ByteBuffer nioOutAppBuf = bufferPool.acquireBuffer(); ChannelBuffer nettyOutAppBuf = null; try { boolean needsWrap = false; for (;;) { SSLEngineResult result; boolean needsHandshake = false; synchronized (handshakeLock) { if (!handshaken && !handshaking && !engine.getUseClientMode() && !engine.isInboundDone() && !engine.isOutboundDone()) { needsHandshake = true; } } if (needsHandshake) { handshake(); } synchronized (handshakeLock) { // Decrypt at least one record in the inbound network buffer. // It is impossible to consume no record here because we made sure the inbound network buffer // always contain at least one record in decode(). Therefore, if SSLEngine.unwrap() returns // BUFFER_OVERFLOW, it is always resolved by retrying after emptying the application buffer. for (;;) { try { result = engine.unwrap(nioInNetBuf, nioOutAppBuf); switch (result.getStatus()) { case CLOSED: // notify about the CLOSED state of the SSLEngine. See #137 sslEngineCloseFuture.setClosed(); break; case BUFFER_OVERFLOW: // Flush the unwrapped data in the outAppBuf into frame and try again. // See the finally block. continue; } break; } finally { nioOutAppBuf.flip(); // Sync the offset of the inbound buffer. nettyInNetBuf.readerIndex( nettyInNetBufStartOffset + nioInNetBuf.position() - nioInNetBufStartOffset); // Copy the unwrapped data into a smaller buffer. if (nioOutAppBuf.hasRemaining()) { if (nettyOutAppBuf == null) { ChannelBufferFactory factory = ctx.getChannel().getConfig().getBufferFactory(); nettyOutAppBuf = factory.getBuffer(initialNettyOutAppBufCapacity); } nettyOutAppBuf.writeBytes(nioOutAppBuf); } nioOutAppBuf.clear(); } } final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); handleRenegotiation(handshakeStatus); switch (handshakeStatus) { case NEED_UNWRAP: break; case NEED_WRAP: wrapNonAppData(ctx, channel); break; case NEED_TASK: runDelegatedTasks(); break; case FINISHED: setHandshakeSuccess(channel); needsWrap = true; continue; case NOT_HANDSHAKING: if (setHandshakeSuccessIfStillHandshaking(channel)) { needsWrap = true; continue; } if (writeBeforeHandshakeDone) { // We need to call wrap(...) in case there was a flush done before the handshake completed. // // See https://github.com/netty/netty/pull/2437 writeBeforeHandshakeDone = false; needsWrap = true; } break; default: throw new IllegalStateException( "Unknown handshake status: " + handshakeStatus); } if (result.getStatus() == Status.BUFFER_UNDERFLOW || result.bytesConsumed() == 0 && result.bytesProduced() == 0) { break; } } } if (needsWrap) { // wrap() acquires pendingUnencryptedWrites first and then // handshakeLock. If handshakeLock is already hold by the // current thread, calling wrap() will lead to a dead lock // i.e. pendingUnencryptedWrites -> handshakeLock vs. // handshakeLock -> pendingUnencryptedLock -> handshakeLock // // There is also the same issue between pendingEncryptedWrites // and pendingUnencryptedWrites. if (!Thread.holdsLock(handshakeLock) && !pendingEncryptedWritesLock.isHeldByCurrentThread()) { wrap(ctx, channel); } } } catch (SSLException e) { setHandshakeFailure(channel, e); throw e; } finally { bufferPool.releaseBuffer(nioOutAppBuf); } if (nettyOutAppBuf != null && nettyOutAppBuf.readable()) { return nettyOutAppBuf; } else { return null; } } private void handleRenegotiation(HandshakeStatus handshakeStatus) { synchronized (handshakeLock) { if (handshakeStatus == HandshakeStatus.NOT_HANDSHAKING || handshakeStatus == HandshakeStatus.FINISHED) { // Not handshaking return; } if (!handshaken) { // Not renegotiation return; } final boolean renegotiate; if (handshaking) { // Renegotiation in progress or failed already. // i.e. Renegotiation check has been done already below. return; } if (engine.isInboundDone() || engine.isOutboundDone()) { // Not handshaking but closing. return; } if (isEnableRenegotiation()) { // Continue renegotiation. renegotiate = true; } else { // Do not renegotiate. renegotiate = false; // Prevent reentrance of this method. handshaking = true; } if (renegotiate) { // Renegotiate. handshake(); } else { // Raise an exception. fireExceptionCaught( ctx, new SSLException( "renegotiation attempted by peer; " + "closing the connection")); // Close the connection to stop renegotiation. Channels.close(ctx, succeededFuture(ctx.getChannel())); } } } /** * Fetches all delegated tasks from the {@link SSLEngine} and runs them via the {@link #delegatedTaskExecutor}. * If the {@link #delegatedTaskExecutor} is {@link ImmediateExecutor}, just call {@link Runnable#run()} directly * instead of using {@link Executor#execute(Runnable)}. Otherwise, run the tasks via * the {@link #delegatedTaskExecutor} and wait until the tasks are finished. */ private void runDelegatedTasks() { if (delegatedTaskExecutor == ImmediateExecutor.INSTANCE) { for (;;) { final Runnable task; synchronized (handshakeLock) { task = engine.getDelegatedTask(); } if (task == null) { break; } delegatedTaskExecutor.execute(task); } } else { final List<Runnable> tasks = new ArrayList<Runnable>(2); for (;;) { final Runnable task; synchronized (handshakeLock) { task = engine.getDelegatedTask(); } if (task == null) { break; } tasks.add(task); } if (tasks.isEmpty()) { return; } final CountDownLatch latch = new CountDownLatch(1); delegatedTaskExecutor.execute(new Runnable() { public void run() { try { for (Runnable task: tasks) { task.run(); } } catch (Exception e) { fireExceptionCaught(ctx, e); } finally { latch.countDown(); } } }); boolean interrupted = false; while (latch.getCount() != 0) { try { latch.await(); } catch (InterruptedException e) { // Interrupt later. interrupted = true; } } if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Works around some Android {@link SSLEngine} implementations that skip {@link HandshakeStatus#FINISHED} and * go straight into {@link HandshakeStatus#NOT_HANDSHAKING} when handshake is finished. * * @return {@code true} if and only if the workaround has been applied and thus {@link #handshakeFuture} has been * marked as success by this method */ private boolean setHandshakeSuccessIfStillHandshaking(Channel channel) { if (handshaking && !handshakeFuture.isDone()) { setHandshakeSuccess(channel); return true; } return false; } private void setHandshakeSuccess(Channel channel) { synchronized (handshakeLock) { handshaking = false; handshaken = true; if (handshakeFuture == null) { handshakeFuture = future(channel); } cancelHandshakeTimeout(); } if (logger.isDebugEnabled()) { logger.debug(channel + " HANDSHAKEN: " + engine.getSession().getCipherSuite()); } handshakeFuture.setSuccess(); } private void setHandshakeFailure(Channel channel, SSLException cause) { synchronized (handshakeLock) { if (!handshaking) { return; } handshaking = false; handshaken = false; if (handshakeFuture == null) { handshakeFuture = future(channel); } // cancel the timeout now cancelHandshakeTimeout(); // Release all resources such as internal buffers that SSLEngine // is managing. engine.closeOutbound(); try { engine.closeInbound(); } catch (SSLException e) { if (logger.isDebugEnabled()) { logger.debug( "SSLEngine.closeInbound() raised an exception after " + "a handshake failure.", e); } } } handshakeFuture.setFailure(cause); if (closeOnSslException) { Channels.close(ctx, future(channel)); } } private void closeOutboundAndChannel( final ChannelHandlerContext context, final ChannelStateEvent e) { if (!e.getChannel().isConnected()) { context.sendDownstream(e); return; } // Ensure that the tear-down logic beyond this point is never invoked concurrently nor multiple times. if (!CLOSED_OUTBOUND_AND_CHANNEL_UPDATER.compareAndSet(this, 0, 1)) { // The other thread called this method already, and thus the connection will be closed eventually. // So, just wait until the connection is closed, and then forward the event so that the sink handles // the duplicate close attempt. e.getChannel().getCloseFuture().addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { context.sendDownstream(e); } }); return; } boolean passthrough = true; try { try { unwrapNonAppData(ctx, e.getChannel()); } catch (SSLException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to unwrap before sending a close_notify message", ex); } } if (!engine.isOutboundDone()) { if (SENT_CLOSE_NOTIFY_UPDATER.compareAndSet(this, 0, 1)) { engine.closeOutbound(); try { ChannelFuture closeNotifyFuture = wrapNonAppData(context, e.getChannel()); closeNotifyFuture.addListener( new ClosingChannelFutureListener(context, e)); passthrough = false; } catch (SSLException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to encode a close_notify message", ex); } } } } } finally { if (passthrough) { context.sendDownstream(e); } } } private static final class PendingWrite { final ChannelFuture future; final ByteBuffer outAppBuf; PendingWrite(ChannelFuture future, ByteBuffer outAppBuf) { this.future = future; this.outAppBuf = outAppBuf; } } private static final class ClosingChannelFutureListener implements ChannelFutureListener { private final ChannelHandlerContext context; private final ChannelStateEvent e; ClosingChannelFutureListener( ChannelHandlerContext context, ChannelStateEvent e) { this.context = context; this.e = e; } public void operationComplete(ChannelFuture closeNotifyFuture) throws Exception { if (!(closeNotifyFuture.getCause() instanceof ClosedChannelException)) { Channels.close(context, e.getFuture()); } else { e.getFuture().setSuccess(); } } } @Override public void beforeAdd(ChannelHandlerContext ctx) throws Exception { super.beforeAdd(ctx); this.ctx = ctx; } /** * Fail all pending writes which we were not able to flush out */ @Override public void afterRemove(ChannelHandlerContext ctx) throws Exception { closeEngine(); // there is no need for synchronization here as we do not receive downstream events anymore Throwable cause = null; for (;;) { PendingWrite pw = pendingUnencryptedWrites.poll(); if (pw == null) { break; } if (cause == null) { cause = new IOException("Unable to write data"); } pw.future.setFailure(cause); } for (;;) { MessageEvent ev = pendingEncryptedWrites.poll(); if (ev == null) { break; } if (cause == null) { cause = new IOException("Unable to write data"); } ev.getFuture().setFailure(cause); } if (cause != null) { fireExceptionCaughtLater(ctx, cause); } } /** * Calls {@link #handshake()} once the {@link Channel} is connected */ @Override public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception { if (issueHandshake) { // issue and handshake and add a listener to it which will fire an exception event if // an exception was thrown while doing the handshake handshake().addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Send the event upstream after the handshake was completed without an error. // // See https://github.com/netty/netty/issues/358 ctx.sendUpstream(e); } } }); } else { super.channelConnected(ctx, e); } } /** * Loop over all the pending writes and fail them. * * See <a href="https://github.com/netty/netty/issues/305">#305</a> for more details. */ @Override public void channelClosed(final ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Move the fail of the writes to the IO-Thread to prevent possible deadlock // See https://github.com/netty/netty/issues/989 ctx.getPipeline().execute(new Runnable() { public void run() { if (!pendingUnencryptedWritesLock.tryLock()) { return; } Throwable cause = null; try { for (;;) { PendingWrite pw = pendingUnencryptedWrites.poll(); if (pw == null) { break; } if (cause == null) { cause = new ClosedChannelException(); } pw.future.setFailure(cause); } for (;;) { MessageEvent ev = pendingEncryptedWrites.poll(); if (ev == null) { break; } if (cause == null) { cause = new ClosedChannelException(); } ev.getFuture().setFailure(cause); } } finally { pendingUnencryptedWritesLock.unlock(); } if (cause != null) { fireExceptionCaught(ctx, cause); } } }); super.channelClosed(ctx, e); } private final class SSLEngineInboundCloseFuture extends DefaultChannelFuture { SSLEngineInboundCloseFuture() { super(null, true); } void setClosed() { super.setSuccess(); } @Override public Channel getChannel() { if (ctx == null) { // Maybe we should better throw an IllegalStateException() ? return null; } else { return ctx.getChannel(); } } @Override public boolean setSuccess() { return false; } @Override public boolean setFailure(Throwable cause) { return false; } } }
./CrossVul/dataset_final_sorted/CWE-119/java/bad_2139_0
crossvul-java_data_bad_4291_1
/* * Copyright (C) 2016 Southern Storm Software, Pty Ltd. * * 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 com.southernstorm.noise.protocol; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.ShortBufferException; import com.southernstorm.noise.crypto.GHASH; import com.southernstorm.noise.crypto.RijndaelAES; /** * Fallback implementation of "AESGCM" on platforms where * the JCA/JCE does not have a suitable GCM or CTR provider. */ class AESGCMFallbackCipherState implements CipherState { private RijndaelAES aes; private long n; private byte[] iv; private byte[] enciv; private byte[] hashKey; private GHASH ghash; private boolean haskey; /** * Constructs a new cipher state for the "AESGCM" algorithm. */ public AESGCMFallbackCipherState() { aes = new RijndaelAES(); n = 0; iv = new byte [16]; enciv = new byte [16]; hashKey = new byte [16]; ghash = new GHASH(); haskey = false; } @Override public void destroy() { aes.destroy(); ghash.destroy(); Noise.destroy(hashKey); Noise.destroy(iv); Noise.destroy(enciv); } @Override public String getCipherName() { return "AESGCM"; } @Override public int getKeyLength() { return 32; } @Override public int getMACLength() { return haskey ? 16 : 0; } @Override public void initializeKey(byte[] key, int offset) { // Set up the AES key. aes.setupEnc(key, offset, 256); haskey = true; // Generate the hashing key by encrypting a block of zeroes. Arrays.fill(hashKey, (byte)0); aes.encrypt(hashKey, 0, hashKey, 0); ghash.reset(hashKey, 0); // Reset the nonce. n = 0; } @Override public boolean hasKey() { return haskey; } /** * Set up to encrypt or decrypt the next packet. * * @param ad The associated data for the packet. */ private void setup(byte[] ad) { // Check for nonce wrap-around. if (n == -1L) throw new IllegalStateException("Nonce has wrapped around"); // Format the counter/IV block. iv[0] = 0; iv[1] = 0; iv[2] = 0; iv[3] = 0; iv[4] = (byte)(n >> 56); iv[5] = (byte)(n >> 48); iv[6] = (byte)(n >> 40); iv[7] = (byte)(n >> 32); iv[8] = (byte)(n >> 24); iv[9] = (byte)(n >> 16); iv[10] = (byte)(n >> 8); iv[11] = (byte)n; iv[12] = 0; iv[13] = 0; iv[14] = 0; iv[15] = 1; ++n; // Encrypt a block of zeroes to generate the hash key to XOR // the GHASH tag with at the end of the encrypt/decrypt operation. Arrays.fill(hashKey, (byte)0); aes.encrypt(iv, 0, hashKey, 0); // Initialize the GHASH with the associated data value. ghash.reset(); if (ad != null) { ghash.update(ad, 0, ad.length); ghash.pad(); } } /** * Encrypts a block in CTR mode. * * @param plaintext The plaintext to encrypt. * @param plaintextOffset Offset of the first plaintext byte. * @param ciphertext The resulting ciphertext. * @param ciphertextOffset Offset of the first ciphertext byte. * @param length The number of bytes to encrypt. * * This function can also be used to decrypt. */ private void encryptCTR(byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) { while (length > 0) { // Increment the IV and encrypt it to get the next keystream block. if (++(iv[15]) == 0) if (++(iv[14]) == 0) if (++(iv[13]) == 0) ++(iv[12]); aes.encrypt(iv, 0, enciv, 0); // XOR the keystream block with the plaintext to create the ciphertext. int temp = length; if (temp > 16) temp = 16; for (int index = 0; index < temp; ++index) ciphertext[ciphertextOffset + index] = (byte)(plaintext[plaintextOffset + index] ^ enciv[index]); // Advance to the next block. plaintextOffset += temp; ciphertextOffset += temp; length -= temp; } } @Override public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (!haskey) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); setup(ad); encryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); ghash.update(ciphertext, ciphertextOffset, length); ghash.pad(ad != null ? ad.length : 0, length); ghash.finish(ciphertext, ciphertextOffset + length, 16); for (int index = 0; index < 16; ++index) ciphertext[ciphertextOffset + length + index] ^= hashKey[index]; return length + 16; } @Override public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset > ciphertext.length) space = 0; else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (plaintextOffset > plaintext.length) space = 0; else space = plaintext.length - plaintextOffset; if (!haskey) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); setup(ad); ghash.update(ciphertext, ciphertextOffset, dataLen); ghash.pad(ad != null ? ad.length : 0, dataLen); ghash.finish(enciv, 0, 16); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; } @Override public CipherState fork(byte[] key, int offset) { CipherState cipher; cipher = new AESGCMFallbackCipherState(); cipher.initializeKey(key, offset); return cipher; } @Override public void setNonce(long nonce) { n = nonce; } }
./CrossVul/dataset_final_sorted/CWE-119/java/bad_4291_1
crossvul-java_data_good_4291_1
/* * Copyright (C) 2016 Southern Storm Software, Pty Ltd. * * 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 com.southernstorm.noise.protocol; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.ShortBufferException; import com.southernstorm.noise.crypto.GHASH; import com.southernstorm.noise.crypto.RijndaelAES; /** * Fallback implementation of "AESGCM" on platforms where * the JCA/JCE does not have a suitable GCM or CTR provider. */ class AESGCMFallbackCipherState implements CipherState { private RijndaelAES aes; private long n; private byte[] iv; private byte[] enciv; private byte[] hashKey; private GHASH ghash; private boolean haskey; /** * Constructs a new cipher state for the "AESGCM" algorithm. */ public AESGCMFallbackCipherState() { aes = new RijndaelAES(); n = 0; iv = new byte [16]; enciv = new byte [16]; hashKey = new byte [16]; ghash = new GHASH(); haskey = false; } @Override public void destroy() { aes.destroy(); ghash.destroy(); Noise.destroy(hashKey); Noise.destroy(iv); Noise.destroy(enciv); } @Override public String getCipherName() { return "AESGCM"; } @Override public int getKeyLength() { return 32; } @Override public int getMACLength() { return haskey ? 16 : 0; } @Override public void initializeKey(byte[] key, int offset) { // Set up the AES key. aes.setupEnc(key, offset, 256); haskey = true; // Generate the hashing key by encrypting a block of zeroes. Arrays.fill(hashKey, (byte)0); aes.encrypt(hashKey, 0, hashKey, 0); ghash.reset(hashKey, 0); // Reset the nonce. n = 0; } @Override public boolean hasKey() { return haskey; } /** * Set up to encrypt or decrypt the next packet. * * @param ad The associated data for the packet. */ private void setup(byte[] ad) { // Check for nonce wrap-around. if (n == -1L) throw new IllegalStateException("Nonce has wrapped around"); // Format the counter/IV block. iv[0] = 0; iv[1] = 0; iv[2] = 0; iv[3] = 0; iv[4] = (byte)(n >> 56); iv[5] = (byte)(n >> 48); iv[6] = (byte)(n >> 40); iv[7] = (byte)(n >> 32); iv[8] = (byte)(n >> 24); iv[9] = (byte)(n >> 16); iv[10] = (byte)(n >> 8); iv[11] = (byte)n; iv[12] = 0; iv[13] = 0; iv[14] = 0; iv[15] = 1; ++n; // Encrypt a block of zeroes to generate the hash key to XOR // the GHASH tag with at the end of the encrypt/decrypt operation. Arrays.fill(hashKey, (byte)0); aes.encrypt(iv, 0, hashKey, 0); // Initialize the GHASH with the associated data value. ghash.reset(); if (ad != null) { ghash.update(ad, 0, ad.length); ghash.pad(); } } /** * Encrypts a block in CTR mode. * * @param plaintext The plaintext to encrypt. * @param plaintextOffset Offset of the first plaintext byte. * @param ciphertext The resulting ciphertext. * @param ciphertextOffset Offset of the first ciphertext byte. * @param length The number of bytes to encrypt. * * This function can also be used to decrypt. */ private void encryptCTR(byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) { while (length > 0) { // Increment the IV and encrypt it to get the next keystream block. if (++(iv[15]) == 0) if (++(iv[14]) == 0) if (++(iv[13]) == 0) ++(iv[12]); aes.encrypt(iv, 0, enciv, 0); // XOR the keystream block with the plaintext to create the ciphertext. int temp = length; if (temp > 16) temp = 16; for (int index = 0; index < temp; ++index) ciphertext[ciphertextOffset + index] = (byte)(plaintext[plaintextOffset + index] ^ enciv[index]); // Advance to the next block. plaintextOffset += temp; ciphertextOffset += temp; length -= temp; } } @Override public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length) throw new IllegalArgumentException(); if (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length) throw new IllegalArgumentException(); space = ciphertext.length - ciphertextOffset; if (!haskey) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); setup(ad); encryptCTR(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); ghash.update(ciphertext, ciphertextOffset, length); ghash.pad(ad != null ? ad.length : 0, length); ghash.finish(ciphertext, ciphertextOffset + length, 16); for (int index = 0; index < 16; ++index) ciphertext[ciphertextOffset + length + index] ^= hashKey[index]; return length + 16; } @Override public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length) throw new IllegalArgumentException(); else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length) throw new IllegalArgumentException(); space = plaintext.length - plaintextOffset; if (!haskey) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); setup(ad); ghash.update(ciphertext, ciphertextOffset, dataLen); ghash.pad(ad != null ? ad.length : 0, dataLen); ghash.finish(enciv, 0, 16); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (hashKey[index] ^ enciv[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encryptCTR(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; } @Override public CipherState fork(byte[] key, int offset) { CipherState cipher; cipher = new AESGCMFallbackCipherState(); cipher.initializeKey(key, offset); return cipher; } @Override public void setNonce(long nonce) { n = nonce; } }
./CrossVul/dataset_final_sorted/CWE-119/java/good_4291_1
crossvul-java_data_good_4291_3
/* * Copyright (C) 2016 Southern Storm Software, Pty Ltd. * * 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 com.southernstorm.noise.protocol; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.ShortBufferException; import com.southernstorm.noise.crypto.ChaChaCore; import com.southernstorm.noise.crypto.Poly1305; /** * Implements the ChaChaPoly cipher for Noise. */ class ChaChaPolyCipherState implements CipherState { private Poly1305 poly; private int[] input; private int[] output; private byte[] polyKey; long n; private boolean haskey; /** * Constructs a new cipher state for the "ChaChaPoly" algorithm. */ public ChaChaPolyCipherState() { poly = new Poly1305(); input = new int [16]; output = new int [16]; polyKey = new byte [32]; n = 0; haskey = false; } @Override public void destroy() { poly.destroy(); Arrays.fill(input, 0); Arrays.fill(output, 0); Noise.destroy(polyKey); } @Override public String getCipherName() { return "ChaChaPoly"; } @Override public int getKeyLength() { return 32; } @Override public int getMACLength() { return haskey ? 16 : 0; } @Override public void initializeKey(byte[] key, int offset) { ChaChaCore.initKey256(input, key, offset); n = 0; haskey = true; } @Override public boolean hasKey() { return haskey; } /** * XOR's the output of ChaCha20 with a byte buffer. * * @param input The input byte buffer. * @param inputOffset The offset of the first input byte. * @param output The output byte buffer (can be the same as the input). * @param outputOffset The offset of the first output byte. * @param length The number of bytes to XOR between 1 and 64. * @param block The ChaCha20 output block. */ private static void xorBlock(byte[] input, int inputOffset, byte[] output, int outputOffset, int length, int[] block) { int posn = 0; int value; while (length >= 4) { value = block[posn++]; output[outputOffset] = (byte)(input[inputOffset] ^ value); output[outputOffset + 1] = (byte)(input[inputOffset + 1] ^ (value >> 8)); output[outputOffset + 2] = (byte)(input[inputOffset + 2] ^ (value >> 16)); output[outputOffset + 3] = (byte)(input[inputOffset + 3] ^ (value >> 24)); inputOffset += 4; outputOffset += 4; length -= 4; } if (length == 3) { value = block[posn]; output[outputOffset] = (byte)(input[inputOffset] ^ value); output[outputOffset + 1] = (byte)(input[inputOffset + 1] ^ (value >> 8)); output[outputOffset + 2] = (byte)(input[inputOffset + 2] ^ (value >> 16)); } else if (length == 2) { value = block[posn]; output[outputOffset] = (byte)(input[inputOffset] ^ value); output[outputOffset + 1] = (byte)(input[inputOffset + 1] ^ (value >> 8)); } else if (length == 1) { value = block[posn]; output[outputOffset] = (byte)(input[inputOffset] ^ value); } } /** * Set up to encrypt or decrypt the next packet. * * @param ad The associated data for the packet. */ private void setup(byte[] ad) { if (n == -1L) throw new IllegalStateException("Nonce has wrapped around"); ChaChaCore.initIV(input, n++); ChaChaCore.hash(output, input); Arrays.fill(polyKey, (byte)0); xorBlock(polyKey, 0, polyKey, 0, 32, output); poly.reset(polyKey, 0); if (ad != null) { poly.update(ad, 0, ad.length); poly.pad(); } if (++(input[12]) == 0) ++(input[13]); } /** * Puts a 64-bit integer into a buffer in little-endian order. * * @param output The output buffer. * @param offset The offset into the output buffer. * @param value The 64-bit integer value. */ private static void putLittleEndian64(byte[] output, int offset, long value) { output[offset] = (byte)value; output[offset + 1] = (byte)(value >> 8); output[offset + 2] = (byte)(value >> 16); output[offset + 3] = (byte)(value >> 24); output[offset + 4] = (byte)(value >> 32); output[offset + 5] = (byte)(value >> 40); output[offset + 6] = (byte)(value >> 48); output[offset + 7] = (byte)(value >> 56); } /** * Finishes up the authentication tag for a packet. * * @param ad The associated data. * @param length The length of the plaintext data. */ private void finish(byte[] ad, int length) { poly.pad(); putLittleEndian64(polyKey, 0, ad != null ? ad.length : 0); putLittleEndian64(polyKey, 8, length); poly.update(polyKey, 0, 16); poly.finish(polyKey, 0); } /** * Encrypts or decrypts a buffer of bytes for the active packet. * * @param plaintext The plaintext data to be encrypted. * @param plaintextOffset The offset to the first plaintext byte. * @param ciphertext The ciphertext data that results from encryption. * @param ciphertextOffset The offset to the first ciphertext byte. * @param length The number of bytes to encrypt. */ private void encrypt(byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) { while (length > 0) { int tempLen = 64; if (tempLen > length) tempLen = length; ChaChaCore.hash(output, input); xorBlock(plaintext, plaintextOffset, ciphertext, ciphertextOffset, tempLen, output); if (++(input[12]) == 0) ++(input[13]); plaintextOffset += tempLen; ciphertextOffset += tempLen; length -= tempLen; } } @Override public int encryptWithAd(byte[] ad, byte[] plaintext, int plaintextOffset, byte[] ciphertext, int ciphertextOffset, int length) throws ShortBufferException { int space; if (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length) throw new IllegalArgumentException(); if (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length) throw new IllegalArgumentException(); space = ciphertext.length - ciphertextOffset; if (!haskey) { // The key is not set yet - return the plaintext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); return length; } if (space < 16 || length > (space - 16)) throw new ShortBufferException(); setup(ad); encrypt(plaintext, plaintextOffset, ciphertext, ciphertextOffset, length); poly.update(ciphertext, ciphertextOffset, length); finish(ad, length); System.arraycopy(polyKey, 0, ciphertext, ciphertextOffset + length, 16); return length + 16; } @Override public int decryptWithAd(byte[] ad, byte[] ciphertext, int ciphertextOffset, byte[] plaintext, int plaintextOffset, int length) throws ShortBufferException, BadPaddingException { int space; if (ciphertextOffset < 0 || ciphertextOffset > ciphertext.length) throw new IllegalArgumentException(); else space = ciphertext.length - ciphertextOffset; if (length > space) throw new ShortBufferException(); if (length < 0 || plaintextOffset < 0 || plaintextOffset > plaintext.length) throw new IllegalArgumentException(); space = plaintext.length - plaintextOffset; if (!haskey) { // The key is not set yet - return the ciphertext as-is. if (length > space) throw new ShortBufferException(); if (plaintext != ciphertext || plaintextOffset != ciphertextOffset) System.arraycopy(ciphertext, ciphertextOffset, plaintext, plaintextOffset, length); return length; } if (length < 16) Noise.throwBadTagException(); int dataLen = length - 16; if (dataLen > space) throw new ShortBufferException(); setup(ad); poly.update(ciphertext, ciphertextOffset, dataLen); finish(ad, dataLen); int temp = 0; for (int index = 0; index < 16; ++index) temp |= (polyKey[index] ^ ciphertext[ciphertextOffset + dataLen + index]); if ((temp & 0xFF) != 0) Noise.throwBadTagException(); encrypt(ciphertext, ciphertextOffset, plaintext, plaintextOffset, dataLen); return dataLen; } @Override public CipherState fork(byte[] key, int offset) { CipherState cipher = new ChaChaPolyCipherState(); cipher.initializeKey(key, offset); return cipher; } @Override public void setNonce(long nonce) { n = nonce; } }
./CrossVul/dataset_final_sorted/CWE-119/java/good_4291_3
crossvul-java_data_bad_184_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-835/java/bad_184_1
crossvul-java_data_good_184_0
/* * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved. * Original author: Edmund Wagner * Creation date: 22.05.2007 * * Source: $HeadURL$ * Last changed: $LastChangedDate$ * * the unrar licence applies to all junrar source and binary distributions * you are not allowed to use this source to re-create the RAR compression * algorithm * * Here some html entities which can be used for escaping javadoc tags: * "&": "&#038;" or "&amp;" * "<": "&#060;" or "&lt;" * ">": "&#062;" or "&gt;" * "@": "&#064;" */ package com.github.junrar; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.github.junrar.exception.RarException; import com.github.junrar.exception.RarException.RarExceptionType; import com.github.junrar.impl.FileVolumeManager; import com.github.junrar.io.IReadOnlyAccess; import com.github.junrar.rarfile.AVHeader; import com.github.junrar.rarfile.BaseBlock; import com.github.junrar.rarfile.BlockHeader; import com.github.junrar.rarfile.CommentHeader; import com.github.junrar.rarfile.EAHeader; import com.github.junrar.rarfile.EndArcHeader; import com.github.junrar.rarfile.FileHeader; import com.github.junrar.rarfile.MacInfoHeader; import com.github.junrar.rarfile.MainHeader; import com.github.junrar.rarfile.MarkHeader; import com.github.junrar.rarfile.ProtectHeader; import com.github.junrar.rarfile.SignHeader; import com.github.junrar.rarfile.SubBlockHeader; import com.github.junrar.rarfile.UnixOwnersHeader; import com.github.junrar.rarfile.UnrarHeadertype; import com.github.junrar.unpack.ComprDataIO; import com.github.junrar.unpack.Unpack; /** * The Main Rar Class; represents a rar Archive * * @author $LastChangedBy$ * @version $LastChangedRevision$ */ public class Archive implements Closeable { private static Logger logger = Logger.getLogger(Archive.class.getName()); private static int MAX_HEADER_SIZE = 20971520;//20MB private IReadOnlyAccess rof; private final UnrarCallback unrarCallback; private final ComprDataIO dataIO; private final List<BaseBlock> headers = new ArrayList<BaseBlock>(); private MarkHeader markHead = null; private MainHeader newMhd = null; private Unpack unpack; private int currentHeaderIndex; /** Size of packed data in current file. */ private long totalPackedSize = 0L; /** Number of bytes of compressed data read from current file. */ private long totalPackedRead = 0L; private VolumeManager volumeManager; private Volume volume; public Archive(VolumeManager volumeManager) throws RarException, IOException { this(volumeManager, null); } /** * create a new archive object using the given {@link VolumeManager} * * @param volumeManager * the the {@link VolumeManager} that will provide volume stream * data * @throws RarException */ public Archive(VolumeManager volumeManager, UnrarCallback unrarCallback) throws RarException, IOException { this.volumeManager = volumeManager; this.unrarCallback = unrarCallback; setVolume(this.volumeManager.nextArchive(this, null)); dataIO = new ComprDataIO(this); } public Archive(File firstVolume) throws RarException, IOException { this(new FileVolumeManager(firstVolume), null); } public Archive(File firstVolume, UnrarCallback unrarCallback) throws RarException, IOException { this(new FileVolumeManager(firstVolume), unrarCallback); } // public File getFile() { // return file; // } // // void setFile(File file) throws IOException { // this.file = file; // setFile(new ReadOnlyAccessFile(file), file.length()); // } private void setFile(IReadOnlyAccess file, long length) throws IOException { totalPackedSize = 0L; totalPackedRead = 0L; close(); rof = file; try { readHeaders(length); } catch (Exception e) { logger.log(Level.WARNING, "exception in archive constructor maybe file is encrypted " + "or currupt", e); // ignore exceptions to allow exraction of working files in // corrupt archive } // Calculate size of packed data for (BaseBlock block : headers) { if (block.getHeaderType() == UnrarHeadertype.FileHeader) { totalPackedSize += ((FileHeader) block).getFullPackSize(); } } if (unrarCallback != null) { unrarCallback.volumeProgressChanged(totalPackedRead, totalPackedSize); } } public void bytesReadRead(int count) { if (count > 0) { totalPackedRead += count; if (unrarCallback != null) { unrarCallback.volumeProgressChanged(totalPackedRead, totalPackedSize); } } } public IReadOnlyAccess getRof() { return rof; } /** * Gets all of the headers in the archive. * * @return returns the headers. */ public List<BaseBlock> getHeaders() { return new ArrayList<BaseBlock>(headers); } /** * @return returns all file headers of the archive */ public List<FileHeader> getFileHeaders() { List<FileHeader> list = new ArrayList<FileHeader>(); for (BaseBlock block : headers) { if (block.getHeaderType().equals(UnrarHeadertype.FileHeader)) { list.add((FileHeader) block); } } return list; } public FileHeader nextFileHeader() { int n = headers.size(); while (currentHeaderIndex < n) { BaseBlock block = headers.get(currentHeaderIndex++); if (block.getHeaderType() == UnrarHeadertype.FileHeader) { return (FileHeader) block; } } return null; } public UnrarCallback getUnrarCallback() { return unrarCallback; } /** * * @return whether the archive is encrypted */ public boolean isEncrypted() { if (newMhd != null) { return newMhd.isEncrypted(); } else { throw new NullPointerException("mainheader is null"); } } /** * Read the headers of the archive * * @param fileLength * Length of file. * @throws RarException */ private void readHeaders(long fileLength) throws IOException, RarException { markHead = null; newMhd = null; headers.clear(); currentHeaderIndex = 0; int toRead = 0; //keep track of positions already processed for //more robustness against corrupt files Set<Long> processedPositions = new HashSet<Long>(); while (true) { int size = 0; long newpos = 0; byte[] baseBlockBuffer = safelyAllocate(BaseBlock.BaseBlockSize, MAX_HEADER_SIZE); long position = rof.getPosition(); // Weird, but is trying to read beyond the end of the file if (position >= fileLength) { break; } // logger.info("\n--------reading header--------"); size = rof.readFully(baseBlockBuffer, BaseBlock.BaseBlockSize); if (size == 0) { break; } BaseBlock block = new BaseBlock(baseBlockBuffer); block.setPositionInFile(position); switch (block.getHeaderType()) { case MarkHeader: markHead = new MarkHeader(block); if (!markHead.isSignature()) { throw new RarException( RarException.RarExceptionType.badRarArchive); } headers.add(markHead); // markHead.print(); break; case MainHeader: toRead = block.hasEncryptVersion() ? MainHeader.mainHeaderSizeWithEnc : MainHeader.mainHeaderSize; byte[] mainbuff = safelyAllocate(toRead, MAX_HEADER_SIZE); rof.readFully(mainbuff, toRead); MainHeader mainhead = new MainHeader(block, mainbuff); headers.add(mainhead); this.newMhd = mainhead; if (newMhd.isEncrypted()) { throw new RarException( RarExceptionType.rarEncryptedException); } // mainhead.print(); break; case SignHeader: toRead = SignHeader.signHeaderSize; byte[] signBuff = safelyAllocate(toRead, MAX_HEADER_SIZE); rof.readFully(signBuff, toRead); SignHeader signHead = new SignHeader(block, signBuff); headers.add(signHead); // logger.info("HeaderType: SignHeader"); break; case AvHeader: toRead = AVHeader.avHeaderSize; byte[] avBuff = safelyAllocate(toRead, MAX_HEADER_SIZE); rof.readFully(avBuff, toRead); AVHeader avHead = new AVHeader(block, avBuff); headers.add(avHead); // logger.info("headertype: AVHeader"); break; case CommHeader: toRead = CommentHeader.commentHeaderSize; byte[] commBuff = safelyAllocate(toRead, MAX_HEADER_SIZE); rof.readFully(commBuff, toRead); CommentHeader commHead = new CommentHeader(block, commBuff); headers.add(commHead); // logger.info("method: "+commHead.getUnpMethod()+"; 0x"+ // Integer.toHexString(commHead.getUnpMethod())); newpos = commHead.getPositionInFile() + commHead.getHeaderSize(); if (processedPositions.contains(newpos)) { throw new RarException(RarExceptionType.badRarArchive); } processedPositions.add(newpos); rof.setPosition(newpos); break; case EndArcHeader: toRead = 0; if (block.hasArchiveDataCRC()) { toRead += EndArcHeader.endArcArchiveDataCrcSize; } if (block.hasVolumeNumber()) { toRead += EndArcHeader.endArcVolumeNumberSize; } EndArcHeader endArcHead; if (toRead > 0) { byte[] endArchBuff = safelyAllocate(toRead, MAX_HEADER_SIZE); rof.readFully(endArchBuff, toRead); endArcHead = new EndArcHeader(block, endArchBuff); // logger.info("HeaderType: endarch\ndatacrc:"+ // endArcHead.getArchiveDataCRC()); } else { // logger.info("HeaderType: endarch - no Data"); endArcHead = new EndArcHeader(block, null); } headers.add(endArcHead); // logger.info("\n--------end header--------"); return; default: byte[] blockHeaderBuffer = safelyAllocate(BlockHeader.blockHeaderSize, MAX_HEADER_SIZE); rof.readFully(blockHeaderBuffer, BlockHeader.blockHeaderSize); BlockHeader blockHead = new BlockHeader(block, blockHeaderBuffer); switch (blockHead.getHeaderType()) { case NewSubHeader: case FileHeader: toRead = blockHead.getHeaderSize() - BlockHeader.BaseBlockSize - BlockHeader.blockHeaderSize; byte[] fileHeaderBuffer = safelyAllocate(toRead, MAX_HEADER_SIZE); rof.readFully(fileHeaderBuffer, toRead); FileHeader fh = new FileHeader(blockHead, fileHeaderBuffer); headers.add(fh); newpos = fh.getPositionInFile() + fh.getHeaderSize() + fh.getFullPackSize(); if (processedPositions.contains(newpos)) { throw new RarException(RarExceptionType.badRarArchive); } processedPositions.add(newpos); rof.setPosition(newpos); break; case ProtectHeader: toRead = blockHead.getHeaderSize() - BlockHeader.BaseBlockSize - BlockHeader.blockHeaderSize; byte[] protectHeaderBuffer = safelyAllocate(toRead, MAX_HEADER_SIZE); rof.readFully(protectHeaderBuffer, toRead); ProtectHeader ph = new ProtectHeader(blockHead, protectHeaderBuffer); newpos = ph.getPositionInFile() + ph.getHeaderSize() + ph.getDataSize(); if (processedPositions.contains(newpos)) { throw new RarException(RarExceptionType.badRarArchive); } processedPositions.add(newpos); rof.setPosition(newpos); break; case SubHeader: { byte[] subHeadbuffer = safelyAllocate(SubBlockHeader.SubBlockHeaderSize, MAX_HEADER_SIZE); rof.readFully(subHeadbuffer, SubBlockHeader.SubBlockHeaderSize); SubBlockHeader subHead = new SubBlockHeader(blockHead, subHeadbuffer); subHead.print(); switch (subHead.getSubType()) { case MAC_HEAD: { byte[] macHeaderbuffer = safelyAllocate(MacInfoHeader.MacInfoHeaderSize, MAX_HEADER_SIZE); rof.readFully(macHeaderbuffer, MacInfoHeader.MacInfoHeaderSize); MacInfoHeader macHeader = new MacInfoHeader(subHead, macHeaderbuffer); macHeader.print(); headers.add(macHeader); break; } // TODO implement other subheaders case BEEA_HEAD: break; case EA_HEAD: { byte[] eaHeaderBuffer = safelyAllocate(EAHeader.EAHeaderSize, MAX_HEADER_SIZE); rof.readFully(eaHeaderBuffer, EAHeader.EAHeaderSize); EAHeader eaHeader = new EAHeader(subHead, eaHeaderBuffer); eaHeader.print(); headers.add(eaHeader); break; } case NTACL_HEAD: break; case STREAM_HEAD: break; case UO_HEAD: toRead = subHead.getHeaderSize(); toRead -= BaseBlock.BaseBlockSize; toRead -= BlockHeader.blockHeaderSize; toRead -= SubBlockHeader.SubBlockHeaderSize; byte[] uoHeaderBuffer = safelyAllocate(toRead, MAX_HEADER_SIZE); rof.readFully(uoHeaderBuffer, toRead); UnixOwnersHeader uoHeader = new UnixOwnersHeader( subHead, uoHeaderBuffer); uoHeader.print(); headers.add(uoHeader); break; default: break; } break; } default: logger.warning("Unknown Header"); throw new RarException(RarExceptionType.notRarArchive); } } // logger.info("\n--------end header--------"); } } private static byte[] safelyAllocate(long len, int maxSize) throws RarException { if (maxSize < 0) { throw new IllegalArgumentException("maxsize must be >= 0"); } if (len < 0 || len > (long)maxSize) { throw new RarException(RarExceptionType.badRarArchive); } return new byte[(int)len]; } /** * Extract the file specified by the given header and write it to the * supplied output stream * * @param hd * the header to be extracted * @param os * the outputstream * @throws RarException */ public void extractFile(FileHeader hd, OutputStream os) throws RarException { if (!headers.contains(hd)) { throw new RarException(RarExceptionType.headerNotInArchive); } try { doExtractFile(hd, os); } catch (Exception e) { if (e instanceof RarException) { throw (RarException) e; } else { throw new RarException(e); } } } /** * Returns an {@link InputStream} that will allow to read the file and * stream it. Please note that this method will create a new Thread and an a * pair of Pipe streams. * * @param hd * the header to be extracted * @throws RarException * @throws IOException * if any IO error occur */ public InputStream getInputStream(final FileHeader hd) throws RarException, IOException { final PipedInputStream in = new PipedInputStream(32 * 1024); final PipedOutputStream out = new PipedOutputStream(in); // creates a new thread that will write data to the pipe. Data will be // available in another InputStream, connected to the OutputStream. new Thread(new Runnable() { public void run() { try { extractFile(hd, out); } catch (RarException e) { } finally { try { out.close(); } catch (IOException e) { } } } }).start(); return in; } private void doExtractFile(FileHeader hd, OutputStream os) throws RarException, IOException { dataIO.init(os); dataIO.init(hd); dataIO.setUnpFileCRC(this.isOldFormat() ? 0 : 0xffFFffFF); if (unpack == null) { unpack = new Unpack(dataIO); } if (!hd.isSolid()) { unpack.init(null); } unpack.setDestSize(hd.getFullUnpackSize()); try { unpack.doUnpack(hd.getUnpVersion(), hd.isSolid()); // Verify file CRC hd = dataIO.getSubHeader(); long actualCRC = hd.isSplitAfter() ? ~dataIO.getPackedCRC() : ~dataIO.getUnpFileCRC(); int expectedCRC = hd.getFileCRC(); if (actualCRC != expectedCRC) { throw new RarException(RarExceptionType.crcError); } // if (!hd.isSplitAfter()) { // // Verify file CRC // if(~dataIO.getUnpFileCRC() != hd.getFileCRC()){ // throw new RarException(RarExceptionType.crcError); // } // } } catch (Exception e) { unpack.cleanUp(); if (e instanceof RarException) { // throw new RarException((RarException)e); throw (RarException) e; } else { throw new RarException(e); } } } /** * @return returns the main header of this archive */ public MainHeader getMainHeader() { return newMhd; } /** * @return whether the archive is old format */ public boolean isOldFormat() { return markHead.isOldFormat(); } /** Close the underlying compressed file. */ public void close() throws IOException { if (rof != null) { rof.close(); rof = null; } if (unpack != null) { unpack.cleanUp(); } } /** * @return the volumeManager */ public VolumeManager getVolumeManager() { return volumeManager; } /** * @param volumeManager * the volumeManager to set */ public void setVolumeManager(VolumeManager volumeManager) { this.volumeManager = volumeManager; } /** * @return the volume */ public Volume getVolume() { return volume; } /** * @param volume * the volume to set * @throws IOException */ public void setVolume(Volume volume) throws IOException { this.volume = volume; setFile(volume.getReadOnlyAccess(), volume.getLength()); } }
./CrossVul/dataset_final_sorted/CWE-835/java/good_184_0
crossvul-java_data_bad_184_0
/* * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved. * Original author: Edmund Wagner * Creation date: 22.05.2007 * * Source: $HeadURL$ * Last changed: $LastChangedDate$ * * the unrar licence applies to all junrar source and binary distributions * you are not allowed to use this source to re-create the RAR compression * algorithm * * Here some html entities which can be used for escaping javadoc tags: * "&": "&#038;" or "&amp;" * "<": "&#060;" or "&lt;" * ">": "&#062;" or "&gt;" * "@": "&#064;" */ package com.github.junrar; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.github.junrar.exception.RarException; import com.github.junrar.exception.RarException.RarExceptionType; import com.github.junrar.impl.FileVolumeManager; import com.github.junrar.io.IReadOnlyAccess; import com.github.junrar.rarfile.AVHeader; import com.github.junrar.rarfile.BaseBlock; import com.github.junrar.rarfile.BlockHeader; import com.github.junrar.rarfile.CommentHeader; import com.github.junrar.rarfile.EAHeader; import com.github.junrar.rarfile.EndArcHeader; import com.github.junrar.rarfile.FileHeader; import com.github.junrar.rarfile.MacInfoHeader; import com.github.junrar.rarfile.MainHeader; import com.github.junrar.rarfile.MarkHeader; import com.github.junrar.rarfile.ProtectHeader; import com.github.junrar.rarfile.SignHeader; import com.github.junrar.rarfile.SubBlockHeader; import com.github.junrar.rarfile.UnixOwnersHeader; import com.github.junrar.rarfile.UnrarHeadertype; import com.github.junrar.unpack.ComprDataIO; import com.github.junrar.unpack.Unpack; /** * The Main Rar Class; represents a rar Archive * * @author $LastChangedBy$ * @version $LastChangedRevision$ */ public class Archive implements Closeable { private static Logger logger = Logger.getLogger(Archive.class.getName()); private IReadOnlyAccess rof; private final UnrarCallback unrarCallback; private final ComprDataIO dataIO; private final List<BaseBlock> headers = new ArrayList<BaseBlock>(); private MarkHeader markHead = null; private MainHeader newMhd = null; private Unpack unpack; private int currentHeaderIndex; /** Size of packed data in current file. */ private long totalPackedSize = 0L; /** Number of bytes of compressed data read from current file. */ private long totalPackedRead = 0L; private VolumeManager volumeManager; private Volume volume; public Archive(VolumeManager volumeManager) throws RarException, IOException { this(volumeManager, null); } /** * create a new archive object using the given {@link VolumeManager} * * @param volumeManager * the the {@link VolumeManager} that will provide volume stream * data * @throws RarException */ public Archive(VolumeManager volumeManager, UnrarCallback unrarCallback) throws RarException, IOException { this.volumeManager = volumeManager; this.unrarCallback = unrarCallback; setVolume(this.volumeManager.nextArchive(this, null)); dataIO = new ComprDataIO(this); } public Archive(File firstVolume) throws RarException, IOException { this(new FileVolumeManager(firstVolume), null); } public Archive(File firstVolume, UnrarCallback unrarCallback) throws RarException, IOException { this(new FileVolumeManager(firstVolume), unrarCallback); } // public File getFile() { // return file; // } // // void setFile(File file) throws IOException { // this.file = file; // setFile(new ReadOnlyAccessFile(file), file.length()); // } private void setFile(IReadOnlyAccess file, long length) throws IOException { totalPackedSize = 0L; totalPackedRead = 0L; close(); rof = file; try { readHeaders(length); } catch (Exception e) { logger.log(Level.WARNING, "exception in archive constructor maybe file is encrypted " + "or currupt", e); // ignore exceptions to allow exraction of working files in // corrupt archive } // Calculate size of packed data for (BaseBlock block : headers) { if (block.getHeaderType() == UnrarHeadertype.FileHeader) { totalPackedSize += ((FileHeader) block).getFullPackSize(); } } if (unrarCallback != null) { unrarCallback.volumeProgressChanged(totalPackedRead, totalPackedSize); } } public void bytesReadRead(int count) { if (count > 0) { totalPackedRead += count; if (unrarCallback != null) { unrarCallback.volumeProgressChanged(totalPackedRead, totalPackedSize); } } } public IReadOnlyAccess getRof() { return rof; } /** * Gets all of the headers in the archive. * * @return returns the headers. */ public List<BaseBlock> getHeaders() { return new ArrayList<BaseBlock>(headers); } /** * @return returns all file headers of the archive */ public List<FileHeader> getFileHeaders() { List<FileHeader> list = new ArrayList<FileHeader>(); for (BaseBlock block : headers) { if (block.getHeaderType().equals(UnrarHeadertype.FileHeader)) { list.add((FileHeader) block); } } return list; } public FileHeader nextFileHeader() { int n = headers.size(); while (currentHeaderIndex < n) { BaseBlock block = headers.get(currentHeaderIndex++); if (block.getHeaderType() == UnrarHeadertype.FileHeader) { return (FileHeader) block; } } return null; } public UnrarCallback getUnrarCallback() { return unrarCallback; } /** * * @return whether the archive is encrypted */ public boolean isEncrypted() { if (newMhd != null) { return newMhd.isEncrypted(); } else { throw new NullPointerException("mainheader is null"); } } /** * Read the headers of the archive * * @param fileLength * Length of file. * @throws RarException */ private void readHeaders(long fileLength) throws IOException, RarException { markHead = null; newMhd = null; headers.clear(); currentHeaderIndex = 0; int toRead = 0; while (true) { int size = 0; long newpos = 0; byte[] baseBlockBuffer = new byte[BaseBlock.BaseBlockSize]; long position = rof.getPosition(); // Weird, but is trying to read beyond the end of the file if (position >= fileLength) { break; } // logger.info("\n--------reading header--------"); size = rof.readFully(baseBlockBuffer, BaseBlock.BaseBlockSize); if (size == 0) { break; } BaseBlock block = new BaseBlock(baseBlockBuffer); block.setPositionInFile(position); switch (block.getHeaderType()) { case MarkHeader: markHead = new MarkHeader(block); if (!markHead.isSignature()) { throw new RarException( RarException.RarExceptionType.badRarArchive); } headers.add(markHead); // markHead.print(); break; case MainHeader: toRead = block.hasEncryptVersion() ? MainHeader.mainHeaderSizeWithEnc : MainHeader.mainHeaderSize; byte[] mainbuff = new byte[toRead]; rof.readFully(mainbuff, toRead); MainHeader mainhead = new MainHeader(block, mainbuff); headers.add(mainhead); this.newMhd = mainhead; if (newMhd.isEncrypted()) { throw new RarException( RarExceptionType.rarEncryptedException); } // mainhead.print(); break; case SignHeader: toRead = SignHeader.signHeaderSize; byte[] signBuff = new byte[toRead]; rof.readFully(signBuff, toRead); SignHeader signHead = new SignHeader(block, signBuff); headers.add(signHead); // logger.info("HeaderType: SignHeader"); break; case AvHeader: toRead = AVHeader.avHeaderSize; byte[] avBuff = new byte[toRead]; rof.readFully(avBuff, toRead); AVHeader avHead = new AVHeader(block, avBuff); headers.add(avHead); // logger.info("headertype: AVHeader"); break; case CommHeader: toRead = CommentHeader.commentHeaderSize; byte[] commBuff = new byte[toRead]; rof.readFully(commBuff, toRead); CommentHeader commHead = new CommentHeader(block, commBuff); headers.add(commHead); // logger.info("method: "+commHead.getUnpMethod()+"; 0x"+ // Integer.toHexString(commHead.getUnpMethod())); newpos = commHead.getPositionInFile() + commHead.getHeaderSize(); rof.setPosition(newpos); break; case EndArcHeader: toRead = 0; if (block.hasArchiveDataCRC()) { toRead += EndArcHeader.endArcArchiveDataCrcSize; } if (block.hasVolumeNumber()) { toRead += EndArcHeader.endArcVolumeNumberSize; } EndArcHeader endArcHead; if (toRead > 0) { byte[] endArchBuff = new byte[toRead]; rof.readFully(endArchBuff, toRead); endArcHead = new EndArcHeader(block, endArchBuff); // logger.info("HeaderType: endarch\ndatacrc:"+ // endArcHead.getArchiveDataCRC()); } else { // logger.info("HeaderType: endarch - no Data"); endArcHead = new EndArcHeader(block, null); } headers.add(endArcHead); // logger.info("\n--------end header--------"); return; default: byte[] blockHeaderBuffer = new byte[BlockHeader.blockHeaderSize]; rof.readFully(blockHeaderBuffer, BlockHeader.blockHeaderSize); BlockHeader blockHead = new BlockHeader(block, blockHeaderBuffer); switch (blockHead.getHeaderType()) { case NewSubHeader: case FileHeader: toRead = blockHead.getHeaderSize() - BlockHeader.BaseBlockSize - BlockHeader.blockHeaderSize; byte[] fileHeaderBuffer = new byte[toRead]; rof.readFully(fileHeaderBuffer, toRead); FileHeader fh = new FileHeader(blockHead, fileHeaderBuffer); headers.add(fh); newpos = fh.getPositionInFile() + fh.getHeaderSize() + fh.getFullPackSize(); rof.setPosition(newpos); break; case ProtectHeader: toRead = blockHead.getHeaderSize() - BlockHeader.BaseBlockSize - BlockHeader.blockHeaderSize; byte[] protectHeaderBuffer = new byte[toRead]; rof.readFully(protectHeaderBuffer, toRead); ProtectHeader ph = new ProtectHeader(blockHead, protectHeaderBuffer); newpos = ph.getPositionInFile() + ph.getHeaderSize() + ph.getDataSize(); rof.setPosition(newpos); break; case SubHeader: { byte[] subHeadbuffer = new byte[SubBlockHeader.SubBlockHeaderSize]; rof.readFully(subHeadbuffer, SubBlockHeader.SubBlockHeaderSize); SubBlockHeader subHead = new SubBlockHeader(blockHead, subHeadbuffer); subHead.print(); switch (subHead.getSubType()) { case MAC_HEAD: { byte[] macHeaderbuffer = new byte[MacInfoHeader.MacInfoHeaderSize]; rof.readFully(macHeaderbuffer, MacInfoHeader.MacInfoHeaderSize); MacInfoHeader macHeader = new MacInfoHeader(subHead, macHeaderbuffer); macHeader.print(); headers.add(macHeader); break; } // TODO implement other subheaders case BEEA_HEAD: break; case EA_HEAD: { byte[] eaHeaderBuffer = new byte[EAHeader.EAHeaderSize]; rof.readFully(eaHeaderBuffer, EAHeader.EAHeaderSize); EAHeader eaHeader = new EAHeader(subHead, eaHeaderBuffer); eaHeader.print(); headers.add(eaHeader); break; } case NTACL_HEAD: break; case STREAM_HEAD: break; case UO_HEAD: toRead = subHead.getHeaderSize(); toRead -= BaseBlock.BaseBlockSize; toRead -= BlockHeader.blockHeaderSize; toRead -= SubBlockHeader.SubBlockHeaderSize; byte[] uoHeaderBuffer = new byte[toRead]; rof.readFully(uoHeaderBuffer, toRead); UnixOwnersHeader uoHeader = new UnixOwnersHeader( subHead, uoHeaderBuffer); uoHeader.print(); headers.add(uoHeader); break; default: break; } break; } default: logger.warning("Unknown Header"); throw new RarException(RarExceptionType.notRarArchive); } } // logger.info("\n--------end header--------"); } } /** * Extract the file specified by the given header and write it to the * supplied output stream * * @param hd * the header to be extracted * @param os * the outputstream * @throws RarException */ public void extractFile(FileHeader hd, OutputStream os) throws RarException { if (!headers.contains(hd)) { throw new RarException(RarExceptionType.headerNotInArchive); } try { doExtractFile(hd, os); } catch (Exception e) { if (e instanceof RarException) { throw (RarException) e; } else { throw new RarException(e); } } } /** * Returns an {@link InputStream} that will allow to read the file and * stream it. Please note that this method will create a new Thread and an a * pair of Pipe streams. * * @param hd * the header to be extracted * @throws RarException * @throws IOException * if any IO error occur */ public InputStream getInputStream(final FileHeader hd) throws RarException, IOException { final PipedInputStream in = new PipedInputStream(32 * 1024); final PipedOutputStream out = new PipedOutputStream(in); // creates a new thread that will write data to the pipe. Data will be // available in another InputStream, connected to the OutputStream. new Thread(new Runnable() { public void run() { try { extractFile(hd, out); } catch (RarException e) { } finally { try { out.close(); } catch (IOException e) { } } } }).start(); return in; } private void doExtractFile(FileHeader hd, OutputStream os) throws RarException, IOException { dataIO.init(os); dataIO.init(hd); dataIO.setUnpFileCRC(this.isOldFormat() ? 0 : 0xffFFffFF); if (unpack == null) { unpack = new Unpack(dataIO); } if (!hd.isSolid()) { unpack.init(null); } unpack.setDestSize(hd.getFullUnpackSize()); try { unpack.doUnpack(hd.getUnpVersion(), hd.isSolid()); // Verify file CRC hd = dataIO.getSubHeader(); long actualCRC = hd.isSplitAfter() ? ~dataIO.getPackedCRC() : ~dataIO.getUnpFileCRC(); int expectedCRC = hd.getFileCRC(); if (actualCRC != expectedCRC) { throw new RarException(RarExceptionType.crcError); } // if (!hd.isSplitAfter()) { // // Verify file CRC // if(~dataIO.getUnpFileCRC() != hd.getFileCRC()){ // throw new RarException(RarExceptionType.crcError); // } // } } catch (Exception e) { unpack.cleanUp(); if (e instanceof RarException) { // throw new RarException((RarException)e); throw (RarException) e; } else { throw new RarException(e); } } } /** * @return returns the main header of this archive */ public MainHeader getMainHeader() { return newMhd; } /** * @return whether the archive is old format */ public boolean isOldFormat() { return markHead.isOldFormat(); } /** Close the underlying compressed file. */ public void close() throws IOException { if (rof != null) { rof.close(); rof = null; } if (unpack != null) { unpack.cleanUp(); } } /** * @return the volumeManager */ public VolumeManager getVolumeManager() { return volumeManager; } /** * @param volumeManager * the volumeManager to set */ public void setVolumeManager(VolumeManager volumeManager) { this.volumeManager = volumeManager; } /** * @return the volume */ public Volume getVolume() { return volume; } /** * @param volume * the volume to set * @throws IOException */ public void setVolume(Volume volume) throws IOException { this.volume = volume; setFile(volume.getReadOnlyAccess(), volume.getLength()); } }
./CrossVul/dataset_final_sorted/CWE-835/java/bad_184_0
crossvul-java_data_good_184_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 com.github.junrar.testUtil; import com.github.junrar.Archive; import com.github.junrar.rarfile.FileHeader; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class SimpleTest { @Test public void testTikaDocs() throws Exception { String[] expected = {"testEXCEL.xls", "13824", "testHTML.html", "167", "testOpenOffice2.odt", "26448", "testPDF.pdf", "34824", "testPPT.ppt", "16384", "testRTF.rtf", "3410", "testTXT.txt", "49", "testWORD.doc", "19456", "testXML.xml", "766"}; File f = new File(getClass().getResource("test-documents.rar").toURI()); Archive archive = null; try { archive = new Archive(f); FileHeader fileHeader = archive.nextFileHeader(); int i = 0; while (fileHeader != null) { assertTrue(fileHeader.getFileNameString().contains(expected[i++])); assertEquals(Long.parseLong(expected[i++]), fileHeader.getUnpSize()); fileHeader = archive.nextFileHeader(); } } finally { archive.close(); } } }
./CrossVul/dataset_final_sorted/CWE-835/java/good_184_1
crossvul-java_data_bad_3046_0
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc., * Manufacture Francaise des Pneumatiques Michelin, 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 hudson.Functions; import hudson.security.PermissionScope; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.Collection; import hudson.search.SearchableModelObject; import hudson.security.Permission; import hudson.security.PermissionGroup; import hudson.security.AccessControlled; import hudson.util.Secret; /** * Basic configuration unit in Hudson. * * <p> * Every {@link Item} is hosted in an {@link ItemGroup} called "parent", * and some {@link Item}s are {@link ItemGroup}s. This form a tree * structure, which is rooted at {@link jenkins.model.Jenkins}. * * <p> * Unlike file systems, where a file can be moved from one directory * to another, {@link Item} inherently belongs to a single {@link ItemGroup} * and that relationship will not change. * Think of * <a href="http://images.google.com/images?q=Windows%20device%20manager">Windows device manager</a> * &mdash; an HDD always show up under 'Disk drives' and it can never be moved to another parent. * * Similarly, {@link ItemGroup} is not a generic container. Each subclass * of {@link ItemGroup} can usually only host a certain limited kinds of * {@link Item}s. * * <p> * {@link Item}s have unique {@link #getName() name}s that distinguish themselves * among their siblings uniquely. The names can be combined by '/' to form an * item full name, which uniquely identifies an {@link Item} inside the whole {@link jenkins.model.Jenkins}. * * @author Kohsuke Kawaguchi * @see Items * @see ItemVisitor */ public interface Item extends PersistenceRoot, SearchableModelObject, AccessControlled { /** * Gets the parent that contains this item. */ ItemGroup<? extends Item> getParent(); /** * Gets all the jobs that this {@link Item} contains as descendants. */ Collection<? extends Job> getAllJobs(); /** * Gets the name of the item. * * <p> * The name must be unique among other {@link Item}s that belong * to the same parent. * * <p> * This name is also used for directory name, so it cannot contain * any character that's not allowed on the file system. * * @see #getFullName() */ String getName(); /** * Gets the full name of this item, like "abc/def/ghi". * * <p> * Full name consists of {@link #getName() name}s of {@link Item}s * that lead from the root {@link jenkins.model.Jenkins} to this {@link Item}, * separated by '/'. This is the unique name that identifies this * {@link Item} inside the whole {@link jenkins.model.Jenkins}. * * @see jenkins.model.Jenkins#getItemByFullName(String,Class) */ String getFullName(); /** * Gets the human readable short name of this item. * * <p> * This method should try to return a short concise human * readable string that describes this item. * The string need not be unique. * * <p> * The returned string should not include the display names * of {@link #getParent() ancestor items}. */ String getDisplayName(); /** * Works like {@link #getDisplayName()} but return * the full path that includes all the display names * of the ancestors. */ String getFullDisplayName(); /** * Gets the relative name to this item from the specified group. * * @since 1.419 * @return * String like "../foo/bar" */ String getRelativeNameFrom(ItemGroup g); /** * Short for {@code getRelativeNameFrom(item.getParent())} * * @since 1.419 */ String getRelativeNameFrom(Item item); /** * Returns the URL of this item relative to the context root of the application. * * @see AbstractItem#getUrl() for how to implement this. * * @return * URL that ends with '/'. */ String getUrl(); /** * Returns the URL of this item relative to the parent {@link ItemGroup}. * @see AbstractItem#getShortUrl() for how to implement this. * * @return * URL that ends with '/'. */ String getShortUrl(); /** * Returns the absolute URL of this item. This relies on the current * {@link StaplerRequest} to figure out what the host name is, * so can be used only during processing client requests. * * @return * absolute URL. * @throws IllegalStateException * if the method is invoked outside the HTTP request processing. * * @deprecated * This method shall <b>NEVER</b> be used during HTML page rendering, as it won't work with * network set up like Apache reverse proxy. * This method is only intended for the remote API clients who cannot resolve relative references * (even this won't work for the same reason, which should be fixed.) */ @Deprecated String getAbsoluteUrl(); /** * Called right after when a {@link Item} is loaded from disk. * This is an opportunity to do a post load processing. * * @param name * Name of the directory (not a path --- just the name portion) from * which the configuration was loaded. This usually becomes the * {@link #getName() name} of this item. */ void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException; /** * 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. */ void onCopiedFrom(Item src); /** * When an item is created from scratch (instead of copied), * this method will be invoked. Used as the post-construction initialization. * * @since 1.374 */ void onCreatedFromScratch(); /** * Save the settings to a file. * * Use {@link Items#getConfigFile(Item)} * or {@link AbstractItem#getConfigFile()} to obtain the file * to save the data. */ void save() throws IOException; /** * Deletes this item. */ void delete() throws IOException, InterruptedException; PermissionGroup PERMISSIONS = new PermissionGroup(Item.class,Messages._Item_Permissions_Title()); Permission CREATE = new Permission(PERMISSIONS, "Create", Messages._Item_CREATE_description(), Permission.CREATE, PermissionScope.ITEM_GROUP); Permission DELETE = new Permission(PERMISSIONS, "Delete", Messages._Item_DELETE_description(), Permission.DELETE, PermissionScope.ITEM); Permission CONFIGURE = new Permission(PERMISSIONS, "Configure", Messages._Item_CONFIGURE_description(), Permission.CONFIGURE, PermissionScope.ITEM); Permission READ = new Permission(PERMISSIONS, "Read", Messages._Item_READ_description(), Permission.READ, PermissionScope.ITEM); Permission DISCOVER = new Permission(PERMISSIONS, "Discover", Messages._AbstractProject_DiscoverPermission_Description(), READ, PermissionScope.ITEM); /** * Ability to view configuration details. * If the user lacks {@link CONFIGURE} then any {@link Secret}s must be masked out, even in encrypted form. * @see Secret#ENCRYPTED_VALUE_PATTERN */ Permission EXTENDED_READ = new Permission(PERMISSIONS,"ExtendedRead", Messages._AbstractProject_ExtendedReadPermission_Description(), CONFIGURE, Boolean.getBoolean("hudson.security.ExtendedReadPermission"), new PermissionScope[]{PermissionScope.ITEM}); // TODO the following really belong in Job, not Item, but too late to move since the owner.name is encoded in the ID: Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._AbstractProject_BuildPermission_Description(), Permission.UPDATE, PermissionScope.ITEM); Permission WORKSPACE = new Permission(PERMISSIONS, "Workspace", Messages._AbstractProject_WorkspacePermission_Description(), Permission.READ, PermissionScope.ITEM); Permission WIPEOUT = new Permission(PERMISSIONS, "WipeOut", Messages._AbstractProject_WipeOutPermission_Description(), null, Functions.isWipeOutPermissionEnabled(), new PermissionScope[]{PermissionScope.ITEM}); Permission CANCEL = new Permission(PERMISSIONS, "Cancel", Messages._AbstractProject_CancelPermission_Description(), BUILD, PermissionScope.ITEM); }
./CrossVul/dataset_final_sorted/CWE-326/java/bad_3046_0
crossvul-java_data_good_3046_2
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi * Copyright (c) 2016, 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.util; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.trilead.ssh2.crypto.Base64; import java.util.Arrays; import jenkins.model.Jenkins; import hudson.Util; import jenkins.security.CryptoConfidentialKey; import org.kohsuke.stapler.Stapler; import javax.crypto.Cipher; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.regex.Pattern; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import static java.nio.charset.StandardCharsets.UTF_8; /** * Glorified {@link String} that uses encryption in the persisted form, to avoid accidental exposure of a secret. * * <p> * This is not meant as a protection against code running in the same VM, nor against an attacker * who has local file system access on Jenkins master. * * <p> * {@link Secret}s can correctly read-in plain text password, so this allows the existing * String field to be updated to {@link Secret}. * * @author Kohsuke Kawaguchi */ public final class Secret implements Serializable { private static final byte PAYLOAD_V1 = 1; /** * Unencrypted secret text. */ private final String value; private byte[] iv; /*package*/ Secret(String value) { this.value = value; } /*package*/ Secret(String value, byte[] iv) { this.value = value; this.iv = iv; } /** * Obtains the secret in a plain text. * * @see #getEncryptedValue() * @deprecated as of 1.356 * Use {@link #toString(Secret)} to avoid NPE in case Secret is null. * Or if you really know what you are doing, use the {@link #getPlainText()} method. */ @Override @Deprecated public String toString() { return value; } /** * Obtains the plain text password. * Before using this method, ask yourself if you'd be better off using {@link Secret#toString(Secret)} * to avoid NPE. */ public String getPlainText() { return value; } @Override public boolean equals(Object that) { return that instanceof Secret && value.equals(((Secret)that).value); } @Override public int hashCode() { return value.hashCode(); } /** * Encrypts {@link #value} and returns it in an encoded printable form. * * @see #toString() */ public String getEncryptedValue() { try { synchronized (this) { if (iv == null) { //if we were created from plain text or other reason without iv iv = KEY.newIv(); } } Cipher cipher = KEY.encrypt(iv); byte[] encrypted = cipher.doFinal(this.value.getBytes(UTF_8)); byte[] payload = new byte[1 + 8 + iv.length + encrypted.length]; int pos = 0; // For PAYLOAD_V1 we use this byte shifting model, V2 probably will need DataOutput payload[pos++] = PAYLOAD_V1; payload[pos++] = (byte)(iv.length >> 24); payload[pos++] = (byte)(iv.length >> 16); payload[pos++] = (byte)(iv.length >> 8); payload[pos++] = (byte)(iv.length); payload[pos++] = (byte)(encrypted.length >> 24); payload[pos++] = (byte)(encrypted.length >> 16); payload[pos++] = (byte)(encrypted.length >> 8); payload[pos++] = (byte)(encrypted.length); System.arraycopy(iv, 0, payload, pos, iv.length); pos+=iv.length; System.arraycopy(encrypted, 0, payload, pos, encrypted.length); return "{"+new String(Base64.encode(payload))+"}"; } catch (GeneralSecurityException e) { throw new Error(e); // impossible } } /** * Pattern matching a possible output of {@link #getEncryptedValue} * Basically, any Base64-encoded value optionally wrapped by {@code {}}. * You must then call {@link #decrypt(String)} to eliminate false positives. * @see #ENCRYPTED_VALUE_PATTERN */ @Restricted(NoExternalUse.class) public static final Pattern ENCRYPTED_VALUE_PATTERN = Pattern.compile("\\{?[A-Za-z0-9+/]+={0,2}}?"); /** * Reverse operation of {@link #getEncryptedValue()}. Returns null * if the given cipher text was invalid. */ public static Secret decrypt(String data) { if (data == null) return null; if (data.startsWith("{") && data.endsWith("}")) { //likely CBC encrypted/containing metadata but could be plain text byte[] payload; try { payload = Base64.decode(data.substring(1, data.length()-1).toCharArray()); } catch (IOException e) { return null; } switch (payload[0]) { case PAYLOAD_V1: // For PAYLOAD_V1 we use this byte shifting model, V2 probably will need DataOutput int ivLength = ((payload[1] & 0xff) << 24) | ((payload[2] & 0xff) << 16) | ((payload[3] & 0xff) << 8) | (payload[4] & 0xff); int dataLength = ((payload[5] & 0xff) << 24) | ((payload[6] & 0xff) << 16) | ((payload[7] & 0xff) << 8) | (payload[8] & 0xff); if (payload.length != 1 + 8 + ivLength + dataLength) { // not valid v1 return null; } byte[] iv = Arrays.copyOfRange(payload, 9, 9 + ivLength); byte[] code = Arrays.copyOfRange(payload, 9+ivLength, payload.length); String text; try { text = new String(KEY.decrypt(iv).doFinal(code), UTF_8); } catch (GeneralSecurityException e) { // it's v1 which cannot be historical, but not decrypting return null; } return new Secret(text, iv); default: return null; } } else { try { return HistoricalSecrets.decrypt(data, KEY); } catch (GeneralSecurityException e) { return null; } catch (UnsupportedEncodingException e) { throw new Error(e); // impossible } catch (IOException e) { return null; } } } /** * Workaround for JENKINS-6459 / http://java.net/jira/browse/GLASSFISH-11862 * This method uses specific provider selected via hudson.util.Secret.provider system property * to provide a workaround for the above bug where default provide gives an unusable instance. * (Glassfish Enterprise users should set value of this property to "SunJCE") */ public static Cipher getCipher(String algorithm) throws GeneralSecurityException { return PROVIDER != null ? Cipher.getInstance(algorithm, PROVIDER) : Cipher.getInstance(algorithm); } /** * Attempts to treat the given string first as a cipher text, and if it doesn't work, * treat the given string as the unencrypted secret value. * * <p> * Useful for recovering a value from a form field. * * @return never null */ public static Secret fromString(String data) { data = Util.fixNull(data); Secret s = decrypt(data); if(s==null) s=new Secret(data); return s; } /** * Works just like {@link Secret#toString()} but avoids NPE when the secret is null. * To be consistent with {@link #fromString(String)}, this method doesn't distinguish * empty password and null password. */ public static String toString(Secret s) { return s==null ? "" : s.value; } public static final class ConverterImpl implements Converter { public ConverterImpl() { } public boolean canConvert(Class type) { return type==Secret.class; } public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { Secret src = (Secret) source; writer.setValue(src.getEncryptedValue()); } public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) { return fromString(reader.getValue()); } } /** * Workaround for JENKINS-6459 / http://java.net/jira/browse/GLASSFISH-11862 * @see #getCipher(String) */ private static final String PROVIDER = System.getProperty(Secret.class.getName()+".provider"); /** * For testing only. Override the secret key so that we can test this class without {@link Jenkins}. */ /*package*/ static String SECRET = null; /** * The key that encrypts the data on disk. */ private static final CryptoConfidentialKey KEY = new CryptoConfidentialKey(Secret.class.getName()); /** * Reset the internal secret key for testing. */ @Restricted(NoExternalUse.class) /*package*/ static void resetKeyForTest() { KEY.resetForTest(); } private static final long serialVersionUID = 1L; static { Stapler.CONVERT_UTILS.register(new org.apache.commons.beanutils.Converter() { public Secret convert(Class type, Object value) { return Secret.fromString(value.toString()); } }, Secret.class); } }
./CrossVul/dataset_final_sorted/CWE-326/java/good_3046_2
crossvul-java_data_bad_3046_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-326/java/bad_3046_1
crossvul-java_data_good_3046_1
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi * Copyright (c) 2016, 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.util; import com.trilead.ssh2.crypto.Base64; import hudson.Util; import jenkins.model.Jenkins; import jenkins.security.CryptoConfidentialKey; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import javax.crypto.Cipher; import javax.crypto.SecretKey; import java.io.IOException; import java.security.GeneralSecurityException; import static java.nio.charset.StandardCharsets.UTF_8; /** * Historical algorithms for decrypting {@link Secret}s. */ @Restricted(NoExternalUse.class) public class HistoricalSecrets { /*package*/ static Secret decrypt(String data, CryptoConfidentialKey key) throws IOException, GeneralSecurityException { byte[] in = Base64.decode(data.toCharArray()); Secret s = tryDecrypt(key.decrypt(), in); if (s!=null) return s; // try our historical key for backward compatibility Cipher cipher = Secret.getCipher("AES"); cipher.init(Cipher.DECRYPT_MODE, getLegacyKey()); return tryDecrypt(cipher, in); } /*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) { try { String plainText = new String(cipher.doFinal(in), UTF_8); if(plainText.endsWith(MAGIC)) return new Secret(plainText.substring(0,plainText.length()-MAGIC.length())); return null; } catch (GeneralSecurityException e) { return null; // if the key doesn't match with the bytes, it can result in BadPaddingException } } /** * Turns {@link Jenkins#getSecretKey()} into an AES key. * * @deprecated * This is no longer the key we use to encrypt new information, but we still need this * to be able to decrypt what's already persisted. */ @Deprecated /*package*/ static SecretKey getLegacyKey() throws GeneralSecurityException { String secret = Secret.SECRET; if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128(); return Util.toAes128Key(secret); } private static final String MAGIC = "::::MAGIC::::"; }
./CrossVul/dataset_final_sorted/CWE-326/java/good_3046_1
crossvul-java_data_good_3046_3
package hudson.util; import com.trilead.ssh2.crypto.Base64; import hudson.model.TaskListener; import javax.crypto.Cipher; import javax.crypto.SecretKey; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.util.HashSet; import java.util.Set; /** * Rewrites XML files by looking for Secrets that are stored with the old key and replaces them * by the new encrypted values. * * @author Kohsuke Kawaguchi */ public class SecretRewriter { private final Cipher cipher; private final SecretKey key; /** * How many files have been scanned? */ private int count; /** * Canonical paths of the directories we are recursing to protect * against symlink induced cycles. */ private Set<String> callstack = new HashSet<String>(); public SecretRewriter() throws GeneralSecurityException { cipher = Secret.getCipher("AES"); key = HistoricalSecrets.getLegacyKey(); } /** @deprecated SECURITY-376: {@code backupDirectory} is ignored */ @Deprecated public SecretRewriter(File backupDirectory) throws GeneralSecurityException { this(); } private String tryRewrite(String s) throws IOException, InvalidKeyException { if (s.length()<24) return s; // Encrypting "" in Secret produces 24-letter characters, so this must be the minimum length if (!isBase64(s)) return s; // decode throws IOException if the input is not base64, and this is also a very quick way to filter byte[] in; try { in = Base64.decode(s.toCharArray()); } catch (IOException e) { return s; // not a valid base64 } cipher.init(Cipher.DECRYPT_MODE, key); Secret sec = HistoricalSecrets.tryDecrypt(cipher, in); if(sec!=null) // matched return sec.getEncryptedValue(); // replace by the new encrypted value else // not encrypted with the legacy key. leave it unmodified return s; } /** @deprecated SECURITY-376: {@code backup} is ignored */ @Deprecated public boolean rewrite(File f, File backup) throws InvalidKeyException, IOException { return rewrite(f); } public boolean rewrite(File f) throws InvalidKeyException, IOException { AtomicFileWriter w = new AtomicFileWriter(f, "UTF-8"); try { PrintWriter out = new PrintWriter(new BufferedWriter(w)); boolean modified = false; // did we actually change anything? try { FileInputStream fin = new FileInputStream(f); try { BufferedReader r = new BufferedReader(new InputStreamReader(fin, "UTF-8")); String line; StringBuilder buf = new StringBuilder(); while ((line=r.readLine())!=null) { int copied=0; buf.setLength(0); while (true) { int sidx = line.indexOf('>',copied); if (sidx<0) break; int eidx = line.indexOf('<',sidx); if (eidx<0) break; String elementText = line.substring(sidx+1,eidx); String replacement = tryRewrite(elementText); if (!replacement.equals(elementText)) modified = true; buf.append(line.substring(copied,sidx+1)); buf.append(replacement); copied = eidx; } buf.append(line.substring(copied)); out.println(buf.toString()); } } finally { fin.close(); } } finally { out.close(); } if (modified) { w.commit(); } return modified; } finally { w.abort(); } } /** * Recursively scans and rewrites a directory. * * This method shouldn't abort just because one file fails to rewrite. * * @return * Number of files that were actually rewritten. */ // synchronized to prevent accidental concurrent use. this instance is not thread safe public synchronized int rewriteRecursive(File dir, TaskListener listener) throws InvalidKeyException { return rewriteRecursive(dir,"",listener); } private int rewriteRecursive(File dir, String relative, TaskListener listener) throws InvalidKeyException { String canonical; try { canonical = dir.getCanonicalPath(); } catch (IOException e) { canonical = dir.getAbsolutePath(); // } if (!callstack.add(canonical)) { listener.getLogger().println("Cycle detected: "+dir); return 0; } try { File[] children = dir.listFiles(); if (children==null) return 0; int rewritten=0; for (File child : children) { String cn = child.getName(); if (cn.endsWith(".xml")) { if ((count++)%100==0) listener.getLogger().println("Scanning "+child); try { if (rewrite(child)) { listener.getLogger().println("Rewritten "+child); rewritten++; } } catch (IOException e) { e.printStackTrace(listener.error("Failed to rewrite "+child)); } } if (child.isDirectory()) { if (!isIgnoredDir(child)) rewritten += rewriteRecursive(child, relative.length()==0 ? cn : relative+'/'+ cn, listener); } } return rewritten; } finally { callstack.remove(canonical); } } /** * Decides if this directory is worth visiting or not. */ protected boolean isIgnoredDir(File dir) { // ignoring the workspace and the artifacts directories. Both of them // are potentially large and they do not store any secrets. String n = dir.getName(); return n.equals("workspace") || n.equals("artifacts") || n.equals("plugins") // no mutable data here || n.equals(".") || n.equals(".."); } private static boolean isBase64(char ch) { return 0<=ch && ch<128 && IS_BASE64[ch]; } private static boolean isBase64(String s) { for (int i=0; i<s.length(); i++) if (!isBase64(s.charAt(i))) return false; return true; } private static final boolean[] IS_BASE64 = new boolean[128]; static { String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; for (int i=0; i<chars.length();i++) IS_BASE64[chars.charAt(i)] = true; } }
./CrossVul/dataset_final_sorted/CWE-326/java/good_3046_3
crossvul-java_data_bad_3046_2
/* * The MIT License * * Copyright (c) 2004-2010, 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.util; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.trilead.ssh2.crypto.Base64; import jenkins.model.Jenkins; import hudson.Util; import jenkins.security.CryptoConfidentialKey; import org.kohsuke.stapler.Stapler; import javax.crypto.SecretKey; import javax.crypto.Cipher; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.regex.Pattern; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Glorified {@link String} that uses encryption in the persisted form, to avoid accidental exposure of a secret. * * <p> * This is not meant as a protection against code running in the same VM, nor against an attacker * who has local file system access on Jenkins master. * * <p> * {@link Secret}s can correctly read-in plain text password, so this allows the existing * String field to be updated to {@link Secret}. * * @author Kohsuke Kawaguchi */ public final class Secret implements Serializable { /** * Unencrypted secret text. */ private final String value; private Secret(String value) { this.value = value; } /** * Obtains the secret in a plain text. * * @see #getEncryptedValue() * @deprecated as of 1.356 * Use {@link #toString(Secret)} to avoid NPE in case Secret is null. * Or if you really know what you are doing, use the {@link #getPlainText()} method. */ @Override @Deprecated public String toString() { return value; } /** * Obtains the plain text password. * Before using this method, ask yourself if you'd be better off using {@link Secret#toString(Secret)} * to avoid NPE. */ public String getPlainText() { return value; } @Override public boolean equals(Object that) { return that instanceof Secret && value.equals(((Secret)that).value); } @Override public int hashCode() { return value.hashCode(); } /** * Turns {@link Jenkins#getSecretKey()} into an AES key. * * @deprecated * This is no longer the key we use to encrypt new information, but we still need this * to be able to decrypt what's already persisted. */ @Deprecated /*package*/ static SecretKey getLegacyKey() throws GeneralSecurityException { String secret = SECRET; if(secret==null) return Jenkins.getInstance().getSecretKeyAsAES128(); return Util.toAes128Key(secret); } /** * Encrypts {@link #value} and returns it in an encoded printable form. * * @see #toString() */ public String getEncryptedValue() { try { Cipher cipher = KEY.encrypt(); // add the magic suffix which works like a check sum. return new String(Base64.encode(cipher.doFinal((value+MAGIC).getBytes("UTF-8")))); } catch (GeneralSecurityException e) { throw new Error(e); // impossible } catch (UnsupportedEncodingException e) { throw new Error(e); // impossible } } /** * Pattern matching a possible output of {@link #getEncryptedValue}. * Basically, any Base64-encoded value. * You must then call {@link #decrypt} to eliminate false positives. */ @Restricted(NoExternalUse.class) public static final Pattern ENCRYPTED_VALUE_PATTERN = Pattern.compile("[A-Za-z0-9+/]+={0,2}"); /** * Reverse operation of {@link #getEncryptedValue()}. Returns null * if the given cipher text was invalid. */ public static Secret decrypt(String data) { if(data==null) return null; try { byte[] in = Base64.decode(data.toCharArray()); Secret s = tryDecrypt(KEY.decrypt(), in); if (s!=null) return s; // try our historical key for backward compatibility Cipher cipher = getCipher("AES"); cipher.init(Cipher.DECRYPT_MODE, getLegacyKey()); return tryDecrypt(cipher, in); } catch (GeneralSecurityException e) { return null; } catch (UnsupportedEncodingException e) { throw new Error(e); // impossible } catch (IOException e) { return null; } } /*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) throws UnsupportedEncodingException { try { String plainText = new String(cipher.doFinal(in), "UTF-8"); if(plainText.endsWith(MAGIC)) return new Secret(plainText.substring(0,plainText.length()-MAGIC.length())); return null; } catch (GeneralSecurityException e) { return null; // if the key doesn't match with the bytes, it can result in BadPaddingException } } /** * Workaround for JENKINS-6459 / http://java.net/jira/browse/GLASSFISH-11862 * This method uses specific provider selected via hudson.util.Secret.provider system property * to provide a workaround for the above bug where default provide gives an unusable instance. * (Glassfish Enterprise users should set value of this property to "SunJCE") */ public static Cipher getCipher(String algorithm) throws GeneralSecurityException { return PROVIDER != null ? Cipher.getInstance(algorithm, PROVIDER) : Cipher.getInstance(algorithm); } /** * Attempts to treat the given string first as a cipher text, and if it doesn't work, * treat the given string as the unencrypted secret value. * * <p> * Useful for recovering a value from a form field. * * @return never null */ public static Secret fromString(String data) { data = Util.fixNull(data); Secret s = decrypt(data); if(s==null) s=new Secret(data); return s; } /** * Works just like {@link Secret#toString()} but avoids NPE when the secret is null. * To be consistent with {@link #fromString(String)}, this method doesn't distinguish * empty password and null password. */ public static String toString(Secret s) { return s==null ? "" : s.value; } public static final class ConverterImpl implements Converter { public ConverterImpl() { } public boolean canConvert(Class type) { return type==Secret.class; } public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { Secret src = (Secret) source; writer.setValue(src.getEncryptedValue()); } public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) { return fromString(reader.getValue()); } } private static final String MAGIC = "::::MAGIC::::"; /** * Workaround for JENKINS-6459 / http://java.net/jira/browse/GLASSFISH-11862 * @see #getCipher(String) */ private static final String PROVIDER = System.getProperty(Secret.class.getName()+".provider"); /** * For testing only. Override the secret key so that we can test this class without {@link Jenkins}. */ /*package*/ static String SECRET = null; /** * The key that encrypts the data on disk. */ private static final CryptoConfidentialKey KEY = new CryptoConfidentialKey(Secret.class.getName()); private static final long serialVersionUID = 1L; static { Stapler.CONVERT_UTILS.register(new org.apache.commons.beanutils.Converter() { public Secret convert(Class type, Object value) { return Secret.fromString(value.toString()); } }, Secret.class); } }
./CrossVul/dataset_final_sorted/CWE-326/java/bad_3046_2
crossvul-java_data_bad_3046_3
package hudson.util; import com.trilead.ssh2.crypto.Base64; import hudson.model.TaskListener; import javax.crypto.Cipher; import javax.crypto.SecretKey; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.util.HashSet; import java.util.Set; /** * Rewrites XML files by looking for Secrets that are stored with the old key and replaces them * by the new encrypted values. * * @author Kohsuke Kawaguchi */ public class SecretRewriter { private final Cipher cipher; private final SecretKey key; /** * How many files have been scanned? */ private int count; /** * Canonical paths of the directories we are recursing to protect * against symlink induced cycles. */ private Set<String> callstack = new HashSet<String>(); public SecretRewriter() throws GeneralSecurityException { cipher = Secret.getCipher("AES"); key = Secret.getLegacyKey(); } /** @deprecated SECURITY-376: {@code backupDirectory} is ignored */ @Deprecated public SecretRewriter(File backupDirectory) throws GeneralSecurityException { this(); } private String tryRewrite(String s) throws IOException, InvalidKeyException { if (s.length()<24) return s; // Encrypting "" in Secret produces 24-letter characters, so this must be the minimum length if (!isBase64(s)) return s; // decode throws IOException if the input is not base64, and this is also a very quick way to filter byte[] in; try { in = Base64.decode(s.toCharArray()); } catch (IOException e) { return s; // not a valid base64 } cipher.init(Cipher.DECRYPT_MODE, key); Secret sec = Secret.tryDecrypt(cipher, in); if(sec!=null) // matched return sec.getEncryptedValue(); // replace by the new encrypted value else // not encrypted with the legacy key. leave it unmodified return s; } /** @deprecated SECURITY-376: {@code backup} is ignored */ @Deprecated public boolean rewrite(File f, File backup) throws InvalidKeyException, IOException { return rewrite(f); } public boolean rewrite(File f) throws InvalidKeyException, IOException { AtomicFileWriter w = new AtomicFileWriter(f, "UTF-8"); try { PrintWriter out = new PrintWriter(new BufferedWriter(w)); boolean modified = false; // did we actually change anything? try { FileInputStream fin = new FileInputStream(f); try { BufferedReader r = new BufferedReader(new InputStreamReader(fin, "UTF-8")); String line; StringBuilder buf = new StringBuilder(); while ((line=r.readLine())!=null) { int copied=0; buf.setLength(0); while (true) { int sidx = line.indexOf('>',copied); if (sidx<0) break; int eidx = line.indexOf('<',sidx); if (eidx<0) break; String elementText = line.substring(sidx+1,eidx); String replacement = tryRewrite(elementText); if (!replacement.equals(elementText)) modified = true; buf.append(line.substring(copied,sidx+1)); buf.append(replacement); copied = eidx; } buf.append(line.substring(copied)); out.println(buf.toString()); } } finally { fin.close(); } } finally { out.close(); } if (modified) { w.commit(); } return modified; } finally { w.abort(); } } /** * Recursively scans and rewrites a directory. * * This method shouldn't abort just because one file fails to rewrite. * * @return * Number of files that were actually rewritten. */ // synchronized to prevent accidental concurrent use. this instance is not thread safe public synchronized int rewriteRecursive(File dir, TaskListener listener) throws InvalidKeyException { return rewriteRecursive(dir,"",listener); } private int rewriteRecursive(File dir, String relative, TaskListener listener) throws InvalidKeyException { String canonical; try { canonical = dir.getCanonicalPath(); } catch (IOException e) { canonical = dir.getAbsolutePath(); // } if (!callstack.add(canonical)) { listener.getLogger().println("Cycle detected: "+dir); return 0; } try { File[] children = dir.listFiles(); if (children==null) return 0; int rewritten=0; for (File child : children) { String cn = child.getName(); if (cn.endsWith(".xml")) { if ((count++)%100==0) listener.getLogger().println("Scanning "+child); try { if (rewrite(child)) { listener.getLogger().println("Rewritten "+child); rewritten++; } } catch (IOException e) { e.printStackTrace(listener.error("Failed to rewrite "+child)); } } if (child.isDirectory()) { if (!isIgnoredDir(child)) rewritten += rewriteRecursive(child, relative.length()==0 ? cn : relative+'/'+ cn, listener); } } return rewritten; } finally { callstack.remove(canonical); } } /** * Decides if this directory is worth visiting or not. */ protected boolean isIgnoredDir(File dir) { // ignoring the workspace and the artifacts directories. Both of them // are potentially large and they do not store any secrets. String n = dir.getName(); return n.equals("workspace") || n.equals("artifacts") || n.equals("plugins") // no mutable data here || n.equals(".") || n.equals(".."); } private static boolean isBase64(char ch) { return 0<=ch && ch<128 && IS_BASE64[ch]; } private static boolean isBase64(String s) { for (int i=0; i<s.length(); i++) if (!isBase64(s.charAt(i))) return false; return true; } private static final boolean[] IS_BASE64 = new boolean[128]; static { String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; for (int i=0; i<chars.length();i++) IS_BASE64[chars.charAt(i)] = true; } }
./CrossVul/dataset_final_sorted/CWE-326/java/bad_3046_3
crossvul-java_data_good_3046_0
/* * The MIT License * * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc., * Manufacture Francaise des Pneumatiques Michelin, 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 hudson.Functions; import hudson.security.PermissionScope; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.Collection; import hudson.search.SearchableModelObject; import hudson.security.Permission; import hudson.security.PermissionGroup; import hudson.security.AccessControlled; import hudson.util.Secret; /** * Basic configuration unit in Hudson. * * <p> * Every {@link Item} is hosted in an {@link ItemGroup} called "parent", * and some {@link Item}s are {@link ItemGroup}s. This form a tree * structure, which is rooted at {@link jenkins.model.Jenkins}. * * <p> * Unlike file systems, where a file can be moved from one directory * to another, {@link Item} inherently belongs to a single {@link ItemGroup} * and that relationship will not change. * Think of * <a href="http://images.google.com/images?q=Windows%20device%20manager">Windows device manager</a> * &mdash; an HDD always show up under 'Disk drives' and it can never be moved to another parent. * * Similarly, {@link ItemGroup} is not a generic container. Each subclass * of {@link ItemGroup} can usually only host a certain limited kinds of * {@link Item}s. * * <p> * {@link Item}s have unique {@link #getName() name}s that distinguish themselves * among their siblings uniquely. The names can be combined by '/' to form an * item full name, which uniquely identifies an {@link Item} inside the whole {@link jenkins.model.Jenkins}. * * @author Kohsuke Kawaguchi * @see Items * @see ItemVisitor */ public interface Item extends PersistenceRoot, SearchableModelObject, AccessControlled { /** * Gets the parent that contains this item. */ ItemGroup<? extends Item> getParent(); /** * Gets all the jobs that this {@link Item} contains as descendants. */ Collection<? extends Job> getAllJobs(); /** * Gets the name of the item. * * <p> * The name must be unique among other {@link Item}s that belong * to the same parent. * * <p> * This name is also used for directory name, so it cannot contain * any character that's not allowed on the file system. * * @see #getFullName() */ String getName(); /** * Gets the full name of this item, like "abc/def/ghi". * * <p> * Full name consists of {@link #getName() name}s of {@link Item}s * that lead from the root {@link jenkins.model.Jenkins} to this {@link Item}, * separated by '/'. This is the unique name that identifies this * {@link Item} inside the whole {@link jenkins.model.Jenkins}. * * @see jenkins.model.Jenkins#getItemByFullName(String,Class) */ String getFullName(); /** * Gets the human readable short name of this item. * * <p> * This method should try to return a short concise human * readable string that describes this item. * The string need not be unique. * * <p> * The returned string should not include the display names * of {@link #getParent() ancestor items}. */ String getDisplayName(); /** * Works like {@link #getDisplayName()} but return * the full path that includes all the display names * of the ancestors. */ String getFullDisplayName(); /** * Gets the relative name to this item from the specified group. * * @since 1.419 * @return * String like "../foo/bar" */ String getRelativeNameFrom(ItemGroup g); /** * Short for {@code getRelativeNameFrom(item.getParent())} * * @since 1.419 */ String getRelativeNameFrom(Item item); /** * Returns the URL of this item relative to the context root of the application. * * @see AbstractItem#getUrl() for how to implement this. * * @return * URL that ends with '/'. */ String getUrl(); /** * Returns the URL of this item relative to the parent {@link ItemGroup}. * @see AbstractItem#getShortUrl() for how to implement this. * * @return * URL that ends with '/'. */ String getShortUrl(); /** * Returns the absolute URL of this item. This relies on the current * {@link StaplerRequest} to figure out what the host name is, * so can be used only during processing client requests. * * @return * absolute URL. * @throws IllegalStateException * if the method is invoked outside the HTTP request processing. * * @deprecated * This method shall <b>NEVER</b> be used during HTML page rendering, as it won't work with * network set up like Apache reverse proxy. * This method is only intended for the remote API clients who cannot resolve relative references * (even this won't work for the same reason, which should be fixed.) */ @Deprecated String getAbsoluteUrl(); /** * Called right after when a {@link Item} is loaded from disk. * This is an opportunity to do a post load processing. * * @param name * Name of the directory (not a path --- just the name portion) from * which the configuration was loaded. This usually becomes the * {@link #getName() name} of this item. */ void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException; /** * 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. */ void onCopiedFrom(Item src); /** * When an item is created from scratch (instead of copied), * this method will be invoked. Used as the post-construction initialization. * * @since 1.374 */ void onCreatedFromScratch(); /** * Save the settings to a file. * * Use {@link Items#getConfigFile(Item)} * or {@link AbstractItem#getConfigFile()} to obtain the file * to save the data. */ void save() throws IOException; /** * Deletes this item. */ void delete() throws IOException, InterruptedException; PermissionGroup PERMISSIONS = new PermissionGroup(Item.class,Messages._Item_Permissions_Title()); Permission CREATE = new Permission(PERMISSIONS, "Create", Messages._Item_CREATE_description(), Permission.CREATE, PermissionScope.ITEM_GROUP); Permission DELETE = new Permission(PERMISSIONS, "Delete", Messages._Item_DELETE_description(), Permission.DELETE, PermissionScope.ITEM); Permission CONFIGURE = new Permission(PERMISSIONS, "Configure", Messages._Item_CONFIGURE_description(), Permission.CONFIGURE, PermissionScope.ITEM); Permission READ = new Permission(PERMISSIONS, "Read", Messages._Item_READ_description(), Permission.READ, PermissionScope.ITEM); Permission DISCOVER = new Permission(PERMISSIONS, "Discover", Messages._AbstractProject_DiscoverPermission_Description(), READ, PermissionScope.ITEM); /** * Ability to view configuration details. * If the user lacks {@link #CONFIGURE} then any {@link Secret}s must be masked out, even in encrypted form. * @see Secret#ENCRYPTED_VALUE_PATTERN */ Permission EXTENDED_READ = new Permission(PERMISSIONS,"ExtendedRead", Messages._AbstractProject_ExtendedReadPermission_Description(), CONFIGURE, Boolean.getBoolean("hudson.security.ExtendedReadPermission"), new PermissionScope[]{PermissionScope.ITEM}); // TODO the following really belong in Job, not Item, but too late to move since the owner.name is encoded in the ID: Permission BUILD = new Permission(PERMISSIONS, "Build", Messages._AbstractProject_BuildPermission_Description(), Permission.UPDATE, PermissionScope.ITEM); Permission WORKSPACE = new Permission(PERMISSIONS, "Workspace", Messages._AbstractProject_WorkspacePermission_Description(), Permission.READ, PermissionScope.ITEM); Permission WIPEOUT = new Permission(PERMISSIONS, "WipeOut", Messages._AbstractProject_WipeOutPermission_Description(), null, Functions.isWipeOutPermissionEnabled(), new PermissionScope[]{PermissionScope.ITEM}); Permission CANCEL = new Permission(PERMISSIONS, "Cancel", Messages._AbstractProject_CancelPermission_Description(), BUILD, PermissionScope.ITEM); }
./CrossVul/dataset_final_sorted/CWE-326/java/good_3046_0
crossvul-java_data_bad_2733_0
package org.bouncycastle.tls.crypto.impl.jcajce; import java.io.IOException; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.interfaces.RSAPrivateKey; import javax.crypto.Cipher; import org.bouncycastle.tls.Certificate; import org.bouncycastle.tls.ProtocolVersion; import org.bouncycastle.tls.TlsCredentialedDecryptor; import org.bouncycastle.tls.crypto.TlsCryptoParameters; import org.bouncycastle.tls.crypto.TlsSecret; import org.bouncycastle.util.Arrays; /** * Credentialed class decrypting RSA encrypted secrets sent from a peer for our end of the TLS connection using the JCE. */ public class JceDefaultTlsCredentialedDecryptor implements TlsCredentialedDecryptor { protected JcaTlsCrypto crypto; protected Certificate certificate; protected PrivateKey privateKey; public JceDefaultTlsCredentialedDecryptor(JcaTlsCrypto crypto, Certificate certificate, PrivateKey privateKey) { if (crypto == null) { throw new IllegalArgumentException("'crypto' cannot be null"); } if (certificate == null) { throw new IllegalArgumentException("'certificate' cannot be null"); } if (certificate.isEmpty()) { throw new IllegalArgumentException("'certificate' cannot be empty"); } if (privateKey == null) { throw new IllegalArgumentException("'privateKey' cannot be null"); } if (privateKey instanceof RSAPrivateKey || "RSA".equals(privateKey.getAlgorithm())) { this.crypto = crypto; this.certificate = certificate; this.privateKey = privateKey; } else { throw new IllegalArgumentException("'privateKey' type not supported: " + privateKey.getClass().getName()); } } public Certificate getCertificate() { return certificate; } public TlsSecret decrypt(TlsCryptoParameters cryptoParams, byte[] ciphertext) throws IOException { // TODO Keep only the decryption itself here - move error handling outside return safeDecryptPreMasterSecret(cryptoParams, privateKey, ciphertext); } /* * TODO[tls-ops] Probably need to make RSA encryption/decryption into TlsCrypto functions so * that users can implement "generic" encryption credentials externally */ protected TlsSecret safeDecryptPreMasterSecret(TlsCryptoParameters cryptoParams, PrivateKey rsaServerPrivateKey, byte[] encryptedPreMasterSecret) { SecureRandom secureRandom = crypto.getSecureRandom(); /* * RFC 5246 7.4.7.1. */ ProtocolVersion clientVersion = cryptoParams.getClientVersion(); // TODO Provide as configuration option? boolean versionNumberCheckDisabled = false; /* * Generate 48 random bytes we can use as a Pre-Master-Secret, if the * PKCS1 padding check should fail. */ byte[] fallback = new byte[48]; secureRandom.nextBytes(fallback); byte[] M = Arrays.clone(fallback); try { Cipher c = crypto.createRSAEncryptionCipher(); c.init(Cipher.DECRYPT_MODE, rsaServerPrivateKey); M = c.doFinal(encryptedPreMasterSecret); } catch (Exception e) { /* * A TLS server MUST NOT generate an alert if processing an * RSA-encrypted premaster secret message fails, or the version number is not as * expected. Instead, it MUST continue the handshake with a randomly generated * premaster secret. */ } /* * If ClientHello.client_version is TLS 1.1 or higher, server implementations MUST * check the version number [..]. */ if (versionNumberCheckDisabled && clientVersion.isEqualOrEarlierVersionOf(ProtocolVersion.TLSv10)) { /* * If the version number is TLS 1.0 or earlier, server * implementations SHOULD check the version number, but MAY have a * configuration option to disable the check. * * So there is nothing to do here. */ } else { /* * OK, we need to compare the version number in the decrypted Pre-Master-Secret with the * clientVersion received during the handshake. If they don't match, we replace the * decrypted Pre-Master-Secret with a random one. */ int correct = (clientVersion.getMajorVersion() ^ (M[0] & 0xff)) | (clientVersion.getMinorVersion() ^ (M[1] & 0xff)); correct |= correct >> 1; correct |= correct >> 2; correct |= correct >> 4; int mask = ~((correct & 1) - 1); /* * mask will be all bits set to 0xff if the version number differed. */ for (int i = 0; i < 48; i++) { M[i] = (byte)((M[i] & (~mask)) | (fallback[i] & mask)); } } return crypto.createSecret(M); } }
./CrossVul/dataset_final_sorted/CWE-203/java/bad_2733_0
crossvul-java_data_good_2733_0
package org.bouncycastle.tls.crypto.impl.jcajce; import java.io.IOException; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.interfaces.RSAPrivateKey; import javax.crypto.Cipher; import org.bouncycastle.tls.Certificate; import org.bouncycastle.tls.ProtocolVersion; import org.bouncycastle.tls.TlsCredentialedDecryptor; import org.bouncycastle.tls.crypto.TlsCryptoParameters; import org.bouncycastle.tls.crypto.TlsSecret; import org.bouncycastle.util.Arrays; /** * Credentialed class decrypting RSA encrypted secrets sent from a peer for our end of the TLS connection using the JCE. */ public class JceDefaultTlsCredentialedDecryptor implements TlsCredentialedDecryptor { protected JcaTlsCrypto crypto; protected Certificate certificate; protected PrivateKey privateKey; public JceDefaultTlsCredentialedDecryptor(JcaTlsCrypto crypto, Certificate certificate, PrivateKey privateKey) { if (crypto == null) { throw new IllegalArgumentException("'crypto' cannot be null"); } if (certificate == null) { throw new IllegalArgumentException("'certificate' cannot be null"); } if (certificate.isEmpty()) { throw new IllegalArgumentException("'certificate' cannot be empty"); } if (privateKey == null) { throw new IllegalArgumentException("'privateKey' cannot be null"); } if (privateKey instanceof RSAPrivateKey || "RSA".equals(privateKey.getAlgorithm())) { this.crypto = crypto; this.certificate = certificate; this.privateKey = privateKey; } else { throw new IllegalArgumentException("'privateKey' type not supported: " + privateKey.getClass().getName()); } } public Certificate getCertificate() { return certificate; } public TlsSecret decrypt(TlsCryptoParameters cryptoParams, byte[] ciphertext) throws IOException { // TODO Keep only the decryption itself here - move error handling outside return safeDecryptPreMasterSecret(cryptoParams, privateKey, ciphertext); } /* * TODO[tls-ops] Probably need to make RSA encryption/decryption into TlsCrypto functions so * that users can implement "generic" encryption credentials externally */ protected TlsSecret safeDecryptPreMasterSecret(TlsCryptoParameters cryptoParams, PrivateKey rsaServerPrivateKey, byte[] encryptedPreMasterSecret) { SecureRandom secureRandom = crypto.getSecureRandom(); /* * RFC 5246 7.4.7.1. */ ProtocolVersion clientVersion = cryptoParams.getClientVersion(); // TODO Provide as configuration option? boolean versionNumberCheckDisabled = false; /* * Generate 48 random bytes we can use as a Pre-Master-Secret, if the * PKCS1 padding check should fail. */ byte[] fallback = new byte[48]; secureRandom.nextBytes(fallback); byte[] M = Arrays.clone(fallback); try { Cipher c = crypto.createRSAEncryptionCipher(); c.init(Cipher.DECRYPT_MODE, rsaServerPrivateKey); byte[] m = c.doFinal(encryptedPreMasterSecret); if (m != null && m.length == 48) { M = m; } } catch (Exception e) { /* * A TLS server MUST NOT generate an alert if processing an * RSA-encrypted premaster secret message fails, or the version number is not as * expected. Instead, it MUST continue the handshake with a randomly generated * premaster secret. */ } /* * If ClientHello.client_version is TLS 1.1 or higher, server implementations MUST * check the version number [..]. */ if (versionNumberCheckDisabled && clientVersion.isEqualOrEarlierVersionOf(ProtocolVersion.TLSv10)) { /* * If the version number is TLS 1.0 or earlier, server * implementations SHOULD check the version number, but MAY have a * configuration option to disable the check. * * So there is nothing to do here. */ } else { /* * OK, we need to compare the version number in the decrypted Pre-Master-Secret with the * clientVersion received during the handshake. If they don't match, we replace the * decrypted Pre-Master-Secret with a random one. */ int correct = (clientVersion.getMajorVersion() ^ (M[0] & 0xff)) | (clientVersion.getMinorVersion() ^ (M[1] & 0xff)); correct |= correct >> 1; correct |= correct >> 2; correct |= correct >> 4; int mask = ~((correct & 1) - 1); /* * mask will be all bits set to 0xff if the version number differed. */ for (int i = 0; i < 48; i++) { M[i] = (byte)((M[i] & (~mask)) | (fallback[i] & mask)); } } return crypto.createSecret(M); } }
./CrossVul/dataset_final_sorted/CWE-203/java/good_2733_0
crossvul-java_data_good_830_1
/* * Copyright 2013 the original author or authors. * * 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 ratpack.session.internal; import com.google.inject.Singleton; import io.netty.util.AsciiString; import ratpack.session.SessionIdGenerator; import java.util.UUID; @Singleton public class DefaultSessionIdGenerator implements SessionIdGenerator { public AsciiString generateSessionId() { return AsciiString.cached(UUID.randomUUID().toString()); } }
./CrossVul/dataset_final_sorted/CWE-338/java/good_830_1
crossvul-java_data_good_830_0
/* * Copyright 2015 the original author or authors. * * 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 ratpack.session; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalListener; import com.google.inject.*; import com.google.inject.name.Names; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.util.AsciiString; import ratpack.func.Action; import ratpack.guice.BindingsSpec; import ratpack.guice.ConfigurableModule; import ratpack.guice.RequestScoped; import ratpack.http.Request; import ratpack.http.Response; import ratpack.session.internal.*; import ratpack.util.Types; import javax.inject.Named; import java.io.Serializable; import java.util.function.Consumer; /** * Provides support for HTTP sessions. * <p> * This module provides the general session API (see {@link Session}), and a default {@link SessionStore} implementation that stores session data in local memory. * * <h3>The session store</h3> * <p> * It is expected that most applications will provide alternative bindings for the {@link SessionStore} type, overriding the default. * This allows arbitrary stores to be used to persist session data. * <p> * The default, in memory, implementation stores the data in a {@link Cache}{@code <}{@link AsciiString}, {@link ByteBuf}{@code >}. * This cache instance is provided by this module and defaults to storing a maximum of 1000 entries, discarding least recently used. * The {@link #memoryStore} methods are provided to conveniently construct alternative cache configurations, if necessary. * <h3>Serialization</h3> * <p> * Objects must be serialized to be stored in the session. * The get/set methods {@link SessionData} allow supplying a {@link SessionSerializer} to be used for the specific value. * For variants of the get/set methods where a serializer is not provided, the implementation of {@link SessionSerializer} bound with Guice will be used. * The default implementation provided by this module uses Java's in built serialization mechanism. * Users of this module may choose to override this binding with an alternative serialization strategy. * <p> * However, other Ratpack extensions may require session storage any rely on Java serialization. * For this reason, there is also always a {@link JavaSessionSerializer} implementation available that is guaranteed to be able to serialize any {@link Serializable} * object (that conforms to the {@link Serializable} contract. * Users of this module may also choose to override this binding with another implementation (e.g. one based on <a href="https://github.com/EsotericSoftware/kryo">Kryo</a>), * but this implementation must be able to serialize any object implementing {@link Serializable}. * * It is also often desirable to provide alternative implementations for {@link SessionSerializer} and {@link JavaSessionSerializer}. * The default binding for both types is an implementation that uses out-of-the-box Java serialization (which is neither fast nor efficient). * * <h3>Example usage</h3> * <pre class="java">{@code * import ratpack.guice.Guice; * import ratpack.path.PathTokens; * import ratpack.session.Session; * import ratpack.session.SessionModule; * import ratpack.test.embed.EmbeddedApp; * * import static org.junit.Assert.assertEquals; * * public class Example { * public static void main(String... args) throws Exception { * EmbeddedApp.of(a -> a * .registry(Guice.registry(b -> b * .module(SessionModule.class) * )) * .handlers(c -> c * .get("set/:name/:value", ctx -> * ctx.get(Session.class).getData().then(sessionData -> { * PathTokens pathTokens = ctx.getPathTokens(); * sessionData.set(pathTokens.get("name"), pathTokens.get("value")); * ctx.render("ok"); * }) * ) * .get("get/:name", ctx -> { * ctx.get(Session.class).getData() * .map(d -> d.require(ctx.getPathTokens().get("name"))) * .then(ctx::render); * }) * ) * ).test(httpClient -> { * assertEquals("ok", httpClient.getText("set/foo/bar")); * assertEquals("bar", httpClient.getText("get/foo")); * * assertEquals("ok", httpClient.getText("set/foo/baz")); * assertEquals("baz", httpClient.getText("get/foo")); * }); * } * } * }</pre> */ public class SessionModule extends ConfigurableModule<SessionCookieConfig> { /** * The name of the binding for the {@link Cache} implementation that backs the in memory session store. * * @see #memoryStore(Consumer) */ public static final String LOCAL_MEMORY_SESSION_CACHE_BINDING_NAME = "localMemorySessionCache"; /** * The key of the binding for the {@link Cache} implementation that backs the in memory session store. * * @see #memoryStore(Consumer) */ public static final Key<Cache<AsciiString, ByteBuf>> LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY = Key.get( new TypeLiteral<Cache<AsciiString, ByteBuf>>() {}, Names.named(LOCAL_MEMORY_SESSION_CACHE_BINDING_NAME) ); /** * A builder for an alternative cache for the default in memory store. * <p> * This method is intended to be used with the {@link BindingsSpec#binder(Action)} method. * <pre class="java">{@code * import ratpack.guice.Guice; * import ratpack.session.SessionModule; * * public class Example { * public static void main(String... args) { * Guice.registry(b -> b * .binder(SessionModule.memoryStore(c -> c.maximumSize(100))) * ); * } * } * }</pre> * * @param config the cache configuration * @return an action that binds the cache * @see #memoryStore(Binder, Consumer) */ public static Action<Binder> memoryStore(Consumer<? super CacheBuilder<AsciiString, ByteBuf>> config) { return b -> memoryStore(b, config); } /** * A builder for an alternative cache for the default in memory store. * <p> * This method can be used from within a custom {@link Module}. * <pre class="java">{@code * import com.google.inject.AbstractModule; * import ratpack.session.SessionModule; * * public class CustomSessionModule extends AbstractModule { * protected void configure() { * SessionModule.memoryStore(binder(), c -> c.maximumSize(100)); * } * } * }</pre> * }<p> * This method binds the built cache with the {@link #LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY} key. * It also implicitly registers a {@link RemovalListener}, that releases the byte buffers as they are discarded. * * @param binder the guice binder * @param config the cache configuration */ public static void memoryStore(Binder binder, Consumer<? super CacheBuilder<AsciiString, ByteBuf>> config) { binder.bind(LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY).toProvider(() -> { CacheBuilder<AsciiString, ByteBuf> cacheBuilder = Types.cast(CacheBuilder.newBuilder()); cacheBuilder.removalListener(n -> n.getValue().release()); config.accept(cacheBuilder); return cacheBuilder.build(); }).in(Scopes.SINGLETON); } @Override protected void configure() { memoryStore(binder(), s -> s.maximumSize(1000)); } @Provides @Singleton SessionStore sessionStoreAdapter(@Named(LOCAL_MEMORY_SESSION_CACHE_BINDING_NAME) Cache<AsciiString, ByteBuf> cache) { return new LocalMemorySessionStore(cache); } @Provides @Singleton SessionIdGenerator sessionIdGenerator() { return new DefaultSessionIdGenerator(); } @Provides @RequestScoped SessionId sessionId(Request request, Response response, SessionIdGenerator idGenerator, SessionCookieConfig cookieConfig) { return new CookieBasedSessionId(request, response, idGenerator, cookieConfig); } @Provides SessionSerializer sessionValueSerializer(JavaSessionSerializer sessionSerializer) { return sessionSerializer; } @Provides JavaSessionSerializer javaSessionSerializer() { return new JavaBuiltinSessionSerializer(); } @Provides @RequestScoped Session sessionAdapter(SessionId sessionId, SessionStore store, Response response, ByteBufAllocator bufferAllocator, SessionSerializer defaultSerializer, JavaSessionSerializer javaSerializer) { return new DefaultSession(sessionId, bufferAllocator, store, response, defaultSerializer, javaSerializer); } }
./CrossVul/dataset_final_sorted/CWE-338/java/good_830_0
crossvul-java_data_bad_830_0
/* * Copyright 2015 the original author or authors. * * 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 ratpack.session; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalListener; import com.google.inject.*; import com.google.inject.name.Names; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.util.AsciiString; import ratpack.func.Action; import ratpack.guice.BindingsSpec; import ratpack.guice.ConfigurableModule; import ratpack.guice.RequestScoped; import ratpack.http.Request; import ratpack.http.Response; import ratpack.session.internal.*; import ratpack.util.Types; import javax.inject.Named; import java.io.Serializable; import java.util.function.Consumer; /** * Provides support for HTTP sessions. * <p> * This module provides the general session API (see {@link Session}), and a default {@link SessionStore} implementation that stores session data in local memory. * * <h3>The session store</h3> * <p> * It is expected that most applications will provide alternative bindings for the {@link SessionStore} type, overriding the default. * This allows arbitrary stores to be used to persist session data. * <p> * The default, in memory, implementation stores the data in a {@link Cache}{@code <}{@link AsciiString}, {@link ByteBuf}{@code >}. * This cache instance is provided by this module and defaults to storing a maximum of 1000 entries, discarding least recently used. * The {@link #memoryStore} methods are provided to conveniently construct alternative cache configurations, if necessary. * <h3>Serialization</h3> * <p> * Objects must be serialized to be stored in the session. * The get/set methods {@link SessionData} allow supplying a {@link SessionSerializer} to be used for the specific value. * For variants of the get/set methods where a serializer is not provided, the implementation of {@link SessionSerializer} bound with Guice will be used. * The default implementation provided by this module uses Java's in built serialization mechanism. * Users of this module may choose to override this binding with an alternative serialization strategy. * <p> * However, other Ratpack extensions may require session storage any rely on Java serialization. * For this reason, there is also always a {@link JavaSessionSerializer} implementation available that is guaranteed to be able to serialize any {@link Serializable} * object (that conforms to the {@link Serializable} contract. * Users of this module may also choose to override this binding with another implementation (e.g. one based on <a href="https://github.com/EsotericSoftware/kryo">Kryo</a>), * but this implementation must be able to serialize any object implementing {@link Serializable}. * * It is also often desirable to provide alternative implementations for {@link SessionSerializer} and {@link JavaSessionSerializer}. * The default binding for both types is an implementation that uses out-of-the-box Java serialization (which is neither fast nor efficient). * * <h3>Example usage</h3> * <pre class="java">{@code * import ratpack.guice.Guice; * import ratpack.path.PathTokens; * import ratpack.session.Session; * import ratpack.session.SessionModule; * import ratpack.test.embed.EmbeddedApp; * * import static org.junit.Assert.assertEquals; * * public class Example { * public static void main(String... args) throws Exception { * EmbeddedApp.of(a -> a * .registry(Guice.registry(b -> b * .module(SessionModule.class) * )) * .handlers(c -> c * .get("set/:name/:value", ctx -> * ctx.get(Session.class).getData().then(sessionData -> { * PathTokens pathTokens = ctx.getPathTokens(); * sessionData.set(pathTokens.get("name"), pathTokens.get("value")); * ctx.render("ok"); * }) * ) * .get("get/:name", ctx -> { * ctx.get(Session.class).getData() * .map(d -> d.require(ctx.getPathTokens().get("name"))) * .then(ctx::render); * }) * ) * ).test(httpClient -> { * assertEquals("ok", httpClient.getText("set/foo/bar")); * assertEquals("bar", httpClient.getText("get/foo")); * * assertEquals("ok", httpClient.getText("set/foo/baz")); * assertEquals("baz", httpClient.getText("get/foo")); * }); * } * } * }</pre> */ public class SessionModule extends ConfigurableModule<SessionCookieConfig> { /** * The name of the binding for the {@link Cache} implementation that backs the in memory session store. * * @see #memoryStore(Consumer) */ public static final String LOCAL_MEMORY_SESSION_CACHE_BINDING_NAME = "localMemorySessionCache"; /** * The key of the binding for the {@link Cache} implementation that backs the in memory session store. * * @see #memoryStore(Consumer) */ public static final Key<Cache<AsciiString, ByteBuf>> LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY = Key.get( new TypeLiteral<Cache<AsciiString, ByteBuf>>() {}, Names.named(LOCAL_MEMORY_SESSION_CACHE_BINDING_NAME) ); /** * A builder for an alternative cache for the default in memory store. * <p> * This method is intended to be used with the {@link BindingsSpec#binder(Action)} method. * <pre class="java">{@code * import ratpack.guice.Guice; * import ratpack.session.SessionModule; * * public class Example { * public static void main(String... args) { * Guice.registry(b -> b * .binder(SessionModule.memoryStore(c -> c.maximumSize(100))) * ); * } * } * }</pre> * * @param config the cache configuration * @return an action that binds the cache * @see #memoryStore(Binder, Consumer) */ public static Action<Binder> memoryStore(Consumer<? super CacheBuilder<AsciiString, ByteBuf>> config) { return b -> memoryStore(b, config); } /** * A builder for an alternative cache for the default in memory store. * <p> * This method can be used from within a custom {@link Module}. * <pre class="java">{@code * import com.google.inject.AbstractModule; * import ratpack.session.SessionModule; * * public class CustomSessionModule extends AbstractModule { * protected void configure() { * SessionModule.memoryStore(binder(), c -> c.maximumSize(100)); * } * } * }</pre> * }<p> * This method binds the built cache with the {@link #LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY} key. * It also implicitly registers a {@link RemovalListener}, that releases the byte buffers as they are discarded. * * @param binder the guice binder * @param config the cache configuration */ public static void memoryStore(Binder binder, Consumer<? super CacheBuilder<AsciiString, ByteBuf>> config) { binder.bind(LOCAL_MEMORY_SESSION_CACHE_BINDING_KEY).toProvider(() -> { CacheBuilder<AsciiString, ByteBuf> cacheBuilder = Types.cast(CacheBuilder.newBuilder()); cacheBuilder.removalListener(n -> n.getValue().release()); config.accept(cacheBuilder); return cacheBuilder.build(); }).in(Scopes.SINGLETON); } @Override protected void configure() { memoryStore(binder(), s -> s.maximumSize(1000)); } @Provides @Singleton SessionStore sessionStoreAdapter(@Named(LOCAL_MEMORY_SESSION_CACHE_BINDING_NAME) Cache<AsciiString, ByteBuf> cache) { return new LocalMemorySessionStore(cache); } @Provides SessionIdGenerator sessionIdGenerator() { return new DefaultSessionIdGenerator(); } @Provides @RequestScoped SessionId sessionId(Request request, Response response, SessionIdGenerator idGenerator, SessionCookieConfig cookieConfig) { return new CookieBasedSessionId(request, response, idGenerator, cookieConfig); } @Provides SessionSerializer sessionValueSerializer(JavaSessionSerializer sessionSerializer) { return sessionSerializer; } @Provides JavaSessionSerializer javaSessionSerializer() { return new JavaBuiltinSessionSerializer(); } @Provides @RequestScoped Session sessionAdapter(SessionId sessionId, SessionStore store, Response response, ByteBufAllocator bufferAllocator, SessionSerializer defaultSerializer, JavaSessionSerializer javaSerializer) { return new DefaultSession(sessionId, bufferAllocator, store, response, defaultSerializer, javaSerializer); } }
./CrossVul/dataset_final_sorted/CWE-338/java/bad_830_0
crossvul-java_data_bad_830_1
/* * Copyright 2013 the original author or authors. * * 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 ratpack.session.internal; import io.netty.util.AsciiString; import ratpack.session.SessionIdGenerator; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; public class DefaultSessionIdGenerator implements SessionIdGenerator { public AsciiString generateSessionId() { ThreadLocalRandom random = ThreadLocalRandom.current(); UUID uuid = new UUID(random.nextLong(), random.nextLong()); return AsciiString.of(uuid.toString()); } }
./CrossVul/dataset_final_sorted/CWE-338/java/bad_830_1
crossvul-java_data_bad_1000_1
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.services.managers; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.jboss.logging.Logger; import org.keycloak.authentication.ClientAuthenticator; import org.keycloak.authentication.ClientAuthenticatorFactory; import org.keycloak.common.constants.ServiceAccountConstants; import org.keycloak.common.util.Time; import org.keycloak.models.ClientModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.RealmModel; import org.keycloak.models.UserManager; import org.keycloak.models.UserModel; import org.keycloak.models.UserSessionProvider; import org.keycloak.models.session.UserSessionPersisterProvider; import org.keycloak.models.utils.RepresentationToModel; import org.keycloak.protocol.LoginProtocol; import org.keycloak.protocol.LoginProtocolFactory; import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.protocol.oidc.mappers.UserSessionNoteMapper; import org.keycloak.representations.adapters.config.BaseRealmConfig; import org.keycloak.representations.adapters.config.PolicyEnforcerConfig; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.sessions.AuthenticationSessionProvider; import java.net.URI; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class ClientManager { private static final Logger logger = Logger.getLogger(ClientManager.class); protected RealmManager realmManager; public ClientManager(RealmManager realmManager) { this.realmManager = realmManager; } public ClientManager() { } /** * Should not be called from an import. This really expects that the client is created from the admin console. * * @param session * @param realm * @param rep * @param addDefaultRoles * @return */ public static ClientModel createClient(KeycloakSession session, RealmModel realm, ClientRepresentation rep, boolean addDefaultRoles) { ClientModel client = RepresentationToModel.createClient(session, realm, rep, addDefaultRoles); if (rep.getProtocol() != null) { LoginProtocolFactory providerFactory = (LoginProtocolFactory) session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, rep.getProtocol()); providerFactory.setupClientDefaults(rep, client); } // remove default mappers if there is a template if (rep.getProtocolMappers() == null && rep.getClientTemplate() != null) { Set<ProtocolMapperModel> mappers = client.getProtocolMappers(); for (ProtocolMapperModel mapper : mappers) client.removeProtocolMapper(mapper); } return client; } public boolean removeClient(RealmModel realm, ClientModel client) { if (realm.removeClient(client.getId())) { UserSessionProvider sessions = realmManager.getSession().sessions(); if (sessions != null) { sessions.onClientRemoved(realm, client); } UserSessionPersisterProvider sessionsPersister = realmManager.getSession().getProvider(UserSessionPersisterProvider.class); if (sessionsPersister != null) { sessionsPersister.onClientRemoved(realm, client); } AuthenticationSessionProvider authSessions = realmManager.getSession().authenticationSessions(); if (authSessions != null) { authSessions.onClientRemoved(realm, client); } UserModel serviceAccountUser = realmManager.getSession().users().getServiceAccount(client); if (serviceAccountUser != null) { new UserManager(realmManager.getSession()).removeUser(realm, serviceAccountUser); } return true; } else { return false; } } public Set<String> validateRegisteredNodes(ClientModel client) { Map<String, Integer> registeredNodes = client.getRegisteredNodes(); if (registeredNodes == null || registeredNodes.isEmpty()) { return Collections.emptySet(); } int currentTime = Time.currentTime(); Set<String> validatedNodes = new TreeSet<String>(); if (client.getNodeReRegistrationTimeout() > 0) { List<String> toRemove = new LinkedList<String>(); for (Map.Entry<String, Integer> entry : registeredNodes.entrySet()) { Integer lastReRegistration = entry.getValue(); if (lastReRegistration + client.getNodeReRegistrationTimeout() < currentTime) { toRemove.add(entry.getKey()); } else { validatedNodes.add(entry.getKey()); } } // Remove time-outed nodes for (String node : toRemove) { client.unregisterNode(node); } } else { // Periodic node reRegistration is disabled, so allow all nodes validatedNodes.addAll(registeredNodes.keySet()); } return validatedNodes; } public void enableServiceAccount(ClientModel client) { client.setServiceAccountsEnabled(true); // Add dedicated user for this service account if (realmManager.getSession().users().getServiceAccount(client) == null) { String username = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + client.getClientId(); logger.debugf("Creating service account user '%s'", username); // Don't use federation for service account user UserModel user = realmManager.getSession().userLocalStorage().addUser(client.getRealm(), username); user.setEnabled(true); user.setEmail(username + "@placeholder.org"); user.setServiceAccountClientLink(client.getId()); } // Add protocol mappers to retrieve clientId in access token if (client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER) == null) { logger.debugf("Creating service account protocol mapper '%s' for client '%s'", ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER, client.getClientId()); ProtocolMapperModel protocolMapper = UserSessionNoteMapper.createClaimMapper(ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER, ServiceAccountConstants.CLIENT_ID, ServiceAccountConstants.CLIENT_ID, "String", true, true); client.addProtocolMapper(protocolMapper); } // Add protocol mappers to retrieve hostname and IP address of client in access token if (client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_HOST_PROTOCOL_MAPPER) == null) { logger.debugf("Creating service account protocol mapper '%s' for client '%s'", ServiceAccountConstants.CLIENT_HOST_PROTOCOL_MAPPER, client.getClientId()); ProtocolMapperModel protocolMapper = UserSessionNoteMapper.createClaimMapper(ServiceAccountConstants.CLIENT_HOST_PROTOCOL_MAPPER, ServiceAccountConstants.CLIENT_HOST, ServiceAccountConstants.CLIENT_HOST, "String", true, true); client.addProtocolMapper(protocolMapper); } if (client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_ADDRESS_PROTOCOL_MAPPER) == null) { logger.debugf("Creating service account protocol mapper '%s' for client '%s'", ServiceAccountConstants.CLIENT_ADDRESS_PROTOCOL_MAPPER, client.getClientId()); ProtocolMapperModel protocolMapper = UserSessionNoteMapper.createClaimMapper(ServiceAccountConstants.CLIENT_ADDRESS_PROTOCOL_MAPPER, ServiceAccountConstants.CLIENT_ADDRESS, ServiceAccountConstants.CLIENT_ADDRESS, "String", true, true); client.addProtocolMapper(protocolMapper); } } public void clientIdChanged(ClientModel client, String newClientId) { logger.debugf("Updating clientId from '%s' to '%s'", client.getClientId(), newClientId); UserModel serviceAccountUser = realmManager.getSession().users().getServiceAccount(client); if (serviceAccountUser != null) { String username = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + newClientId; serviceAccountUser.setUsername(username); serviceAccountUser.setEmail(username + "@placeholder.org"); } } @JsonPropertyOrder({"realm", "realm-public-key", "bearer-only", "auth-server-url", "ssl-required", "resource", "public-client", "verify-token-audience", "credentials", "use-resource-role-mappings"}) public static class InstallationAdapterConfig extends BaseRealmConfig { @JsonProperty("resource") protected String resource; @JsonProperty("use-resource-role-mappings") protected Boolean useResourceRoleMappings; @JsonProperty("bearer-only") protected Boolean bearerOnly; @JsonProperty("public-client") protected Boolean publicClient; @JsonProperty("credentials") protected Map<String, Object> credentials; @JsonProperty("verify-token-audience") protected Boolean verifyTokenAudience; @JsonProperty("policy-enforcer") protected PolicyEnforcerConfig enforcerConfig; public Boolean isUseResourceRoleMappings() { return useResourceRoleMappings; } public void setUseResourceRoleMappings(Boolean useResourceRoleMappings) { this.useResourceRoleMappings = useResourceRoleMappings; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } public Map<String, Object> getCredentials() { return credentials; } public void setCredentials(Map<String, Object> credentials) { this.credentials = credentials; } public Boolean getVerifyTokenAudience() { return verifyTokenAudience; } public void setVerifyTokenAudience(Boolean verifyTokenAudience) { this.verifyTokenAudience = verifyTokenAudience; } public Boolean getPublicClient() { return publicClient; } public void setPublicClient(Boolean publicClient) { this.publicClient = publicClient; } public Boolean getBearerOnly() { return bearerOnly; } public void setBearerOnly(Boolean bearerOnly) { this.bearerOnly = bearerOnly; } public PolicyEnforcerConfig getEnforcerConfig() { return this.enforcerConfig; } public void setEnforcerConfig(PolicyEnforcerConfig enforcerConfig) { this.enforcerConfig = enforcerConfig; } } public InstallationAdapterConfig toInstallationRepresentation(RealmModel realmModel, ClientModel clientModel, URI baseUri) { InstallationAdapterConfig rep = new InstallationAdapterConfig(); rep.setAuthServerUrl(baseUri.toString()); rep.setRealm(realmModel.getName()); rep.setSslRequired(realmModel.getSslRequired().name().toLowerCase()); if (clientModel.isPublicClient() && !clientModel.isBearerOnly()) rep.setPublicClient(true); if (clientModel.isBearerOnly()) rep.setBearerOnly(true); if (clientModel.getRoles().size() > 0) rep.setUseResourceRoleMappings(true); rep.setResource(clientModel.getClientId()); if (showClientCredentialsAdapterConfig(clientModel)) { Map<String, Object> adapterConfig = getClientCredentialsAdapterConfig(clientModel); rep.setCredentials(adapterConfig); } return rep; } public String toJBossSubsystemConfig(RealmModel realmModel, ClientModel clientModel, URI baseUri) { StringBuffer buffer = new StringBuffer(); buffer.append("<secure-deployment name=\"WAR MODULE NAME.war\">\n"); buffer.append(" <realm>").append(realmModel.getName()).append("</realm>\n"); buffer.append(" <auth-server-url>").append(baseUri.toString()).append("</auth-server-url>\n"); if (clientModel.isBearerOnly()){ buffer.append(" <bearer-only>true</bearer-only>\n"); } else if (clientModel.isPublicClient()) { buffer.append(" <public-client>true</public-client>\n"); } buffer.append(" <ssl-required>").append(realmModel.getSslRequired().name()).append("</ssl-required>\n"); buffer.append(" <resource>").append(clientModel.getClientId()).append("</resource>\n"); String cred = clientModel.getSecret(); if (showClientCredentialsAdapterConfig(clientModel)) { Map<String, Object> adapterConfig = getClientCredentialsAdapterConfig(clientModel); for (Map.Entry<String, Object> entry : adapterConfig.entrySet()) { buffer.append(" <credential name=\"" + entry.getKey() + "\">"); Object value = entry.getValue(); if (value instanceof Map) { buffer.append("\n"); Map<String, Object> asMap = (Map<String, Object>) value; for (Map.Entry<String, Object> credEntry : asMap.entrySet()) { buffer.append(" <" + credEntry.getKey() + ">" + credEntry.getValue().toString() + "</" + credEntry.getKey() + ">\n"); } buffer.append(" </credential>\n"); } else { buffer.append(value.toString()).append("</credential>\n"); } } } if (clientModel.getRoles().size() > 0) { buffer.append(" <use-resource-role-mappings>true</use-resource-role-mappings>\n"); } buffer.append("</secure-deployment>\n"); return buffer.toString(); } private boolean showClientCredentialsAdapterConfig(ClientModel client) { if (client.isPublicClient()) { return false; } if (client.isBearerOnly() && client.getNodeReRegistrationTimeout() <= 0) { return false; } return true; } private Map<String, Object> getClientCredentialsAdapterConfig(ClientModel client) { String clientAuthenticator = client.getClientAuthenticatorType(); ClientAuthenticatorFactory authenticator = (ClientAuthenticatorFactory) realmManager.getSession().getKeycloakSessionFactory().getProviderFactory(ClientAuthenticator.class, clientAuthenticator); return authenticator.getAdapterConfiguration(client); } }
./CrossVul/dataset_final_sorted/CWE-798/java/bad_1000_1
crossvul-java_data_good_1000_1
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.services.managers; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.jboss.logging.Logger; import org.keycloak.authentication.ClientAuthenticator; import org.keycloak.authentication.ClientAuthenticatorFactory; import org.keycloak.common.constants.ServiceAccountConstants; import org.keycloak.common.util.Time; import org.keycloak.models.ClientModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.RealmModel; import org.keycloak.models.UserManager; import org.keycloak.models.UserModel; import org.keycloak.models.UserSessionProvider; import org.keycloak.models.session.UserSessionPersisterProvider; import org.keycloak.models.utils.RepresentationToModel; import org.keycloak.protocol.LoginProtocol; import org.keycloak.protocol.LoginProtocolFactory; import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.protocol.oidc.mappers.UserSessionNoteMapper; import org.keycloak.representations.adapters.config.BaseRealmConfig; import org.keycloak.representations.adapters.config.PolicyEnforcerConfig; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.sessions.AuthenticationSessionProvider; import java.net.URI; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class ClientManager { private static final Logger logger = Logger.getLogger(ClientManager.class); protected RealmManager realmManager; public ClientManager(RealmManager realmManager) { this.realmManager = realmManager; } public ClientManager() { } /** * Should not be called from an import. This really expects that the client is created from the admin console. * * @param session * @param realm * @param rep * @param addDefaultRoles * @return */ public static ClientModel createClient(KeycloakSession session, RealmModel realm, ClientRepresentation rep, boolean addDefaultRoles) { ClientModel client = RepresentationToModel.createClient(session, realm, rep, addDefaultRoles); if (rep.getProtocol() != null) { LoginProtocolFactory providerFactory = (LoginProtocolFactory) session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, rep.getProtocol()); providerFactory.setupClientDefaults(rep, client); } // remove default mappers if there is a template if (rep.getProtocolMappers() == null && rep.getClientTemplate() != null) { Set<ProtocolMapperModel> mappers = client.getProtocolMappers(); for (ProtocolMapperModel mapper : mappers) client.removeProtocolMapper(mapper); } return client; } public boolean removeClient(RealmModel realm, ClientModel client) { if (realm.removeClient(client.getId())) { UserSessionProvider sessions = realmManager.getSession().sessions(); if (sessions != null) { sessions.onClientRemoved(realm, client); } UserSessionPersisterProvider sessionsPersister = realmManager.getSession().getProvider(UserSessionPersisterProvider.class); if (sessionsPersister != null) { sessionsPersister.onClientRemoved(realm, client); } AuthenticationSessionProvider authSessions = realmManager.getSession().authenticationSessions(); if (authSessions != null) { authSessions.onClientRemoved(realm, client); } UserModel serviceAccountUser = realmManager.getSession().users().getServiceAccount(client); if (serviceAccountUser != null) { new UserManager(realmManager.getSession()).removeUser(realm, serviceAccountUser); } return true; } else { return false; } } public Set<String> validateRegisteredNodes(ClientModel client) { Map<String, Integer> registeredNodes = client.getRegisteredNodes(); if (registeredNodes == null || registeredNodes.isEmpty()) { return Collections.emptySet(); } int currentTime = Time.currentTime(); Set<String> validatedNodes = new TreeSet<String>(); if (client.getNodeReRegistrationTimeout() > 0) { List<String> toRemove = new LinkedList<String>(); for (Map.Entry<String, Integer> entry : registeredNodes.entrySet()) { Integer lastReRegistration = entry.getValue(); if (lastReRegistration + client.getNodeReRegistrationTimeout() < currentTime) { toRemove.add(entry.getKey()); } else { validatedNodes.add(entry.getKey()); } } // Remove time-outed nodes for (String node : toRemove) { client.unregisterNode(node); } } else { // Periodic node reRegistration is disabled, so allow all nodes validatedNodes.addAll(registeredNodes.keySet()); } return validatedNodes; } public void enableServiceAccount(ClientModel client) { client.setServiceAccountsEnabled(true); // Add dedicated user for this service account if (realmManager.getSession().users().getServiceAccount(client) == null) { String username = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + client.getClientId(); logger.debugf("Creating service account user '%s'", username); // Don't use federation for service account user UserModel user = realmManager.getSession().userLocalStorage().addUser(client.getRealm(), username); user.setEnabled(true); user.setServiceAccountClientLink(client.getId()); } // Add protocol mappers to retrieve clientId in access token if (client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER) == null) { logger.debugf("Creating service account protocol mapper '%s' for client '%s'", ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER, client.getClientId()); ProtocolMapperModel protocolMapper = UserSessionNoteMapper.createClaimMapper(ServiceAccountConstants.CLIENT_ID_PROTOCOL_MAPPER, ServiceAccountConstants.CLIENT_ID, ServiceAccountConstants.CLIENT_ID, "String", true, true); client.addProtocolMapper(protocolMapper); } // Add protocol mappers to retrieve hostname and IP address of client in access token if (client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_HOST_PROTOCOL_MAPPER) == null) { logger.debugf("Creating service account protocol mapper '%s' for client '%s'", ServiceAccountConstants.CLIENT_HOST_PROTOCOL_MAPPER, client.getClientId()); ProtocolMapperModel protocolMapper = UserSessionNoteMapper.createClaimMapper(ServiceAccountConstants.CLIENT_HOST_PROTOCOL_MAPPER, ServiceAccountConstants.CLIENT_HOST, ServiceAccountConstants.CLIENT_HOST, "String", true, true); client.addProtocolMapper(protocolMapper); } if (client.getProtocolMapperByName(OIDCLoginProtocol.LOGIN_PROTOCOL, ServiceAccountConstants.CLIENT_ADDRESS_PROTOCOL_MAPPER) == null) { logger.debugf("Creating service account protocol mapper '%s' for client '%s'", ServiceAccountConstants.CLIENT_ADDRESS_PROTOCOL_MAPPER, client.getClientId()); ProtocolMapperModel protocolMapper = UserSessionNoteMapper.createClaimMapper(ServiceAccountConstants.CLIENT_ADDRESS_PROTOCOL_MAPPER, ServiceAccountConstants.CLIENT_ADDRESS, ServiceAccountConstants.CLIENT_ADDRESS, "String", true, true); client.addProtocolMapper(protocolMapper); } } public void clientIdChanged(ClientModel client, String newClientId) { logger.debugf("Updating clientId from '%s' to '%s'", client.getClientId(), newClientId); UserModel serviceAccountUser = realmManager.getSession().users().getServiceAccount(client); if (serviceAccountUser != null) { String username = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + newClientId; serviceAccountUser.setUsername(username); } } @JsonPropertyOrder({"realm", "realm-public-key", "bearer-only", "auth-server-url", "ssl-required", "resource", "public-client", "verify-token-audience", "credentials", "use-resource-role-mappings"}) public static class InstallationAdapterConfig extends BaseRealmConfig { @JsonProperty("resource") protected String resource; @JsonProperty("use-resource-role-mappings") protected Boolean useResourceRoleMappings; @JsonProperty("bearer-only") protected Boolean bearerOnly; @JsonProperty("public-client") protected Boolean publicClient; @JsonProperty("credentials") protected Map<String, Object> credentials; @JsonProperty("verify-token-audience") protected Boolean verifyTokenAudience; @JsonProperty("policy-enforcer") protected PolicyEnforcerConfig enforcerConfig; public Boolean isUseResourceRoleMappings() { return useResourceRoleMappings; } public void setUseResourceRoleMappings(Boolean useResourceRoleMappings) { this.useResourceRoleMappings = useResourceRoleMappings; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } public Map<String, Object> getCredentials() { return credentials; } public void setCredentials(Map<String, Object> credentials) { this.credentials = credentials; } public Boolean getVerifyTokenAudience() { return verifyTokenAudience; } public void setVerifyTokenAudience(Boolean verifyTokenAudience) { this.verifyTokenAudience = verifyTokenAudience; } public Boolean getPublicClient() { return publicClient; } public void setPublicClient(Boolean publicClient) { this.publicClient = publicClient; } public Boolean getBearerOnly() { return bearerOnly; } public void setBearerOnly(Boolean bearerOnly) { this.bearerOnly = bearerOnly; } public PolicyEnforcerConfig getEnforcerConfig() { return this.enforcerConfig; } public void setEnforcerConfig(PolicyEnforcerConfig enforcerConfig) { this.enforcerConfig = enforcerConfig; } } public InstallationAdapterConfig toInstallationRepresentation(RealmModel realmModel, ClientModel clientModel, URI baseUri) { InstallationAdapterConfig rep = new InstallationAdapterConfig(); rep.setAuthServerUrl(baseUri.toString()); rep.setRealm(realmModel.getName()); rep.setSslRequired(realmModel.getSslRequired().name().toLowerCase()); if (clientModel.isPublicClient() && !clientModel.isBearerOnly()) rep.setPublicClient(true); if (clientModel.isBearerOnly()) rep.setBearerOnly(true); if (clientModel.getRoles().size() > 0) rep.setUseResourceRoleMappings(true); rep.setResource(clientModel.getClientId()); if (showClientCredentialsAdapterConfig(clientModel)) { Map<String, Object> adapterConfig = getClientCredentialsAdapterConfig(clientModel); rep.setCredentials(adapterConfig); } return rep; } public String toJBossSubsystemConfig(RealmModel realmModel, ClientModel clientModel, URI baseUri) { StringBuffer buffer = new StringBuffer(); buffer.append("<secure-deployment name=\"WAR MODULE NAME.war\">\n"); buffer.append(" <realm>").append(realmModel.getName()).append("</realm>\n"); buffer.append(" <auth-server-url>").append(baseUri.toString()).append("</auth-server-url>\n"); if (clientModel.isBearerOnly()){ buffer.append(" <bearer-only>true</bearer-only>\n"); } else if (clientModel.isPublicClient()) { buffer.append(" <public-client>true</public-client>\n"); } buffer.append(" <ssl-required>").append(realmModel.getSslRequired().name()).append("</ssl-required>\n"); buffer.append(" <resource>").append(clientModel.getClientId()).append("</resource>\n"); String cred = clientModel.getSecret(); if (showClientCredentialsAdapterConfig(clientModel)) { Map<String, Object> adapterConfig = getClientCredentialsAdapterConfig(clientModel); for (Map.Entry<String, Object> entry : adapterConfig.entrySet()) { buffer.append(" <credential name=\"" + entry.getKey() + "\">"); Object value = entry.getValue(); if (value instanceof Map) { buffer.append("\n"); Map<String, Object> asMap = (Map<String, Object>) value; for (Map.Entry<String, Object> credEntry : asMap.entrySet()) { buffer.append(" <" + credEntry.getKey() + ">" + credEntry.getValue().toString() + "</" + credEntry.getKey() + ">\n"); } buffer.append(" </credential>\n"); } else { buffer.append(value.toString()).append("</credential>\n"); } } } if (clientModel.getRoles().size() > 0) { buffer.append(" <use-resource-role-mappings>true</use-resource-role-mappings>\n"); } buffer.append("</secure-deployment>\n"); return buffer.toString(); } private boolean showClientCredentialsAdapterConfig(ClientModel client) { if (client.isPublicClient()) { return false; } if (client.isBearerOnly() && client.getNodeReRegistrationTimeout() <= 0) { return false; } return true; } private Map<String, Object> getClientCredentialsAdapterConfig(ClientModel client) { String clientAuthenticator = client.getClientAuthenticatorType(); ClientAuthenticatorFactory authenticator = (ClientAuthenticatorFactory) realmManager.getSession().getKeycloakSessionFactory().getProviderFactory(ClientAuthenticator.class, clientAuthenticator); return authenticator.getAdapterConfiguration(client); } }
./CrossVul/dataset_final_sorted/CWE-798/java/good_1000_1
crossvul-java_data_good_4528_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.kernel.security; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.codec.Hex; import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Objects; /** * This implements a zero-configuration version Spring Security's token based remember-me service. While the key can * still be augmented by configuration, it is generally generated based on seldom changing but unique system * properties like hostname, IP address, file system information and Linux kernel. */ public class SystemTokenBasedRememberMeService extends TokenBasedRememberMeServices { private Logger logger = LoggerFactory.getLogger(SystemTokenBasedRememberMeService.class); private String key; @Deprecated public SystemTokenBasedRememberMeService() { super(); setKey(null); } public SystemTokenBasedRememberMeService(String key, UserDetailsService userDetailsService) { super(key, userDetailsService); setKey(key); } /** * Set a new key to be used when generating remember-me tokens. * * Note that the key passed to this method will be augmented by seldom changing but generally unique system * properties like hostname, IP address, file system information and Linux kernel. Hence, even setting no custom * key should be save. */ @Override public void setKey(String key) { // Start with a user key if provided StringBuilder keyBuilder = new StringBuilder(Objects.toString(key, "")); // This will give us the hostname and IP address as something which should be unique per system. // For example: lk.elan-ev.de/10.10.10.31 try { keyBuilder.append(InetAddress.getLocalHost()); } catch (UnknownHostException e) { // silently ignore this } // Gather additional system properties as key // This requires a proc-fs which should generally be available under Linux. // But even without, we have fallbacks above and below. for (String procFile: Arrays.asList("/proc/version", "/proc/partitions")) { try (FileInputStream fileInputStream = new FileInputStream(new File(procFile))) { keyBuilder.append(IOUtils.toString(fileInputStream, StandardCharsets.UTF_8)); } catch (IOException e) { // ignore this } } // If we still have no proper key, just generate a random one. // This will work just fine with the single drawback that restarting Opencast invalidates all remember-me tokens. // But it should be a sufficiently good fallback. key = keyBuilder.toString(); if (key.isEmpty()) { logger.warn("Could not generate semi-persistent remember-me key. Will generate a non-persistent random one."); key = Double.toString(Math.random()); } logger.debug("Remember me key before hashing: {}", key); // Use a SHA-512 hash as key to have a more sane key. try { MessageDigest digest = MessageDigest.getInstance("SHA-512"); key = new String(Hex.encode(digest.digest(key.getBytes()))); } catch (NoSuchAlgorithmException e) { logger.warn("No SHA-512 algorithm available!"); } logger.debug("Calculated remember me key: {}", key); this.key = key; super.setKey(key); } @Override public String getKey() { return this.key; } /** * Calculates the digital signature to be put in the cookie. Default value is * SHA-512 ("username:tokenExpiryTime:password:key") */ @Override protected String makeTokenSignature(long tokenExpiryTime, String username, String password) { String data = username + ":" + tokenExpiryTime + ":" + password + ":" + getKey(); MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-512"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("No SHA-512 algorithm available!"); } return new String(Hex.encode(digest.digest(data.getBytes()))); } }
./CrossVul/dataset_final_sorted/CWE-798/java/good_4528_1
crossvul-java_data_bad_4528_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-798/java/bad_4528_1
crossvul-java_data_good_1000_3
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.testsuite.admin; import org.junit.Test; import org.keycloak.OAuth2Constants; import org.keycloak.admin.client.resource.ClientResource; import org.keycloak.admin.client.resource.ProtocolMappersResource; import org.keycloak.admin.client.resource.RoleMappingResource; import org.keycloak.common.util.Time; import org.keycloak.events.admin.OperationType; import org.keycloak.events.admin.ResourceType; import org.keycloak.models.AccountRoles; import org.keycloak.models.Constants; import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.protocol.oidc.OIDCLoginProtocolFactory; import org.keycloak.representations.adapters.action.GlobalRequestResult; import org.keycloak.representations.adapters.action.PushNotBeforeAction; import org.keycloak.representations.adapters.action.TestAvailabilityAction; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.OAuth2ErrorRepresentation; import org.keycloak.representations.idm.ProtocolMapperRepresentation; import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.representations.idm.UserSessionRepresentation; import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.AdminEventPaths; import org.keycloak.testsuite.util.ClientBuilder; import org.keycloak.testsuite.util.CredentialBuilder; import org.keycloak.testsuite.util.OAuthClient; import org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse; import org.keycloak.testsuite.util.RoleBuilder; import org.keycloak.testsuite.util.UserBuilder; import javax.ws.rs.BadRequestException; import javax.ws.rs.NotFoundException; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.junit.Assert.*; /** * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> */ public class ClientTest extends AbstractAdminTest { @Test public void getClients() { Assert.assertNames(realm.clients().findAll(), "account", "realm-management", "security-admin-console", "broker", Constants.ADMIN_CLI_CLIENT_ID); } private ClientRepresentation createClient() { ClientRepresentation rep = new ClientRepresentation(); rep.setClientId("my-app"); rep.setDescription("my-app description"); rep.setEnabled(true); Response response = realm.clients().create(rep); response.close(); String id = ApiUtil.getCreatedId(response); getCleanup().addClientUuid(id); ClientRepresentation found = ApiUtil.findClientResourceByClientId(realm, "my-app").toRepresentation(); assertEquals("my-app", found.getClientId()); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(id), rep, ResourceType.CLIENT); rep.setId(id); return rep; } @Test public void createClientVerify() { String id = createClient().getId(); assertNotNull(realm.clients().get(id)); Assert.assertNames(realm.clients().findAll(), "account", "realm-management", "security-admin-console", "broker", "my-app", Constants.ADMIN_CLI_CLIENT_ID); } @Test public void removeClient() { String id = createClient().getId(); assertNotNull(ApiUtil.findClientByClientId(realm, "my-app")); realm.clients().get(id).remove(); assertNull(ApiUtil.findClientResourceByClientId(realm, "my-app")); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientResourcePath(id), ResourceType.CLIENT); } @Test public void getClientRepresentation() { String id = createClient().getId(); ClientRepresentation rep = realm.clients().get(id).toRepresentation(); assertEquals(id, rep.getId()); assertEquals("my-app", rep.getClientId()); assertTrue(rep.isEnabled()); } /** * See <a href="https://issues.jboss.org/browse/KEYCLOAK-1918">KEYCLOAK-1918</a> */ @Test public void getClientDescription() { String id = createClient().getId(); ClientRepresentation rep = realm.clients().get(id).toRepresentation(); assertEquals(id, rep.getId()); assertEquals("my-app description", rep.getDescription()); } @Test public void getClientSessions() throws Exception { OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password"); assertEquals(200, response.getStatusCode()); OAuthClient.AuthorizationEndpointResponse codeResponse = oauth.doLogin("test-user@localhost", "password"); OAuthClient.AccessTokenResponse response2 = oauth.doAccessTokenRequest(codeResponse.getCode(), "password"); assertEquals(200, response2.getStatusCode()); ClientResource app = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"); assertEquals(2, (long) app.getApplicationSessionCount().get("count")); List<UserSessionRepresentation> userSessions = app.getUserSessions(0, 100); assertEquals(2, userSessions.size()); assertEquals(1, userSessions.get(0).getClients().size()); } @Test public void getAllClients() { List<ClientRepresentation> allClients = realm.clients().findAll(); assertNotNull(allClients); assertFalse(allClients.isEmpty()); } @Test public void getClientById() { createClient(); ClientRepresentation rep = ApiUtil.findClientResourceByClientId(realm, "my-app").toRepresentation(); ClientRepresentation gotById = realm.clients().get(rep.getId()).toRepresentation(); assertClient(rep, gotById); } @Test // KEYCLOAK-1110 public void deleteDefaultRole() { ClientRepresentation rep = createClient(); String id = rep.getId(); RoleRepresentation role = new RoleRepresentation("test", "test", false); realm.clients().get(id).roles().create(role); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientRoleResourcePath(id, "test"), role, ResourceType.CLIENT_ROLE); ClientRepresentation foundClientRep = realm.clients().get(id).toRepresentation(); foundClientRep.setDefaultRoles(new String[]{"test"}); realm.clients().get(id).update(foundClientRep); assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, AdminEventPaths.clientResourcePath(id), rep, ResourceType.CLIENT); assertArrayEquals(new String[]{"test"}, realm.clients().get(id).toRepresentation().getDefaultRoles()); realm.clients().get(id).roles().deleteRole("test"); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientRoleResourcePath(id, "test"), ResourceType.CLIENT_ROLE); assertNull(realm.clients().get(id).toRepresentation().getDefaultRoles()); } @Test public void testProtocolMappers() { String clientDbId = createClient().getId(); ProtocolMappersResource mappersResource = ApiUtil.findClientByClientId(realm, "my-app").getProtocolMappers(); protocolMappersTest(clientDbId, mappersResource); } @Test public void updateClient() { ClientRepresentation client = createClient(); ClientRepresentation newClient = new ClientRepresentation(); newClient.setId(client.getId()); newClient.setClientId(client.getClientId()); newClient.setBaseUrl("http://baseurl"); realm.clients().get(client.getId()).update(newClient); assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, AdminEventPaths.clientResourcePath(client.getId()), newClient, ResourceType.CLIENT); ClientRepresentation storedClient = realm.clients().get(client.getId()).toRepresentation(); assertClient(client, storedClient); newClient.setSecret("new-secret"); realm.clients().get(client.getId()).update(newClient); assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, AdminEventPaths.clientResourcePath(client.getId()), newClient, ResourceType.CLIENT); storedClient = realm.clients().get(client.getId()).toRepresentation(); assertClient(client, storedClient); } @Test public void serviceAccount() { Response response = realm.clients().create(ClientBuilder.create().clientId("serviceClient").serviceAccount().build()); String id = ApiUtil.getCreatedId(response); getCleanup().addClientUuid(id); response.close(); UserRepresentation userRep = realm.clients().get(id).getServiceAccountUser(); assertEquals("service-account-serviceclient", userRep.getUsername()); // KEYCLOAK-11197 service accounts are no longer created with a placeholder e-mail. assertNull(userRep.getEmail()); } // KEYCLOAK-3421 @Test public void createClientWithFragments() { ClientRepresentation client = ClientBuilder.create() .clientId("client-with-fragment") .rootUrl("http://localhost/base#someFragment") .redirectUris("http://localhost/auth", "http://localhost/auth#fragment", "http://localhost/auth*", "/relative") .build(); Response response = realm.clients().create(client); assertUriFragmentError(response); } // KEYCLOAK-3421 @Test public void updateClientWithFragments() { ClientRepresentation client = ClientBuilder.create() .clientId("client-with-fragment") .redirectUris("http://localhost/auth", "http://localhost/auth*") .build(); Response response = realm.clients().create(client); String clientUuid = ApiUtil.getCreatedId(response); ClientResource clientResource = realm.clients().get(clientUuid); getCleanup().addClientUuid(clientUuid); response.close(); client = clientResource.toRepresentation(); client.setRootUrl("http://localhost/base#someFragment"); List<String> redirectUris = client.getRedirectUris(); redirectUris.add("http://localhost/auth#fragment"); redirectUris.add("/relative"); client.setRedirectUris(redirectUris); try { clientResource.update(client); fail("Should fail"); } catch (BadRequestException e) { assertUriFragmentError(e.getResponse()); } } private void assertUriFragmentError(Response response) { assertEquals(response.getStatus(), 400); String error = response.readEntity(OAuth2ErrorRepresentation.class).getError(); assertTrue("Error response doesn't mention Redirect URIs fragments", error.contains("Redirect URIs must not contain an URI fragment")); assertTrue("Error response doesn't mention Root URL fragments", error.contains("Root URL must not contain an URL fragment")); } @Test public void pushRevocation() { testingClient.testApp().clearAdminActions(); ClientRepresentation client = createAppClient(); String id = client.getId(); realm.clients().get(id).pushRevocation(); PushNotBeforeAction pushNotBefore = testingClient.testApp().getAdminPushNotBefore(); assertEquals(client.getNotBefore().intValue(), pushNotBefore.getNotBefore()); assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.clientPushRevocationPath(id), ResourceType.CLIENT); } private ClientRepresentation createAppClient() { String redirectUri = oauth.getRedirectUri().replace("/master/", "/" + REALM_NAME + "/"); ClientRepresentation client = new ClientRepresentation(); client.setClientId("test-app"); client.setAdminUrl(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/app/admin"); client.setRedirectUris(Collections.singletonList(redirectUri)); client.setSecret("secret"); client.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); int notBefore = Time.currentTime() - 60; client.setNotBefore(notBefore); Response response = realm.clients().create(client); String id = ApiUtil.getCreatedId(response); getCleanup().addClientUuid(id); response.close(); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(id), client, ResourceType.CLIENT); client.setId(id); return client; } @Test public void nodes() { testingClient.testApp().clearAdminActions(); ClientRepresentation client = createAppClient(); String id = client.getId(); String myhost = suiteContext.getAuthServerInfo().getContextRoot().getHost(); realm.clients().get(id).registerNode(Collections.singletonMap("node", myhost)); realm.clients().get(id).registerNode(Collections.singletonMap("node", "invalid")); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientNodePath(id, myhost), ResourceType.CLUSTER_NODE); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientNodePath(id, "invalid"), ResourceType.CLUSTER_NODE); GlobalRequestResult result = realm.clients().get(id).testNodesAvailable(); assertEquals(1, result.getSuccessRequests().size()); assertEquals(1, result.getFailedRequests().size()); assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.clientTestNodesAvailablePath(id), result, ResourceType.CLUSTER_NODE); TestAvailabilityAction testAvailable = testingClient.testApp().getTestAvailable(); assertEquals("test-app", testAvailable.getResource()); assertEquals(2, realm.clients().get(id).toRepresentation().getRegisteredNodes().size()); realm.clients().get(id).unregisterNode("invalid"); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientNodePath(id, "invalid"), ResourceType.CLUSTER_NODE); assertEquals(1, realm.clients().get(id).toRepresentation().getRegisteredNodes().size()); } @Test public void offlineUserSessions() throws IOException { ClientRepresentation client = createAppClient(); String id = client.getId(); Response response = realm.users().create(UserBuilder.create().username("testuser").build()); String userId = ApiUtil.getCreatedId(response); response.close(); realm.users().get(userId).resetPassword(CredentialBuilder.create().password("password").build()); Map<String, Long> offlineSessionCount = realm.clients().get(id).getOfflineSessionCount(); assertEquals(new Long(0), offlineSessionCount.get("count")); List<UserSessionRepresentation> userSessions = realm.users().get(userId).getOfflineSessions(id); assertEquals("There should be no offline sessions", 0, userSessions.size()); oauth.realm(REALM_NAME); oauth.redirectUri(client.getRedirectUris().get(0)); oauth.scope(OAuth2Constants.OFFLINE_ACCESS); oauth.doLogin("testuser", "password"); AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(oauth.getCurrentQuery().get("code"), "secret"); assertEquals(200, accessTokenResponse.getStatusCode()); offlineSessionCount = realm.clients().get(id).getOfflineSessionCount(); assertEquals(new Long(1), offlineSessionCount.get("count")); List<UserSessionRepresentation> offlineUserSessions = realm.clients().get(id).getOfflineUserSessions(0, 100); assertEquals(1, offlineUserSessions.size()); assertEquals("testuser", offlineUserSessions.get(0).getUsername()); userSessions = realm.users().get(userId).getOfflineSessions(id); assertEquals("There should be one offline session", 1, userSessions.size()); assertOfflineSession(offlineUserSessions.get(0), userSessions.get(0)); } private void assertOfflineSession(UserSessionRepresentation expected, UserSessionRepresentation actual) { assertEquals("id", expected.getId(), actual.getId()); assertEquals("userId", expected.getUserId(), actual.getUserId()); assertEquals("userName", expected.getUsername(), actual.getUsername()); assertEquals("clients", expected.getClients(), actual.getClients()); } @Test public void scopes() { Response response = realm.clients().create(ClientBuilder.create().clientId("client").fullScopeEnabled(false).build()); String id = ApiUtil.getCreatedId(response); getCleanup().addClientUuid(id); response.close(); assertAdminEvents.poll(); RoleMappingResource scopesResource = realm.clients().get(id).getScopeMappings(); RoleRepresentation roleRep1 = RoleBuilder.create().name("role1").build(); RoleRepresentation roleRep2 = RoleBuilder.create().name("role2").build(); realm.roles().create(roleRep1); realm.roles().create(roleRep2); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.roleResourcePath("role1"), roleRep1, ResourceType.REALM_ROLE); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.roleResourcePath("role2"), roleRep2, ResourceType.REALM_ROLE); roleRep1 = realm.roles().get("role1").toRepresentation(); roleRep2 = realm.roles().get("role2").toRepresentation(); realm.roles().get("role1").addComposites(Collections.singletonList(roleRep2)); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.roleResourceCompositesPath("role1"), Collections.singletonList(roleRep2), ResourceType.REALM_ROLE); String accountMgmtId = realm.clients().findByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).get(0).getId(); RoleRepresentation viewAccountRoleRep = realm.clients().get(accountMgmtId).roles().get(AccountRoles.VIEW_PROFILE).toRepresentation(); scopesResource.realmLevel().add(Collections.singletonList(roleRep1)); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientScopeMappingsRealmLevelPath(id), Collections.singletonList(roleRep1), ResourceType.REALM_SCOPE_MAPPING); scopesResource.clientLevel(accountMgmtId).add(Collections.singletonList(viewAccountRoleRep)); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientScopeMappingsClientLevelPath(id, accountMgmtId), Collections.singletonList(viewAccountRoleRep), ResourceType.CLIENT_SCOPE_MAPPING); Assert.assertNames(scopesResource.realmLevel().listAll(), "role1"); Assert.assertNames(scopesResource.realmLevel().listEffective(), "role1", "role2"); Assert.assertNames(scopesResource.realmLevel().listAvailable(), "offline_access", Constants.AUTHZ_UMA_AUTHORIZATION); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAll(), AccountRoles.VIEW_PROFILE); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listEffective(), AccountRoles.VIEW_PROFILE); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS); Assert.assertNames(scopesResource.getAll().getRealmMappings(), "role1"); Assert.assertNames(scopesResource.getAll().getClientMappings().get(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getMappings(), AccountRoles.VIEW_PROFILE); scopesResource.realmLevel().remove(Collections.singletonList(roleRep1)); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientScopeMappingsRealmLevelPath(id), Collections.singletonList(roleRep1), ResourceType.REALM_SCOPE_MAPPING); scopesResource.clientLevel(accountMgmtId).remove(Collections.singletonList(viewAccountRoleRep)); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientScopeMappingsClientLevelPath(id, accountMgmtId), Collections.singletonList(viewAccountRoleRep), ResourceType.CLIENT_SCOPE_MAPPING); Assert.assertNames(scopesResource.realmLevel().listAll()); Assert.assertNames(scopesResource.realmLevel().listEffective()); Assert.assertNames(scopesResource.realmLevel().listAvailable(), "offline_access", Constants.AUTHZ_UMA_AUTHORIZATION, "role1", "role2"); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAll()); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.VIEW_PROFILE, AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listEffective()); } public void protocolMappersTest(String clientDbId, ProtocolMappersResource mappersResource) { // assert default mappers found List<ProtocolMapperRepresentation> protocolMappers = mappersResource.getMappers(); String emailMapperId = null; String usernameMapperId = null; String fooMapperId = null; for (ProtocolMapperRepresentation mapper : protocolMappers) { if (mapper.getName().equals(OIDCLoginProtocolFactory.EMAIL)) { emailMapperId = mapper.getId(); } else if (mapper.getName().equals(OIDCLoginProtocolFactory.USERNAME)) { usernameMapperId = mapper.getId(); } else if (mapper.getName().equals("foo")) { fooMapperId = mapper.getId(); } } // Builtin mappers are not here assertNull(emailMapperId); assertNull(usernameMapperId); assertNull(fooMapperId); // Create foo mapper ProtocolMapperRepresentation fooMapper = new ProtocolMapperRepresentation(); fooMapper.setName("foo"); fooMapper.setProtocol("openid-connect"); fooMapper.setProtocolMapper("oidc-hardcoded-claim-mapper"); Response response = mappersResource.createMapper(fooMapper); String location = response.getLocation().toString(); fooMapperId = location.substring(location.lastIndexOf("/") + 1); response.close(); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientProtocolMapperPath(clientDbId, fooMapperId), fooMapper, ResourceType.PROTOCOL_MAPPER); fooMapper = mappersResource.getMapperById(fooMapperId); assertEquals(fooMapper.getName(), "foo"); // Update foo mapper mappersResource.update(fooMapperId, fooMapper); assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, AdminEventPaths.clientProtocolMapperPath(clientDbId, fooMapperId), fooMapper, ResourceType.PROTOCOL_MAPPER); fooMapper = mappersResource.getMapperById(fooMapperId); // Remove foo mapper mappersResource.delete(fooMapperId); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientProtocolMapperPath(clientDbId, fooMapperId), ResourceType.PROTOCOL_MAPPER); try { mappersResource.getMapperById(fooMapperId); fail("Not expected to find deleted mapper"); } catch (NotFoundException nfe) { } } public static void assertClient(ClientRepresentation client, ClientRepresentation storedClient) { if (client.getClientId() != null) Assert.assertEquals(client.getClientId(), storedClient.getClientId()); if (client.getName() != null) Assert.assertEquals(client.getName(), storedClient.getName()); if (client.isEnabled() != null) Assert.assertEquals(client.isEnabled(), storedClient.isEnabled()); if (client.isBearerOnly() != null) Assert.assertEquals(client.isBearerOnly(), storedClient.isBearerOnly()); if (client.isPublicClient() != null) Assert.assertEquals(client.isPublicClient(), storedClient.isPublicClient()); if (client.isFullScopeAllowed() != null) Assert.assertEquals(client.isFullScopeAllowed(), storedClient.isFullScopeAllowed()); if (client.getRootUrl() != null) Assert.assertEquals(client.getRootUrl(), storedClient.getRootUrl()); if (client.getAdminUrl() != null) Assert.assertEquals(client.getAdminUrl(), storedClient.getAdminUrl()); if (client.getBaseUrl() != null) Assert.assertEquals(client.getBaseUrl(), storedClient.getBaseUrl()); if (client.isSurrogateAuthRequired() != null) Assert.assertEquals(client.isSurrogateAuthRequired(), storedClient.isSurrogateAuthRequired()); if (client.getClientAuthenticatorType() != null) Assert.assertEquals(client.getClientAuthenticatorType(), storedClient.getClientAuthenticatorType()); if (client.getNotBefore() != null) { Assert.assertEquals(client.getNotBefore(), storedClient.getNotBefore()); } if (client.getDefaultRoles() != null) { Set<String> set = new HashSet<String>(); for (String val : client.getDefaultRoles()) { set.add(val); } Set<String> storedSet = new HashSet<String>(); for (String val : storedClient.getDefaultRoles()) { storedSet.add(val); } Assert.assertEquals(set, storedSet); } List<String> redirectUris = client.getRedirectUris(); if (redirectUris != null) { Set<String> set = new HashSet<String>(); for (String val : client.getRedirectUris()) { set.add(val); } Set<String> storedSet = new HashSet<String>(); for (String val : storedClient.getRedirectUris()) { storedSet.add(val); } Assert.assertEquals(set, storedSet); } List<String> webOrigins = client.getWebOrigins(); if (webOrigins != null) { Set<String> set = new HashSet<String>(); for (String val : client.getWebOrigins()) { set.add(val); } Set<String> storedSet = new HashSet<String>(); for (String val : storedClient.getWebOrigins()) { storedSet.add(val); } Assert.assertEquals(set, storedSet); } } }
./CrossVul/dataset_final_sorted/CWE-798/java/good_1000_3
crossvul-java_data_bad_1000_3
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.testsuite.admin; import org.junit.Test; import org.keycloak.OAuth2Constants; import org.keycloak.admin.client.resource.ClientResource; import org.keycloak.admin.client.resource.ProtocolMappersResource; import org.keycloak.admin.client.resource.RoleMappingResource; import org.keycloak.common.util.Time; import org.keycloak.events.admin.OperationType; import org.keycloak.events.admin.ResourceType; import org.keycloak.models.AccountRoles; import org.keycloak.models.Constants; import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.protocol.oidc.OIDCLoginProtocolFactory; import org.keycloak.representations.adapters.action.GlobalRequestResult; import org.keycloak.representations.adapters.action.PushNotBeforeAction; import org.keycloak.representations.adapters.action.TestAvailabilityAction; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.OAuth2ErrorRepresentation; import org.keycloak.representations.idm.ProtocolMapperRepresentation; import org.keycloak.representations.idm.RoleRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.representations.idm.UserSessionRepresentation; import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.util.AdminEventPaths; import org.keycloak.testsuite.util.ClientBuilder; import org.keycloak.testsuite.util.CredentialBuilder; import org.keycloak.testsuite.util.OAuthClient; import org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse; import org.keycloak.testsuite.util.RoleBuilder; import org.keycloak.testsuite.util.UserBuilder; import javax.ws.rs.BadRequestException; import javax.ws.rs.NotFoundException; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.junit.Assert.*; /** * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a> */ public class ClientTest extends AbstractAdminTest { @Test public void getClients() { Assert.assertNames(realm.clients().findAll(), "account", "realm-management", "security-admin-console", "broker", Constants.ADMIN_CLI_CLIENT_ID); } private ClientRepresentation createClient() { ClientRepresentation rep = new ClientRepresentation(); rep.setClientId("my-app"); rep.setDescription("my-app description"); rep.setEnabled(true); Response response = realm.clients().create(rep); response.close(); String id = ApiUtil.getCreatedId(response); getCleanup().addClientUuid(id); ClientRepresentation found = ApiUtil.findClientResourceByClientId(realm, "my-app").toRepresentation(); assertEquals("my-app", found.getClientId()); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(id), rep, ResourceType.CLIENT); rep.setId(id); return rep; } @Test public void createClientVerify() { String id = createClient().getId(); assertNotNull(realm.clients().get(id)); Assert.assertNames(realm.clients().findAll(), "account", "realm-management", "security-admin-console", "broker", "my-app", Constants.ADMIN_CLI_CLIENT_ID); } @Test public void removeClient() { String id = createClient().getId(); assertNotNull(ApiUtil.findClientByClientId(realm, "my-app")); realm.clients().get(id).remove(); assertNull(ApiUtil.findClientResourceByClientId(realm, "my-app")); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientResourcePath(id), ResourceType.CLIENT); } @Test public void getClientRepresentation() { String id = createClient().getId(); ClientRepresentation rep = realm.clients().get(id).toRepresentation(); assertEquals(id, rep.getId()); assertEquals("my-app", rep.getClientId()); assertTrue(rep.isEnabled()); } /** * See <a href="https://issues.jboss.org/browse/KEYCLOAK-1918">KEYCLOAK-1918</a> */ @Test public void getClientDescription() { String id = createClient().getId(); ClientRepresentation rep = realm.clients().get(id).toRepresentation(); assertEquals(id, rep.getId()); assertEquals("my-app description", rep.getDescription()); } @Test public void getClientSessions() throws Exception { OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password"); assertEquals(200, response.getStatusCode()); OAuthClient.AuthorizationEndpointResponse codeResponse = oauth.doLogin("test-user@localhost", "password"); OAuthClient.AccessTokenResponse response2 = oauth.doAccessTokenRequest(codeResponse.getCode(), "password"); assertEquals(200, response2.getStatusCode()); ClientResource app = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"); assertEquals(2, (long) app.getApplicationSessionCount().get("count")); List<UserSessionRepresentation> userSessions = app.getUserSessions(0, 100); assertEquals(2, userSessions.size()); assertEquals(1, userSessions.get(0).getClients().size()); } @Test public void getAllClients() { List<ClientRepresentation> allClients = realm.clients().findAll(); assertNotNull(allClients); assertFalse(allClients.isEmpty()); } @Test public void getClientById() { createClient(); ClientRepresentation rep = ApiUtil.findClientResourceByClientId(realm, "my-app").toRepresentation(); ClientRepresentation gotById = realm.clients().get(rep.getId()).toRepresentation(); assertClient(rep, gotById); } @Test // KEYCLOAK-1110 public void deleteDefaultRole() { ClientRepresentation rep = createClient(); String id = rep.getId(); RoleRepresentation role = new RoleRepresentation("test", "test", false); realm.clients().get(id).roles().create(role); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientRoleResourcePath(id, "test"), role, ResourceType.CLIENT_ROLE); ClientRepresentation foundClientRep = realm.clients().get(id).toRepresentation(); foundClientRep.setDefaultRoles(new String[]{"test"}); realm.clients().get(id).update(foundClientRep); assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, AdminEventPaths.clientResourcePath(id), rep, ResourceType.CLIENT); assertArrayEquals(new String[]{"test"}, realm.clients().get(id).toRepresentation().getDefaultRoles()); realm.clients().get(id).roles().deleteRole("test"); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientRoleResourcePath(id, "test"), ResourceType.CLIENT_ROLE); assertNull(realm.clients().get(id).toRepresentation().getDefaultRoles()); } @Test public void testProtocolMappers() { String clientDbId = createClient().getId(); ProtocolMappersResource mappersResource = ApiUtil.findClientByClientId(realm, "my-app").getProtocolMappers(); protocolMappersTest(clientDbId, mappersResource); } @Test public void updateClient() { ClientRepresentation client = createClient(); ClientRepresentation newClient = new ClientRepresentation(); newClient.setId(client.getId()); newClient.setClientId(client.getClientId()); newClient.setBaseUrl("http://baseurl"); realm.clients().get(client.getId()).update(newClient); assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, AdminEventPaths.clientResourcePath(client.getId()), newClient, ResourceType.CLIENT); ClientRepresentation storedClient = realm.clients().get(client.getId()).toRepresentation(); assertClient(client, storedClient); newClient.setSecret("new-secret"); realm.clients().get(client.getId()).update(newClient); assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, AdminEventPaths.clientResourcePath(client.getId()), newClient, ResourceType.CLIENT); storedClient = realm.clients().get(client.getId()).toRepresentation(); assertClient(client, storedClient); } @Test public void serviceAccount() { Response response = realm.clients().create(ClientBuilder.create().clientId("serviceClient").serviceAccount().build()); String id = ApiUtil.getCreatedId(response); getCleanup().addClientUuid(id); response.close(); UserRepresentation userRep = realm.clients().get(id).getServiceAccountUser(); assertEquals("service-account-serviceclient", userRep.getUsername()); } // KEYCLOAK-3421 @Test public void createClientWithFragments() { ClientRepresentation client = ClientBuilder.create() .clientId("client-with-fragment") .rootUrl("http://localhost/base#someFragment") .redirectUris("http://localhost/auth", "http://localhost/auth#fragment", "http://localhost/auth*", "/relative") .build(); Response response = realm.clients().create(client); assertUriFragmentError(response); } // KEYCLOAK-3421 @Test public void updateClientWithFragments() { ClientRepresentation client = ClientBuilder.create() .clientId("client-with-fragment") .redirectUris("http://localhost/auth", "http://localhost/auth*") .build(); Response response = realm.clients().create(client); String clientUuid = ApiUtil.getCreatedId(response); ClientResource clientResource = realm.clients().get(clientUuid); getCleanup().addClientUuid(clientUuid); response.close(); client = clientResource.toRepresentation(); client.setRootUrl("http://localhost/base#someFragment"); List<String> redirectUris = client.getRedirectUris(); redirectUris.add("http://localhost/auth#fragment"); redirectUris.add("/relative"); client.setRedirectUris(redirectUris); try { clientResource.update(client); fail("Should fail"); } catch (BadRequestException e) { assertUriFragmentError(e.getResponse()); } } private void assertUriFragmentError(Response response) { assertEquals(response.getStatus(), 400); String error = response.readEntity(OAuth2ErrorRepresentation.class).getError(); assertTrue("Error response doesn't mention Redirect URIs fragments", error.contains("Redirect URIs must not contain an URI fragment")); assertTrue("Error response doesn't mention Root URL fragments", error.contains("Root URL must not contain an URL fragment")); } @Test public void pushRevocation() { testingClient.testApp().clearAdminActions(); ClientRepresentation client = createAppClient(); String id = client.getId(); realm.clients().get(id).pushRevocation(); PushNotBeforeAction pushNotBefore = testingClient.testApp().getAdminPushNotBefore(); assertEquals(client.getNotBefore().intValue(), pushNotBefore.getNotBefore()); assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.clientPushRevocationPath(id), ResourceType.CLIENT); } private ClientRepresentation createAppClient() { String redirectUri = oauth.getRedirectUri().replace("/master/", "/" + REALM_NAME + "/"); ClientRepresentation client = new ClientRepresentation(); client.setClientId("test-app"); client.setAdminUrl(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/app/admin"); client.setRedirectUris(Collections.singletonList(redirectUri)); client.setSecret("secret"); client.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); int notBefore = Time.currentTime() - 60; client.setNotBefore(notBefore); Response response = realm.clients().create(client); String id = ApiUtil.getCreatedId(response); getCleanup().addClientUuid(id); response.close(); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(id), client, ResourceType.CLIENT); client.setId(id); return client; } @Test public void nodes() { testingClient.testApp().clearAdminActions(); ClientRepresentation client = createAppClient(); String id = client.getId(); String myhost = suiteContext.getAuthServerInfo().getContextRoot().getHost(); realm.clients().get(id).registerNode(Collections.singletonMap("node", myhost)); realm.clients().get(id).registerNode(Collections.singletonMap("node", "invalid")); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientNodePath(id, myhost), ResourceType.CLUSTER_NODE); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientNodePath(id, "invalid"), ResourceType.CLUSTER_NODE); GlobalRequestResult result = realm.clients().get(id).testNodesAvailable(); assertEquals(1, result.getSuccessRequests().size()); assertEquals(1, result.getFailedRequests().size()); assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.clientTestNodesAvailablePath(id), result, ResourceType.CLUSTER_NODE); TestAvailabilityAction testAvailable = testingClient.testApp().getTestAvailable(); assertEquals("test-app", testAvailable.getResource()); assertEquals(2, realm.clients().get(id).toRepresentation().getRegisteredNodes().size()); realm.clients().get(id).unregisterNode("invalid"); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientNodePath(id, "invalid"), ResourceType.CLUSTER_NODE); assertEquals(1, realm.clients().get(id).toRepresentation().getRegisteredNodes().size()); } @Test public void offlineUserSessions() throws IOException { ClientRepresentation client = createAppClient(); String id = client.getId(); Response response = realm.users().create(UserBuilder.create().username("testuser").build()); String userId = ApiUtil.getCreatedId(response); response.close(); realm.users().get(userId).resetPassword(CredentialBuilder.create().password("password").build()); Map<String, Long> offlineSessionCount = realm.clients().get(id).getOfflineSessionCount(); assertEquals(new Long(0), offlineSessionCount.get("count")); List<UserSessionRepresentation> userSessions = realm.users().get(userId).getOfflineSessions(id); assertEquals("There should be no offline sessions", 0, userSessions.size()); oauth.realm(REALM_NAME); oauth.redirectUri(client.getRedirectUris().get(0)); oauth.scope(OAuth2Constants.OFFLINE_ACCESS); oauth.doLogin("testuser", "password"); AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(oauth.getCurrentQuery().get("code"), "secret"); assertEquals(200, accessTokenResponse.getStatusCode()); offlineSessionCount = realm.clients().get(id).getOfflineSessionCount(); assertEquals(new Long(1), offlineSessionCount.get("count")); List<UserSessionRepresentation> offlineUserSessions = realm.clients().get(id).getOfflineUserSessions(0, 100); assertEquals(1, offlineUserSessions.size()); assertEquals("testuser", offlineUserSessions.get(0).getUsername()); userSessions = realm.users().get(userId).getOfflineSessions(id); assertEquals("There should be one offline session", 1, userSessions.size()); assertOfflineSession(offlineUserSessions.get(0), userSessions.get(0)); } private void assertOfflineSession(UserSessionRepresentation expected, UserSessionRepresentation actual) { assertEquals("id", expected.getId(), actual.getId()); assertEquals("userId", expected.getUserId(), actual.getUserId()); assertEquals("userName", expected.getUsername(), actual.getUsername()); assertEquals("clients", expected.getClients(), actual.getClients()); } @Test public void scopes() { Response response = realm.clients().create(ClientBuilder.create().clientId("client").fullScopeEnabled(false).build()); String id = ApiUtil.getCreatedId(response); getCleanup().addClientUuid(id); response.close(); assertAdminEvents.poll(); RoleMappingResource scopesResource = realm.clients().get(id).getScopeMappings(); RoleRepresentation roleRep1 = RoleBuilder.create().name("role1").build(); RoleRepresentation roleRep2 = RoleBuilder.create().name("role2").build(); realm.roles().create(roleRep1); realm.roles().create(roleRep2); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.roleResourcePath("role1"), roleRep1, ResourceType.REALM_ROLE); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.roleResourcePath("role2"), roleRep2, ResourceType.REALM_ROLE); roleRep1 = realm.roles().get("role1").toRepresentation(); roleRep2 = realm.roles().get("role2").toRepresentation(); realm.roles().get("role1").addComposites(Collections.singletonList(roleRep2)); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.roleResourceCompositesPath("role1"), Collections.singletonList(roleRep2), ResourceType.REALM_ROLE); String accountMgmtId = realm.clients().findByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).get(0).getId(); RoleRepresentation viewAccountRoleRep = realm.clients().get(accountMgmtId).roles().get(AccountRoles.VIEW_PROFILE).toRepresentation(); scopesResource.realmLevel().add(Collections.singletonList(roleRep1)); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientScopeMappingsRealmLevelPath(id), Collections.singletonList(roleRep1), ResourceType.REALM_SCOPE_MAPPING); scopesResource.clientLevel(accountMgmtId).add(Collections.singletonList(viewAccountRoleRep)); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientScopeMappingsClientLevelPath(id, accountMgmtId), Collections.singletonList(viewAccountRoleRep), ResourceType.CLIENT_SCOPE_MAPPING); Assert.assertNames(scopesResource.realmLevel().listAll(), "role1"); Assert.assertNames(scopesResource.realmLevel().listEffective(), "role1", "role2"); Assert.assertNames(scopesResource.realmLevel().listAvailable(), "offline_access", Constants.AUTHZ_UMA_AUTHORIZATION); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAll(), AccountRoles.VIEW_PROFILE); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listEffective(), AccountRoles.VIEW_PROFILE); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS); Assert.assertNames(scopesResource.getAll().getRealmMappings(), "role1"); Assert.assertNames(scopesResource.getAll().getClientMappings().get(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getMappings(), AccountRoles.VIEW_PROFILE); scopesResource.realmLevel().remove(Collections.singletonList(roleRep1)); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientScopeMappingsRealmLevelPath(id), Collections.singletonList(roleRep1), ResourceType.REALM_SCOPE_MAPPING); scopesResource.clientLevel(accountMgmtId).remove(Collections.singletonList(viewAccountRoleRep)); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientScopeMappingsClientLevelPath(id, accountMgmtId), Collections.singletonList(viewAccountRoleRep), ResourceType.CLIENT_SCOPE_MAPPING); Assert.assertNames(scopesResource.realmLevel().listAll()); Assert.assertNames(scopesResource.realmLevel().listEffective()); Assert.assertNames(scopesResource.realmLevel().listAvailable(), "offline_access", Constants.AUTHZ_UMA_AUTHORIZATION, "role1", "role2"); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAll()); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listAvailable(), AccountRoles.VIEW_PROFILE, AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS); Assert.assertNames(scopesResource.clientLevel(accountMgmtId).listEffective()); } public void protocolMappersTest(String clientDbId, ProtocolMappersResource mappersResource) { // assert default mappers found List<ProtocolMapperRepresentation> protocolMappers = mappersResource.getMappers(); String emailMapperId = null; String usernameMapperId = null; String fooMapperId = null; for (ProtocolMapperRepresentation mapper : protocolMappers) { if (mapper.getName().equals(OIDCLoginProtocolFactory.EMAIL)) { emailMapperId = mapper.getId(); } else if (mapper.getName().equals(OIDCLoginProtocolFactory.USERNAME)) { usernameMapperId = mapper.getId(); } else if (mapper.getName().equals("foo")) { fooMapperId = mapper.getId(); } } // Builtin mappers are not here assertNull(emailMapperId); assertNull(usernameMapperId); assertNull(fooMapperId); // Create foo mapper ProtocolMapperRepresentation fooMapper = new ProtocolMapperRepresentation(); fooMapper.setName("foo"); fooMapper.setProtocol("openid-connect"); fooMapper.setProtocolMapper("oidc-hardcoded-claim-mapper"); Response response = mappersResource.createMapper(fooMapper); String location = response.getLocation().toString(); fooMapperId = location.substring(location.lastIndexOf("/") + 1); response.close(); assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientProtocolMapperPath(clientDbId, fooMapperId), fooMapper, ResourceType.PROTOCOL_MAPPER); fooMapper = mappersResource.getMapperById(fooMapperId); assertEquals(fooMapper.getName(), "foo"); // Update foo mapper mappersResource.update(fooMapperId, fooMapper); assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, AdminEventPaths.clientProtocolMapperPath(clientDbId, fooMapperId), fooMapper, ResourceType.PROTOCOL_MAPPER); fooMapper = mappersResource.getMapperById(fooMapperId); // Remove foo mapper mappersResource.delete(fooMapperId); assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientProtocolMapperPath(clientDbId, fooMapperId), ResourceType.PROTOCOL_MAPPER); try { mappersResource.getMapperById(fooMapperId); fail("Not expected to find deleted mapper"); } catch (NotFoundException nfe) { } } public static void assertClient(ClientRepresentation client, ClientRepresentation storedClient) { if (client.getClientId() != null) Assert.assertEquals(client.getClientId(), storedClient.getClientId()); if (client.getName() != null) Assert.assertEquals(client.getName(), storedClient.getName()); if (client.isEnabled() != null) Assert.assertEquals(client.isEnabled(), storedClient.isEnabled()); if (client.isBearerOnly() != null) Assert.assertEquals(client.isBearerOnly(), storedClient.isBearerOnly()); if (client.isPublicClient() != null) Assert.assertEquals(client.isPublicClient(), storedClient.isPublicClient()); if (client.isFullScopeAllowed() != null) Assert.assertEquals(client.isFullScopeAllowed(), storedClient.isFullScopeAllowed()); if (client.getRootUrl() != null) Assert.assertEquals(client.getRootUrl(), storedClient.getRootUrl()); if (client.getAdminUrl() != null) Assert.assertEquals(client.getAdminUrl(), storedClient.getAdminUrl()); if (client.getBaseUrl() != null) Assert.assertEquals(client.getBaseUrl(), storedClient.getBaseUrl()); if (client.isSurrogateAuthRequired() != null) Assert.assertEquals(client.isSurrogateAuthRequired(), storedClient.isSurrogateAuthRequired()); if (client.getClientAuthenticatorType() != null) Assert.assertEquals(client.getClientAuthenticatorType(), storedClient.getClientAuthenticatorType()); if (client.getNotBefore() != null) { Assert.assertEquals(client.getNotBefore(), storedClient.getNotBefore()); } if (client.getDefaultRoles() != null) { Set<String> set = new HashSet<String>(); for (String val : client.getDefaultRoles()) { set.add(val); } Set<String> storedSet = new HashSet<String>(); for (String val : storedClient.getDefaultRoles()) { storedSet.add(val); } Assert.assertEquals(set, storedSet); } List<String> redirectUris = client.getRedirectUris(); if (redirectUris != null) { Set<String> set = new HashSet<String>(); for (String val : client.getRedirectUris()) { set.add(val); } Set<String> storedSet = new HashSet<String>(); for (String val : storedClient.getRedirectUris()) { storedSet.add(val); } Assert.assertEquals(set, storedSet); } List<String> webOrigins = client.getWebOrigins(); if (webOrigins != null) { Set<String> set = new HashSet<String>(); for (String val : client.getWebOrigins()) { set.add(val); } Set<String> storedSet = new HashSet<String>(); for (String val : storedClient.getWebOrigins()) { storedSet.add(val); } Assert.assertEquals(set, storedSet); } } }
./CrossVul/dataset_final_sorted/CWE-798/java/bad_1000_3
crossvul-java_data_good_4128_3
package com.ctrip.framework.apollo.adminservice.filter; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.ctrip.framework.apollo.biz.config.BizConfig; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.http.HttpHeaders; @RunWith(MockitoJUnitRunner.class) public class AdminServiceAuthenticationFilterTest { @Mock private BizConfig bizConfig; private HttpServletRequest servletRequest; private HttpServletResponse servletResponse; private FilterChain filterChain; private AdminServiceAuthenticationFilter authenticationFilter; @Before public void setUp() throws Exception { authenticationFilter = new AdminServiceAuthenticationFilter(bizConfig); initVariables(); } private void initVariables() { servletRequest = mock(HttpServletRequest.class); servletResponse = mock(HttpServletResponse.class); filterChain = mock(FilterChain.class); } @Test public void testWithAccessControlDisabled() throws Exception { when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(false); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(bizConfig, times(1)).isAdminServiceAccessControlEnabled(); verify(filterChain, times(1)).doFilter(servletRequest, servletResponse); verify(bizConfig, never()).getAdminServiceAccessTokens(); verify(servletRequest, never()).getHeader(HttpHeaders.AUTHORIZATION); verify(servletResponse, never()).sendError(anyInt(), anyString()); } @Test public void testWithAccessControlEnabledWithTokenSpecifiedWithValidTokenPassed() throws Exception { String someValidToken = "someToken"; when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(true); when(bizConfig.getAdminServiceAccessTokens()).thenReturn(someValidToken); when(servletRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someValidToken); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(bizConfig, times(1)).isAdminServiceAccessControlEnabled(); verify(bizConfig, times(1)).getAdminServiceAccessTokens(); verify(filterChain, times(1)).doFilter(servletRequest, servletResponse); verify(servletResponse, never()).sendError(anyInt(), anyString()); } @Test public void testWithAccessControlEnabledWithTokenSpecifiedWithInvalidTokenPassed() throws Exception { String someValidToken = "someValidToken"; String someInvalidToken = "someInvalidToken"; when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(true); when(bizConfig.getAdminServiceAccessTokens()).thenReturn(someValidToken); when(servletRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someInvalidToken); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(bizConfig, times(1)).isAdminServiceAccessControlEnabled(); verify(bizConfig, times(1)).getAdminServiceAccessTokens(); verify(servletResponse, times(1)) .sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); verify(filterChain, never()).doFilter(servletRequest, servletResponse); } @Test public void testWithAccessControlEnabledWithTokenSpecifiedWithNoTokenPassed() throws Exception { String someValidToken = "someValidToken"; when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(true); when(bizConfig.getAdminServiceAccessTokens()).thenReturn(someValidToken); when(servletRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(null); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(bizConfig, times(1)).isAdminServiceAccessControlEnabled(); verify(bizConfig, times(1)).getAdminServiceAccessTokens(); verify(servletResponse, times(1)) .sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); verify(filterChain, never()).doFilter(servletRequest, servletResponse); } @Test public void testWithAccessControlEnabledWithMultipleTokenSpecifiedWithValidTokenPassed() throws Exception { String someToken = "someToken"; String anotherToken = "anotherToken"; when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(true); when(bizConfig.getAdminServiceAccessTokens()) .thenReturn(String.format("%s,%s", someToken, anotherToken)); when(servletRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someToken); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(bizConfig, times(1)).isAdminServiceAccessControlEnabled(); verify(bizConfig, times(1)).getAdminServiceAccessTokens(); verify(filterChain, times(1)).doFilter(servletRequest, servletResponse); verify(servletResponse, never()).sendError(anyInt(), anyString()); } @Test public void testWithAccessControlEnabledWithNoTokenSpecifiedWithTokenPassed() throws Exception { String someToken = "someToken"; when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(true); when(bizConfig.getAdminServiceAccessTokens()).thenReturn(null); when(servletRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someToken); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(bizConfig, times(1)).isAdminServiceAccessControlEnabled(); verify(bizConfig, times(1)).getAdminServiceAccessTokens(); verify(filterChain, times(1)).doFilter(servletRequest, servletResponse); verify(servletResponse, never()).sendError(anyInt(), anyString()); } @Test public void testWithAccessControlEnabledWithNoTokenSpecifiedWithNoTokenPassed() throws Exception { String someToken = "someToken"; when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(true); when(bizConfig.getAdminServiceAccessTokens()).thenReturn(null); when(servletRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(null); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(bizConfig, times(1)).isAdminServiceAccessControlEnabled(); verify(bizConfig, times(1)).getAdminServiceAccessTokens(); verify(filterChain, times(1)).doFilter(servletRequest, servletResponse); verify(servletResponse, never()).sendError(anyInt(), anyString()); } @Test public void testWithConfigChanged() throws Exception { String someToken = "someToken"; String anotherToken = "anotherToken"; String yetAnotherToken = "yetAnotherToken"; // case 1: init state when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(true); when(bizConfig.getAdminServiceAccessTokens()).thenReturn(someToken); when(servletRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someToken); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain, times(1)).doFilter(servletRequest, servletResponse); verify(servletResponse, never()).sendError(anyInt(), anyString()); // case 2: change access tokens specified initVariables(); when(bizConfig.getAdminServiceAccessTokens()) .thenReturn(String.format("%s,%s", anotherToken, yetAnotherToken)); when(servletRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(someToken); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse, times(1)) .sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); verify(filterChain, never()).doFilter(servletRequest, servletResponse); initVariables(); when(servletRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn(anotherToken); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain, times(1)).doFilter(servletRequest, servletResponse); verify(servletResponse, never()).sendError(anyInt(), anyString()); // case 3: change access control flag initVariables(); when(bizConfig.isAdminServiceAccessControlEnabled()).thenReturn(false); authenticationFilter.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain, times(1)).doFilter(servletRequest, servletResponse); verify(servletResponse, never()).sendError(anyInt(), anyString()); verify(servletRequest, never()).getHeader(HttpHeaders.AUTHORIZATION); } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_4128_3
crossvul-java_data_bad_4247_2
404: Not Found
./CrossVul/dataset_final_sorted/CWE-20/java/bad_4247_2
crossvul-java_data_good_4128_0
package com.ctrip.framework.apollo.adminservice; import com.ctrip.framework.apollo.adminservice.filter.AdminServiceAuthenticationFilter; import com.ctrip.framework.apollo.biz.config.BizConfig; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AdminServiceAutoConfiguration { private final BizConfig bizConfig; public AdminServiceAutoConfiguration(final BizConfig bizConfig) { this.bizConfig = bizConfig; } @Bean public FilterRegistrationBean<AdminServiceAuthenticationFilter> adminServiceAuthenticationFilter() { FilterRegistrationBean<AdminServiceAuthenticationFilter> filterRegistrationBean = new FilterRegistrationBean<>(); filterRegistrationBean.setFilter(new AdminServiceAuthenticationFilter(bizConfig)); filterRegistrationBean.addUrlPatterns("/apps/*"); filterRegistrationBean.addUrlPatterns("/appnamespaces/*"); filterRegistrationBean.addUrlPatterns("/instances/*"); filterRegistrationBean.addUrlPatterns("/items/*"); filterRegistrationBean.addUrlPatterns("/namespaces/*"); filterRegistrationBean.addUrlPatterns("/releases/*"); return filterRegistrationBean; } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_4128_0
crossvul-java_data_good_418_3
package eu.siacs.conversations.ui; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.PendingIntent; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.ClipboardManager; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.content.res.TypedArray; import android.databinding.DataBindingUtil; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.support.annotation.BoolRes; import android.support.annotation.StringRes; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog.Builder; import android.support.v7.app.AppCompatDelegate; import android.text.InputType; import android.util.DisplayMetrics; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import eu.siacs.conversations.Config; import eu.siacs.conversations.R; import eu.siacs.conversations.crypto.PgpEngine; import eu.siacs.conversations.databinding.DialogQuickeditBinding; import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Contact; import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Presences; import eu.siacs.conversations.services.AvatarService; import eu.siacs.conversations.services.BarcodeProvider; import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder; import eu.siacs.conversations.ui.util.MenuDoubleTabUtil; import eu.siacs.conversations.ui.util.PresenceSelector; import eu.siacs.conversations.ui.util.SoftKeyboardUtils; import eu.siacs.conversations.utils.ExceptionHelper; import eu.siacs.conversations.utils.ThemeHelper; import eu.siacs.conversations.xmpp.OnKeyStatusUpdated; import eu.siacs.conversations.xmpp.OnUpdateBlocklist; import rocks.xmpp.addr.Jid; public abstract class XmppActivity extends ActionBarActivity { public static final String EXTRA_ACCOUNT = "account"; protected static final int REQUEST_ANNOUNCE_PGP = 0x0101; protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102; protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103; protected static final int REQUEST_BATTERY_OP = 0x49ff; public XmppConnectionService xmppConnectionService; public boolean xmppConnectionServiceBound = false; protected int mColorRed; protected static final String FRAGMENT_TAG_DIALOG = "dialog"; private boolean isCameraFeatureAvailable = false; protected int mTheme; protected boolean mUsingEnterKey = false; protected Toast mToast; public Runnable onOpenPGPKeyPublished = () -> Toast.makeText(XmppActivity.this, R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show(); protected ConferenceInvite mPendingConferenceInvite = null; protected ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { XmppConnectionBinder binder = (XmppConnectionBinder) service; xmppConnectionService = binder.getService(); xmppConnectionServiceBound = true; registerListeners(); onBackendConnected(); } @Override public void onServiceDisconnected(ComponentName arg0) { xmppConnectionServiceBound = false; } }; private DisplayMetrics metrics; private long mLastUiRefresh = 0; private Handler mRefreshUiHandler = new Handler(); private Runnable mRefreshUiRunnable = () -> { mLastUiRefresh = SystemClock.elapsedRealtime(); refreshUiReal(); }; private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() { @Override public void success(final Conversation conversation) { runOnUiThread(() -> { switchToConversation(conversation); hideToast(); }); } @Override public void error(final int errorCode, Conversation object) { runOnUiThread(() -> replaceToast(getString(errorCode))); } @Override public void userInputRequried(PendingIntent pi, Conversation object) { } }; public boolean mSkipBackgroundBinding = false; public static boolean cancelPotentialWork(Message message, ImageView imageView) { final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); if (bitmapWorkerTask != null) { final Message oldMessage = bitmapWorkerTask.message; if (oldMessage == null || message != oldMessage) { bitmapWorkerTask.cancel(true); } else { return false; } } return true; } private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) { if (imageView != null) { final Drawable drawable = imageView.getDrawable(); if (drawable instanceof AsyncDrawable) { final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable; return asyncDrawable.getBitmapWorkerTask(); } } return null; } protected void hideToast() { if (mToast != null) { mToast.cancel(); } } protected void replaceToast(String msg) { replaceToast(msg, true); } protected void replaceToast(String msg, boolean showlong) { hideToast(); mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT); mToast.show(); } protected final void refreshUi() { final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh; if (diff > Config.REFRESH_UI_INTERVAL) { mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable); runOnUiThread(mRefreshUiRunnable); } else { final long next = Config.REFRESH_UI_INTERVAL - diff; mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable); mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next); } } abstract protected void refreshUiReal(); @Override protected void onStart() { super.onStart(); if (!xmppConnectionServiceBound) { if (this.mSkipBackgroundBinding) { Log.d(Config.LOGTAG,"skipping background binding"); } else { connectToBackend(); } } else { this.registerListeners(); this.onBackendConnected(); } } public void connectToBackend() { Intent intent = new Intent(this, XmppConnectionService.class); intent.setAction("ui"); startService(intent); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); if (xmppConnectionServiceBound) { this.unregisterListeners(); unbindService(mConnection); xmppConnectionServiceBound = false; } } public boolean hasPgp() { return xmppConnectionService.getPgpEngine() != null; } public void showInstallPgpDialog() { Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.openkeychain_required)); builder.setIconAttribute(android.R.attr.alertDialogIcon); builder.setMessage(getText(R.string.openkeychain_required_long)); builder.setNegativeButton(getString(R.string.cancel), null); builder.setNeutralButton(getString(R.string.restart), (dialog, which) -> { if (xmppConnectionServiceBound) { unbindService(mConnection); xmppConnectionServiceBound = false; } stopService(new Intent(XmppActivity.this, XmppConnectionService.class)); finish(); }); builder.setPositiveButton(getString(R.string.install), (dialog, which) -> { Uri uri = Uri .parse("market://details?id=org.sufficientlysecure.keychain"); Intent marketIntent = new Intent(Intent.ACTION_VIEW, uri); PackageManager manager = getApplicationContext() .getPackageManager(); List<ResolveInfo> infos = manager .queryIntentActivities(marketIntent, 0); if (infos.size() > 0) { startActivity(marketIntent); } else { uri = Uri.parse("http://www.openkeychain.org/"); Intent browserIntent = new Intent( Intent.ACTION_VIEW, uri); startActivity(browserIntent); } finish(); }); builder.create().show(); } abstract void onBackendConnected(); protected void registerListeners() { if (this instanceof XmppConnectionService.OnConversationUpdate) { this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this); } if (this instanceof XmppConnectionService.OnAccountUpdate) { this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this); } if (this instanceof XmppConnectionService.OnCaptchaRequested) { this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this); } if (this instanceof XmppConnectionService.OnRosterUpdate) { this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this); } if (this instanceof XmppConnectionService.OnMucRosterUpdate) { this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this); } if (this instanceof OnUpdateBlocklist) { this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this); } if (this instanceof XmppConnectionService.OnShowErrorToast) { this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this); } if (this instanceof OnKeyStatusUpdated) { this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this); } } protected void unregisterListeners() { if (this instanceof XmppConnectionService.OnConversationUpdate) { this.xmppConnectionService.removeOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this); } if (this instanceof XmppConnectionService.OnAccountUpdate) { this.xmppConnectionService.removeOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this); } if (this instanceof XmppConnectionService.OnCaptchaRequested) { this.xmppConnectionService.removeOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this); } if (this instanceof XmppConnectionService.OnRosterUpdate) { this.xmppConnectionService.removeOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this); } if (this instanceof XmppConnectionService.OnMucRosterUpdate) { this.xmppConnectionService.removeOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this); } if (this instanceof OnUpdateBlocklist) { this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this); } if (this instanceof XmppConnectionService.OnShowErrorToast) { this.xmppConnectionService.removeOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this); } if (this instanceof OnKeyStatusUpdated) { this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this); } } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: startActivity(new Intent(this, SettingsActivity.class)); break; case R.id.action_accounts: startActivity(new Intent(this, ManageAccountActivity.class)); break; case android.R.id.home: finish(); break; case R.id.action_show_qr_code: showQrCode(); break; } return super.onOptionsItemSelected(item); } public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) { final Contact contact = conversation.getContact(); if (!contact.showInRoster()) { showAddToRosterDialog(conversation.getContact()); } else { final Presences presences = contact.getPresences(); if (presences.size() == 0) { if (!contact.getOption(Contact.Options.TO) && !contact.getOption(Contact.Options.ASKING) && contact.getAccount().getStatus() == Account.State.ONLINE) { showAskForPresenceDialog(contact); } else if (!contact.getOption(Contact.Options.TO) || !contact.getOption(Contact.Options.FROM)) { PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener); } else { conversation.setNextCounterpart(null); listener.onPresenceSelected(); } } else if (presences.size() == 1) { String presence = presences.toResourceArray()[0]; try { conversation.setNextCounterpart(Jid.of(contact.getJid().getLocal(), contact.getJid().getDomain(), presence)); } catch (IllegalArgumentException e) { conversation.setNextCounterpart(null); } listener.onPresenceSelected(); } else { PresenceSelector.showPresenceSelectionDialog(this, conversation, listener); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); metrics = getResources().getDisplayMetrics(); ExceptionHelper.init(getApplicationContext()); this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA); mColorRed = ContextCompat.getColor(this, R.color.red800); this.mTheme = findTheme(); setTheme(this.mTheme); this.mUsingEnterKey = usingEnterKey(); } protected boolean isCameraFeatureAvailable() { return this.isCameraFeatureAvailable; } public boolean isDarkTheme() { return ThemeHelper.isDark(mTheme); } public int getThemeResource(int r_attr_name, int r_drawable_def) { int[] attrs = {r_attr_name}; TypedArray ta = this.getTheme().obtainStyledAttributes(attrs); int res = ta.getResourceId(0, r_drawable_def); ta.recycle(); return res; } protected boolean isOptimizingBattery() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE); return pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName()); } else { return false; } } protected boolean isAffectedByDataSaver() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return cm != null && cm.isActiveNetworkMetered() && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED; } else { return false; } } protected boolean usingEnterKey() { return getBooleanPreference("display_enter_key", R.bool.display_enter_key); } protected SharedPreferences getPreferences() { return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); } protected boolean getBooleanPreference(String name, @BoolRes int res) { return getPreferences().getBoolean(name, getResources().getBoolean(res)); } public void switchToConversation(Conversation conversation) { switchToConversation(conversation, null); } public void switchToConversationAndQuote(Conversation conversation, String text) { switchToConversation(conversation, text, true, null, false, false); } public void switchToConversation(Conversation conversation, String text) { switchToConversation(conversation, text, false, null, false, false); } public void switchToConversationDoNotAppend(Conversation conversation, String text) { switchToConversation(conversation, text, false, null, false, true); } public void highlightInMuc(Conversation conversation, String nick) { switchToConversation(conversation, null, false, nick, false, false); } public void privateMsgInMuc(Conversation conversation, String nick) { switchToConversation(conversation, null, false, nick, true, false); } private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm, boolean doNotAppend) { Intent intent = new Intent(this, ConversationsActivity.class); intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION); intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid()); if (text != null) { intent.putExtra(Intent.EXTRA_TEXT, text); if (asQuote) { intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true); } } if (nick != null) { intent.putExtra(ConversationsActivity.EXTRA_NICK, nick); intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm); } if (doNotAppend) { intent.putExtra(ConversationsActivity.EXTRA_DO_NOT_APPEND, true); } intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } public void switchToContactDetails(Contact contact) { switchToContactDetails(contact, null); } public void switchToContactDetails(Contact contact, String messageFingerprint) { Intent intent = new Intent(this, ContactDetailsActivity.class); intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT); intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toString()); intent.putExtra("contact", contact.getJid().toString()); intent.putExtra("fingerprint", messageFingerprint); startActivity(intent); } public void switchToAccount(Account account, String fingerprint) { switchToAccount(account, false, fingerprint); } public void switchToAccount(Account account) { switchToAccount(account, false, null); } public void switchToAccount(Account account, boolean init, String fingerprint) { Intent intent = new Intent(this, EditAccountActivity.class); intent.putExtra("jid", account.getJid().asBareJid().toString()); intent.putExtra("init", init); if (init) { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION); } if (fingerprint != null) { intent.putExtra("fingerprint", fingerprint); } startActivity(intent); if (init) { overridePendingTransition(0, 0); } } protected void delegateUriPermissionsToService(Uri uri) { Intent intent = new Intent(this, XmppConnectionService.class); intent.setAction(Intent.ACTION_SEND); intent.setData(uri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); try { startService(intent); } catch (Exception e) { Log.e(Config.LOGTAG,"unable to delegate uri permission",e); } } protected void inviteToConversation(Conversation conversation) { startActivityForResult(ChooseContactActivity.create(this,conversation), REQUEST_INVITE_TO_CONVERSATION); } protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) { if (account.getPgpId() == 0) { choosePgpSignId(account); } else { String status = null; if (manuallyChangePresence()) { status = account.getPresenceStatusMessage(); } if (status == null) { status = ""; } xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() { @Override public void userInputRequried(PendingIntent pi, String signature) { try { startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0); } catch (final SendIntentException ignored) { } } @Override public void success(String signature) { account.setPgpSignature(signature); xmppConnectionService.databaseBackend.updateAccount(account); xmppConnectionService.sendPresence(account); if (conversation != null) { conversation.setNextEncryption(Message.ENCRYPTION_PGP); xmppConnectionService.updateConversation(conversation); refreshUi(); } if (onSuccess != null) { runOnUiThread(onSuccess); } } @Override public void error(int error, String signature) { if (error == 0) { account.setPgpSignId(0); account.unsetPgpSignature(); xmppConnectionService.databaseBackend.updateAccount(account); choosePgpSignId(account); } else { displayErrorDialog(error); } } }); } } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN) protected void setListItemBackgroundOnView(View view) { int sdk = android.os.Build.VERSION.SDK_INT; if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground)); } else { view.setBackground(getResources().getDrawable(R.drawable.greybackground)); } } protected void choosePgpSignId(Account account) { xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() { @Override public void success(Account account1) { } @Override public void error(int errorCode, Account object) { } @Override public void userInputRequried(PendingIntent pi, Account object) { try { startIntentSenderForResult(pi.getIntentSender(), REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0); } catch (final SendIntentException ignored) { } } }); } protected void displayErrorDialog(final int errorCode) { runOnUiThread(() -> { Builder builder = new Builder(XmppActivity.this); builder.setIconAttribute(android.R.attr.alertDialogIcon); builder.setTitle(getString(R.string.error)); builder.setMessage(errorCode); builder.setNeutralButton(R.string.accept, null); builder.create().show(); }); } protected void showAddToRosterDialog(final Contact contact) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(contact.getJid().toString()); builder.setMessage(getString(R.string.not_in_roster)); builder.setNegativeButton(getString(R.string.cancel), null); builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact,true)); builder.create().show(); } private void showAskForPresenceDialog(final Contact contact) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(contact.getJid().toString()); builder.setMessage(R.string.request_presence_updates); builder.setNegativeButton(R.string.cancel, null); builder.setPositiveButton(R.string.request_now, (dialog, which) -> { if (xmppConnectionServiceBound) { xmppConnectionService.sendPresencePacket(contact .getAccount(), xmppConnectionService .getPresenceGenerator() .requestPresenceUpdatesFrom(contact)); } }); builder.create().show(); } protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) { quickEdit(previousValue, callback, hint, false, false); } protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) { quickEdit(previousValue, callback, hint, false, permitEmpty); } protected void quickPasswordEdit(String previousValue, OnValueEdited callback) { quickEdit(previousValue, callback, R.string.password, true, false); } @SuppressLint("InflateParams") private void quickEdit(final String previousValue, final OnValueEdited callback, final @StringRes int hint, boolean password, boolean permitEmpty) { AlertDialog.Builder builder = new AlertDialog.Builder(this); DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(),R.layout.dialog_quickedit, null, false); if (password) { binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } builder.setPositiveButton(R.string.accept, null); if (hint != 0) { binding.inputLayout.setHint(getString(hint)); } binding.inputEditText.requestFocus(); if (previousValue != null) { binding.inputEditText.getText().append(previousValue); } builder.setView(binding.getRoot()); builder.setNegativeButton(R.string.cancel, null); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText)); dialog.show(); View.OnClickListener clickListener = v -> { String value = binding.inputEditText.getText().toString(); if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) { String error = callback.onValueEdited(value); if (error != null) { binding.inputLayout.setError(error); return; } } SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText); dialog.dismiss(); }; dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener); dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> { SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText); dialog.dismiss(); })); dialog.setOnDismissListener(dialog1 -> { SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText); }); } protected boolean hasStoragePermission(int requestCode) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode); return false; } else { return true; } } else { return true; } } protected void onActivityResult(int requestCode, int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) { mPendingConferenceInvite = ConferenceInvite.parse(data); if (xmppConnectionServiceBound && mPendingConferenceInvite != null) { if (mPendingConferenceInvite.execute(this)) { mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG); mToast.show(); } mPendingConferenceInvite = null; } } } public int getWarningTextColor() { return this.mColorRed; } public int getPixel(int dp) { DisplayMetrics metrics = getResources().getDisplayMetrics(); return ((int) (dp * metrics.density)); } public boolean copyTextToClipboard(String text, int labelResId) { ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); String label = getResources().getString(labelResId); if (mClipBoardManager != null) { ClipData mClipData = ClipData.newPlainText(label, text); mClipBoardManager.setPrimaryClip(mClipData); return true; } return false; } protected boolean neverCompressPictures() { return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never"); } protected boolean manuallyChangePresence() { return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence); } protected String getShareableUri() { return getShareableUri(false); } protected String getShareableUri(boolean http) { return null; } protected void shareLink(boolean http) { String uri = getShareableUri(http); if (uri == null || uri.isEmpty()) { return; } Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http)); try { startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with))); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show(); } } protected void launchOpenKeyChain(long keyId) { PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine(); try { startIntentSenderForResult( pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0, 0, 0); } catch (Throwable e) { Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show(); } } @Override public void onResume() { super.onResume(); } protected int findTheme() { return ThemeHelper.find(this); } @Override public void onPause() { super.onPause(); } @Override public boolean onMenuOpened(int id, Menu menu) { if(id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) { MenuDoubleTabUtil.recordMenuOpen(); } return super.onMenuOpened(id, menu); } protected void showQrCode() { showQrCode(getShareableUri()); } protected void showQrCode(final String uri) { if (uri == null || uri.isEmpty()) { return; } Point size = new Point(); getWindowManager().getDefaultDisplay().getSize(size); final int width = (size.x < size.y ? size.x : size.y); Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width); ImageView view = new ImageView(this); view.setBackgroundColor(Color.WHITE); view.setImageBitmap(bitmap); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(view); builder.create().show(); } protected Account extractAccount(Intent intent) { String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null; try { return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null; } catch (IllegalArgumentException e) { return null; } } public AvatarService avatarService() { return xmppConnectionService.getAvatarService(); } public void loadBitmap(Message message, ImageView imageView) { Bitmap bm; try { bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true); } catch (IOException e) { bm = null; } if (bm != null) { cancelPotentialWork(message, imageView); imageView.setImageBitmap(bm); imageView.setBackgroundColor(0x00000000); } else { if (cancelPotentialWork(message, imageView)) { imageView.setBackgroundColor(0xff333333); imageView.setImageDrawable(null); final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView); final AsyncDrawable asyncDrawable = new AsyncDrawable( getResources(), null, task); imageView.setImageDrawable(asyncDrawable); try { task.execute(message); } catch (final RejectedExecutionException ignored) { ignored.printStackTrace(); } } } } protected interface OnValueEdited { String onValueEdited(String value); } public static class ConferenceInvite { private String uuid; private List<Jid> jids = new ArrayList<>(); public static ConferenceInvite parse(Intent data) { ConferenceInvite invite = new ConferenceInvite(); invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION); if (invite.uuid == null) { return null; } invite.jids.addAll(ChooseContactActivity.extractJabberIds(data)); return invite; } public boolean execute(XmppActivity activity) { XmppConnectionService service = activity.xmppConnectionService; Conversation conversation = service.findConversationByUuid(this.uuid); if (conversation == null) { return false; } if (conversation.getMode() == Conversation.MODE_MULTI) { for (Jid jid : jids) { service.invite(conversation, jid); } return false; } else { jids.add(conversation.getJid().asBareJid()); return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback); } } } static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> { private final WeakReference<ImageView> imageViewReference; private final WeakReference<XmppActivity> activity; private Message message = null; private BitmapWorkerTask(XmppActivity activity, ImageView imageView) { this.activity = new WeakReference<>(activity); this.imageViewReference = new WeakReference<>(imageView); } @Override protected Bitmap doInBackground(Message... params) { if (isCancelled()) { return null; } message = params[0]; try { XmppActivity activity = this.activity.get(); if (activity != null && activity.xmppConnectionService != null) { return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false); } else { return null; } } catch (IOException e) { return null; } } @Override protected void onPostExecute(Bitmap bitmap) { if (bitmap != null && !isCancelled()) { final ImageView imageView = imageViewReference.get(); if (imageView != null) { imageView.setImageBitmap(bitmap); imageView.setBackgroundColor(0x00000000); } } } } private static class AsyncDrawable extends BitmapDrawable { private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference; private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) { super(res, bitmap); bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask); } private BitmapWorkerTask getBitmapWorkerTask() { return bitmapWorkerTaskReference.get(); } } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_418_3
crossvul-java_data_bad_4247_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-20/java/bad_4247_1
crossvul-java_data_bad_195_7
/* * Copyright (c) 2011-2017 Contributors to the Eclipse Foundation * * 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, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.test.core; import io.vertx.core.MultiMap; import io.vertx.core.http.impl.headers.VertxHttpHeaders; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public class VertxHttpHeadersTest extends CaseInsensitiveHeadersTest { @Override protected MultiMap newMultiMap() { return new VertxHttpHeaders(); } }
./CrossVul/dataset_final_sorted/CWE-20/java/bad_195_7
crossvul-java_data_good_4247_1
/* * Copyright (c) 2015, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package org.glassfish.soteria.mechanisms.jaspic; import java.util.Map; import java.util.function.Supplier; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.message.AuthException; import javax.security.auth.message.MessageInfo; import javax.security.auth.message.config.ServerAuthConfig; import javax.security.auth.message.config.ServerAuthContext; import javax.security.auth.message.module.ServerAuthModule; /** * This class functions as a kind of factory for {@link ServerAuthContext} instances, which are delegates for the actual * {@link ServerAuthModule} (SAM) that we're after. * * @author Arjan Tijms */ public class DefaultServerAuthConfig implements ServerAuthConfig { private String layer; private String appContext; private CallbackHandler handler; private Map<String, String> providerProperties; private Supplier<ServerAuthModule> serverAuthModuleSupplier; public DefaultServerAuthConfig(String layer, String appContext, CallbackHandler handler, Map<String, String> providerProperties, Supplier<ServerAuthModule> serverAuthModuleSupplier) { this.layer = layer; this.appContext = appContext; this.handler = handler; this.providerProperties = providerProperties; this.serverAuthModuleSupplier = serverAuthModuleSupplier; } @Override public ServerAuthContext getAuthContext(String authContextID, Subject serviceSubject, @SuppressWarnings("rawtypes") Map properties) throws AuthException { return new DefaultServerAuthContext(handler, serverAuthModuleSupplier); } // ### The methods below mostly just return what has been passed into the // constructor. // ### In practice they don't seem to be called @Override public String getMessageLayer() { return layer; } /** * It's not entirely clear what the difference is between the "application context identifier" (appContext) and the * "authentication context identifier" (authContext). In early iterations of the specification, authContext was called * "operation" and instead of the MessageInfo it was obtained by something called an "authParam". */ @Override public String getAuthContextID(MessageInfo messageInfo) { return appContext; } @Override public String getAppContext() { return appContext; } @Override public void refresh() { } @Override public boolean isProtected() { return false; } public Map<String, String> getProviderProperties() { return providerProperties; } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_4247_1
crossvul-java_data_good_4247_0
/* * Copyright (c) 2015, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package org.glassfish.soteria.mechanisms.jaspic; import java.util.Map; import java.util.function.Supplier; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.message.AuthException; import javax.security.auth.message.config.AuthConfigFactory; import javax.security.auth.message.config.AuthConfigProvider; import javax.security.auth.message.config.ClientAuthConfig; import javax.security.auth.message.config.ServerAuthConfig; import javax.security.auth.message.config.ServerAuthContext; import javax.security.auth.message.module.ServerAuthModule; /** * This class functions as a kind of factory-factory for {@link ServerAuthConfig} instances, which are by themselves factories * for {@link ServerAuthContext} instances, which are delegates for the actual {@link ServerAuthModule} (SAM) that we're after. * * @author Arjan Tijms */ public class DefaultAuthConfigProvider implements AuthConfigProvider { private static final String CALLBACK_HANDLER_PROPERTY_NAME = "authconfigprovider.client.callbackhandler"; private Map<String, String> providerProperties; private Supplier<ServerAuthModule> serverAuthModuleSupplier; public DefaultAuthConfigProvider(Supplier<ServerAuthModule> serverAuthModuleSupplier) { this.serverAuthModuleSupplier = serverAuthModuleSupplier; } /** * Constructor with signature and implementation that's required by API. * * @param properties provider properties * @param factory the auth config factory */ public DefaultAuthConfigProvider(Map<String, String> properties, AuthConfigFactory factory) { this.providerProperties = properties; // API requires self registration if factory is provided. Not clear // where the "layer" (2nd parameter) // and especially "appContext" (3rd parameter) values have to come from // at this place. if (factory != null) { // If this method ever gets called, it may throw a SecurityException. // Don't bother with a PrivilegedAction as we don't expect to ever be // constructed this way. factory.registerConfigProvider(this, null, null, "Auto registration"); } } /** * The actual factory method that creates the factory used to eventually obtain the delegate for a SAM. */ @Override public ServerAuthConfig getServerAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException, SecurityException { return new DefaultServerAuthConfig(layer, appContext, handler == null ? createDefaultCallbackHandler() : handler, providerProperties, serverAuthModuleSupplier); } @Override public ClientAuthConfig getClientAuthConfig(String layer, String appContext, CallbackHandler handler) throws AuthException, SecurityException { return null; } @Override public void refresh() { } /** * Creates a default callback handler via the system property "authconfigprovider.client.callbackhandler", as seemingly * required by the API (API uses wording "may" create default handler). TODO: Isn't * "authconfigprovider.client.callbackhandler" JBoss specific? * * @return * @throws AuthException */ private CallbackHandler createDefaultCallbackHandler() throws AuthException { String callBackClassName = System.getProperty(CALLBACK_HANDLER_PROPERTY_NAME); if (callBackClassName == null) { throw new AuthException("No default handler set via system property: " + CALLBACK_HANDLER_PROPERTY_NAME); } try { return (CallbackHandler) Thread.currentThread().getContextClassLoader().loadClass(callBackClassName).newInstance(); } catch (Exception e) { throw new AuthException(e.getMessage()); } } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_4247_0
crossvul-java_data_good_195_0
/* * Copyright (c) 2011-2017 Contributors to the Eclipse Foundation * * 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, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core.http; import io.netty.util.AsciiString; import io.vertx.core.http.impl.HttpUtils; /** * Contains often used Header names. * <p> * It also contains a utility method to create optimized {@link CharSequence} which can be used as header name and value. * * @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a> */ public final class HttpHeaders { /** * Accept header name */ public static final CharSequence ACCEPT = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT); /** * Accept-Charset header name */ public static final CharSequence ACCEPT_CHARSET = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT_CHARSET); /** * Accept-Encoding header name */ public static final CharSequence ACCEPT_ENCODING = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT_ENCODING); /** * Accept-Language header name */ public static final CharSequence ACCEPT_LANGUAGE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT_LANGUAGE); /** * Accept-Ranges header name */ public static final CharSequence ACCEPT_RANGES = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT_RANGES); /** * Accept-Patch header name */ public static final CharSequence ACCEPT_PATCH = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCEPT_PATCH); /** * Access-Control-Allow-Credentials header name */ public static final CharSequence ACCESS_CONTROL_ALLOW_CREDENTIALS = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_ALLOW_CREDENTIALS); /** * Access-Control-Allow-Headers header name */ public static final CharSequence ACCESS_CONTROL_ALLOW_HEADERS = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_ALLOW_HEADERS); /** * Access-Control-Allow-Methods header name */ public static final CharSequence ACCESS_CONTROL_ALLOW_METHODS = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_ALLOW_METHODS); /** * Access-Control-Allow-Origin header name */ public static final CharSequence ACCESS_CONTROL_ALLOW_ORIGIN = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN); /** * Access-Control-Expose-Headers header name */ public static final CharSequence ACCESS_CONTROL_EXPOSE_HEADERS = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_EXPOSE_HEADERS); /** * Access-Control-Max-Age header name */ public static final CharSequence ACCESS_CONTROL_MAX_AGE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_MAX_AGE); /** * Access-Control-Request-Headers header name */ public static final CharSequence ACCESS_CONTROL_REQUEST_HEADERS = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_REQUEST_HEADERS); /** * Access-Control-Request-Method header name */ public static final CharSequence ACCESS_CONTROL_REQUEST_METHOD = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ACCESS_CONTROL_REQUEST_METHOD); /** * Age header name */ public static final CharSequence AGE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.AGE); /** * Allow header name */ public static final CharSequence ALLOW = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ALLOW); /** * Authorization header name */ public static final CharSequence AUTHORIZATION = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.AUTHORIZATION); /** * Cache-Control header name */ public static final CharSequence CACHE_CONTROL = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CACHE_CONTROL); /** * Connection header name */ public static final CharSequence CONNECTION = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION); /** * Content-Base header name */ public static final CharSequence CONTENT_BASE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_BASE); /** * Content-Encoding header name */ public static final CharSequence CONTENT_ENCODING = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_ENCODING); /** * Content-Language header name */ public static final CharSequence CONTENT_LANGUAGE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LANGUAGE); /** * Content-Length header name */ public static final CharSequence CONTENT_LENGTH = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH); /** * Content-Location header name */ public static final CharSequence CONTENT_LOCATION = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LOCATION); /** * Content-Transfer-Encoding header name */ public static final CharSequence CONTENT_TRANSFER_ENCODING = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TRANSFER_ENCODING); /** * Content-MD5 header name */ public static final CharSequence CONTENT_MD5 = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_MD5); /** * Content-Rage header name */ public static final CharSequence CONTENT_RANGE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_RANGE); /** * Content-Type header name */ public static final CharSequence CONTENT_TYPE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE); /** * Content-Cookie header name */ public static final CharSequence COOKIE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.COOKIE); /** * Date header name */ public static final CharSequence DATE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.DATE); /** * Etag header name */ public static final CharSequence ETAG = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ETAG); /** * Expect header name */ public static final CharSequence EXPECT = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.EXPECT); /** * Expires header name */ public static final CharSequence EXPIRES = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.EXPIRES); /** * From header name */ public static final CharSequence FROM = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.FROM); /** * Host header name */ public static final CharSequence HOST = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.HOST); /** * If-Match header name */ public static final CharSequence IF_MATCH = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.IF_MATCH); /** * If-Modified-Since header name */ public static final CharSequence IF_MODIFIED_SINCE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.IF_MODIFIED_SINCE); /** * If-None-Match header name */ public static final CharSequence IF_NONE_MATCH = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.IF_NONE_MATCH); /** * Last-Modified header name */ public static final CharSequence LAST_MODIFIED = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.LAST_MODIFIED); /** * Location header name */ public static final CharSequence LOCATION = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.LOCATION); /** * Origin header name */ public static final CharSequence ORIGIN = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.ORIGIN); /** * Proxy-Authenticate header name */ public static final CharSequence PROXY_AUTHENTICATE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.PROXY_AUTHENTICATE); /** * Proxy-Authorization header name */ public static final CharSequence PROXY_AUTHORIZATION = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.PROXY_AUTHORIZATION); /** * Referer header name */ public static final CharSequence REFERER = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.REFERER); /** * Retry-After header name */ public static final CharSequence RETRY_AFTER = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.RETRY_AFTER); /** * Server header name */ public static final CharSequence SERVER = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.SERVER); /** * Transfer-Encoding header name */ public static final CharSequence TRANSFER_ENCODING = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.TRANSFER_ENCODING); /** * User-Agent header name */ public static final CharSequence USER_AGENT = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.USER_AGENT); /** * Set-Cookie header name */ public static final CharSequence SET_COOKIE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Names.SET_COOKIE); /** * application/x-www-form-urlencoded header value */ public static final CharSequence APPLICATION_X_WWW_FORM_URLENCODED = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); /** * chunked header value */ public static final CharSequence CHUNKED = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.CHUNKED); /** * close header value */ public static final CharSequence CLOSE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.CLOSE); /** * 100-continue header value */ public static final CharSequence CONTINUE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.CONTINUE); /** * identity header value */ public static final CharSequence IDENTITY = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.IDENTITY); /** * keep-alive header value */ public static final CharSequence KEEP_ALIVE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.KEEP_ALIVE); /** * Upgrade header value */ public static final CharSequence UPGRADE = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.UPGRADE); /** * WebSocket header value */ public static final CharSequence WEBSOCKET = createOptimized(io.netty.handler.codec.http.HttpHeaders.Values.WEBSOCKET); /** * deflate,gzip header value */ public static final CharSequence DEFLATE_GZIP = createOptimized("deflate, gzip"); /** * text/html header value */ public static final CharSequence TEXT_HTML = createOptimized("text/html"); /** * GET header value */ public static final CharSequence GET = createOptimized("GET"); /** * Create an optimized {@link CharSequence} which can be used as header name or value. * This should be used if you expect to use it multiple times liked for example adding the same header name or value * for multiple responses or requests. */ public static CharSequence createOptimized(String value) { HttpUtils.validateHeader(value); return new AsciiString(value); } private HttpHeaders() { } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_195_0
crossvul-java_data_bad_1101_0
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.plugins.signing.signatory.pgp; import org.bouncycastle.bcpg.BCPGOutputStream; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPSecretKey; import org.bouncycastle.openpgp.PGPSignature; import org.bouncycastle.openpgp.PGPSignatureGenerator; import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.operator.PBESecretKeyDecryptor; import org.bouncycastle.openpgp.operator.bc.BcPBESecretKeyDecryptorBuilder; import org.bouncycastle.openpgp.operator.bc.BcPGPContentSignerBuilder; import org.bouncycastle.openpgp.operator.bc.BcPGPDigestCalculatorProvider; import org.gradle.api.UncheckedIOException; import org.gradle.internal.UncheckedException; import org.gradle.plugins.signing.signatory.SignatorySupport; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.Security; /** * PGP signatory from PGP key and password. */ public class PgpSignatory extends SignatorySupport { { Security.addProvider(new BouncyCastleProvider()); } private final String name; private final PGPSecretKey secretKey; private final PGPPrivateKey privateKey; public PgpSignatory(String name, PGPSecretKey secretKey, String password) { this.name = name; this.secretKey = secretKey; this.privateKey = createPrivateKey(secretKey, password); } @Override public final String getName() { return name; } /** * Exhausts {@code toSign}, and writes the signature to {@code signatureDestination}. * * The caller is responsible for closing the streams, though the output WILL be flushed. */ @Override public void sign(InputStream toSign, OutputStream signatureDestination) { PGPSignatureGenerator generator = createSignatureGenerator(); try { feedGeneratorWith(toSign, generator); PGPSignature signature = generator.generate(); writeSignatureTo(signatureDestination, signature); } catch (IOException e) { throw new UncheckedIOException(e); } catch (PGPException e) { throw UncheckedException.throwAsUncheckedException(e); } } @Override public String getKeyId() { PgpKeyId id = new PgpKeyId(secretKey.getKeyID()); return id == null ? null : id.getAsHex(); } private void feedGeneratorWith(InputStream toSign, PGPSignatureGenerator generator) throws IOException { byte[] buffer = new byte[1024]; int read = toSign.read(buffer); while (read > 0) { generator.update(buffer, 0, read); read = toSign.read(buffer); } } private void writeSignatureTo(OutputStream signatureDestination, PGPSignature pgpSignature) throws PGPException, IOException { // BCPGOutputStream seems to do some internal buffering, it's unclear whether it's strictly required here though BCPGOutputStream bufferedOutput = new BCPGOutputStream(signatureDestination); pgpSignature.encode(bufferedOutput); bufferedOutput.flush(); } public PGPSignatureGenerator createSignatureGenerator() { try { PGPSignatureGenerator generator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)); generator.init(PGPSignature.BINARY_DOCUMENT, privateKey); return generator; } catch (PGPException e) { throw UncheckedException.throwAsUncheckedException(e); } } private PGPPrivateKey createPrivateKey(PGPSecretKey secretKey, String password) { try { PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(password.toCharArray()); return secretKey.extractPrivateKey(decryptor); } catch (PGPException e) { throw UncheckedException.throwAsUncheckedException(e); } } }
./CrossVul/dataset_final_sorted/CWE-20/java/bad_1101_0
crossvul-java_data_good_418_0
package eu.siacs.conversations.ui; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.app.FragmentManager; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.databinding.DataBindingUtil; import android.net.Uri; import android.os.Build; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.v7.app.AlertDialog; import android.app.Fragment; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.support.v13.view.inputmethod.InputConnectionCompat; import android.support.v13.view.inputmethod.InputContentInfoCompat; import android.text.Editable; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.CheckBox; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.TextView.OnEditorActionListener; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import eu.siacs.conversations.Config; import eu.siacs.conversations.R; import eu.siacs.conversations.crypto.axolotl.AxolotlService; import eu.siacs.conversations.crypto.axolotl.FingerprintStatus; import eu.siacs.conversations.databinding.FragmentConversationBinding; import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Blockable; import eu.siacs.conversations.entities.Contact; import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Conversational; import eu.siacs.conversations.entities.DownloadableFile; import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.MucOptions; import eu.siacs.conversations.entities.MucOptions.User; import eu.siacs.conversations.entities.Presence; import eu.siacs.conversations.entities.ReadByMarker; import eu.siacs.conversations.entities.Transferable; import eu.siacs.conversations.entities.TransferablePlaceholder; import eu.siacs.conversations.http.HttpDownloadConnection; import eu.siacs.conversations.persistance.FileBackend; import eu.siacs.conversations.services.MessageArchiveService; import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.ui.adapter.MediaPreviewAdapter; import eu.siacs.conversations.ui.adapter.MessageAdapter; import eu.siacs.conversations.ui.util.ActivityResult; import eu.siacs.conversations.ui.util.Attachment; import eu.siacs.conversations.ui.util.ConversationMenuConfigurator; import eu.siacs.conversations.ui.util.DateSeparator; import eu.siacs.conversations.ui.util.EditMessageActionModeCallback; import eu.siacs.conversations.ui.util.ListViewUtils; import eu.siacs.conversations.ui.util.MenuDoubleTabUtil; import eu.siacs.conversations.ui.util.MucDetailsContextMenuHelper; import eu.siacs.conversations.ui.util.PendingItem; import eu.siacs.conversations.ui.util.PresenceSelector; import eu.siacs.conversations.ui.util.ScrollState; import eu.siacs.conversations.ui.util.SendButtonAction; import eu.siacs.conversations.ui.util.SendButtonTool; import eu.siacs.conversations.ui.util.ShareUtil; import eu.siacs.conversations.ui.widget.EditMessage; import eu.siacs.conversations.utils.GeoHelper; import eu.siacs.conversations.utils.MessageUtils; import eu.siacs.conversations.utils.NickValidityChecker; import eu.siacs.conversations.utils.Patterns; import eu.siacs.conversations.utils.QuickLoader; import eu.siacs.conversations.utils.StylingHelper; import eu.siacs.conversations.utils.TimeframeUtils; import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.xmpp.XmppConnection; import eu.siacs.conversations.xmpp.chatstate.ChatState; import eu.siacs.conversations.xmpp.jingle.JingleConnection; import rocks.xmpp.addr.Jid; import static eu.siacs.conversations.ui.XmppActivity.EXTRA_ACCOUNT; import static eu.siacs.conversations.ui.XmppActivity.REQUEST_INVITE_TO_CONVERSATION; import static eu.siacs.conversations.ui.util.SoftKeyboardUtils.hideSoftKeyboard; public class ConversationFragment extends XmppFragment implements EditMessage.KeyboardListener { public static final int REQUEST_SEND_MESSAGE = 0x0201; public static final int REQUEST_DECRYPT_PGP = 0x0202; public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207; public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208; public static final int REQUEST_TRUST_KEYS_ATTACHMENTS = 0x0209; public static final int REQUEST_START_DOWNLOAD = 0x0210; public static final int REQUEST_ADD_EDITOR_CONTENT = 0x0211; public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301; public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302; public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303; public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304; public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305; public static final int ATTACHMENT_CHOICE_INVALID = 0x0306; public static final int ATTACHMENT_CHOICE_RECORD_VIDEO = 0x0307; public static final String RECENTLY_USED_QUICK_ACTION = "recently_used_quick_action"; public static final String STATE_CONVERSATION_UUID = ConversationFragment.class.getName() + ".uuid"; public static final String STATE_SCROLL_POSITION = ConversationFragment.class.getName() + ".scroll_position"; public static final String STATE_PHOTO_URI = ConversationFragment.class.getName() + ".media_previews"; public static final String STATE_MEDIA_PREVIEWS = ConversationFragment.class.getName() + ".take_photo_uri"; private static final String STATE_LAST_MESSAGE_UUID = "state_last_message_uuid"; private final List<Message> messageList = new ArrayList<>(); private final PendingItem<ActivityResult> postponedActivityResult = new PendingItem<>(); private final PendingItem<String> pendingConversationsUuid = new PendingItem<>(); private final PendingItem<ArrayList<Attachment>> pendingMediaPreviews = new PendingItem<>(); private final PendingItem<Bundle> pendingExtras = new PendingItem<>(); private final PendingItem<Uri> pendingTakePhotoUri = new PendingItem<>(); private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>(); private final PendingItem<String> pendingLastMessageUuid = new PendingItem<>(); private final PendingItem<Message> pendingMessage = new PendingItem<>(); public Uri mPendingEditorContent = null; protected MessageAdapter messageListAdapter; private MediaPreviewAdapter mediaPreviewAdapter; private String lastMessageUuid = null; private Conversation conversation; private FragmentConversationBinding binding; private Toast messageLoaderToast; private ConversationsActivity activity; private boolean reInitRequiredOnStart = true; private OnClickListener clickToMuc = new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class); intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC); intent.putExtra("uuid", conversation.getUuid()); startActivity(intent); } }; private OnClickListener leaveMuc = new OnClickListener() { @Override public void onClick(View v) { activity.xmppConnectionService.archiveConversation(conversation); } }; private OnClickListener joinMuc = new OnClickListener() { @Override public void onClick(View v) { activity.xmppConnectionService.joinMuc(conversation); } }; private OnClickListener enterPassword = new OnClickListener() { @Override public void onClick(View v) { MucOptions muc = conversation.getMucOptions(); String password = muc.getPassword(); if (password == null) { password = ""; } activity.quickPasswordEdit(password, value -> { activity.xmppConnectionService.providePasswordForMuc(conversation, value); return null; }); } }; private OnScrollListener mOnScrollListener = new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) { fireReadEvent(); } } @Override public void onScroll(final AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { toggleScrollDownButton(view); synchronized (ConversationFragment.this.messageList) { if (firstVisibleItem < 5 && conversation != null && conversation.messagesLoaded.compareAndSet(true, false) && messageList.size() > 0) { long timestamp; if (messageList.get(0).getType() == Message.TYPE_STATUS && messageList.size() >= 2) { timestamp = messageList.get(1).getTimeSent(); } else { timestamp = messageList.get(0).getTimeSent(); } activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() { @Override public void onMoreMessagesLoaded(final int c, final Conversation conversation) { if (ConversationFragment.this.conversation != conversation) { conversation.messagesLoaded.set(true); return; } runOnUiThread(() -> { synchronized (messageList) { final int oldPosition = binding.messagesView.getFirstVisiblePosition(); Message message = null; int childPos; for (childPos = 0; childPos + oldPosition < messageList.size(); ++childPos) { message = messageList.get(oldPosition + childPos); if (message.getType() != Message.TYPE_STATUS) { break; } } final String uuid = message != null ? message.getUuid() : null; View v = binding.messagesView.getChildAt(childPos); final int pxOffset = (v == null) ? 0 : v.getTop(); ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList); try { updateStatusMessages(); } catch (IllegalStateException e) { Log.d(Config.LOGTAG, "caught illegal state exception while updating status messages"); } messageListAdapter.notifyDataSetChanged(); int pos = Math.max(getIndexOf(uuid, messageList), 0); binding.messagesView.setSelectionFromTop(pos, pxOffset); if (messageLoaderToast != null) { messageLoaderToast.cancel(); } conversation.messagesLoaded.set(true); } }); } @Override public void informUser(final int resId) { runOnUiThread(() -> { if (messageLoaderToast != null) { messageLoaderToast.cancel(); } if (ConversationFragment.this.conversation != conversation) { return; } messageLoaderToast = Toast.makeText(view.getContext(), resId, Toast.LENGTH_LONG); messageLoaderToast.show(); }); } }); } } } }; private EditMessage.OnCommitContentListener mEditorContentListener = new EditMessage.OnCommitContentListener() { @Override public boolean onCommitContent(InputContentInfoCompat inputContentInfo, int flags, Bundle opts, String[] contentMimeTypes) { // try to get permission to read the image, if applicable if ((flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) { try { inputContentInfo.requestPermission(); } catch (Exception e) { Log.e(Config.LOGTAG, "InputContentInfoCompat#requestPermission() failed.", e); Toast.makeText(getActivity(), activity.getString(R.string.no_permission_to_access_x, inputContentInfo.getDescription()), Toast.LENGTH_LONG ).show(); return false; } } if (hasPermissions(REQUEST_ADD_EDITOR_CONTENT, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { attachEditorContentToConversation(inputContentInfo.getContentUri()); } else { mPendingEditorContent = inputContentInfo.getContentUri(); } return true; } }; private Message selectedMessage; private OnClickListener mEnableAccountListener = new OnClickListener() { @Override public void onClick(View v) { final Account account = conversation == null ? null : conversation.getAccount(); if (account != null) { account.setOption(Account.OPTION_DISABLED, false); activity.xmppConnectionService.updateAccount(account); } } }; private OnClickListener mUnblockClickListener = new OnClickListener() { @Override public void onClick(final View v) { v.post(() -> v.setVisibility(View.INVISIBLE)); if (conversation.isDomainBlocked()) { BlockContactDialog.show(activity, conversation); } else { unblockConversation(conversation); } } }; private OnClickListener mBlockClickListener = this::showBlockSubmenu; private OnClickListener mAddBackClickListener = new OnClickListener() { @Override public void onClick(View v) { final Contact contact = conversation == null ? null : conversation.getContact(); if (contact != null) { activity.xmppConnectionService.createContact(contact, true); activity.switchToContactDetails(contact); } } }; private View.OnLongClickListener mLongPressBlockListener = this::showBlockSubmenu; private OnClickListener mAllowPresenceSubscription = new OnClickListener() { @Override public void onClick(View v) { final Contact contact = conversation == null ? null : conversation.getContact(); if (contact != null) { activity.xmppConnectionService.sendPresencePacket(contact.getAccount(), activity.xmppConnectionService.getPresenceGenerator() .sendPresenceUpdatesTo(contact)); hideSnackbar(); } } }; protected OnClickListener clickToDecryptListener = new OnClickListener() { @Override public void onClick(View v) { PendingIntent pendingIntent = conversation.getAccount().getPgpDecryptionService().getPendingIntent(); if (pendingIntent != null) { try { getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), REQUEST_DECRYPT_PGP, null, 0, 0, 0); } catch (SendIntentException e) { Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show(); conversation.getAccount().getPgpDecryptionService().continueDecryption(true); } } updateSnackBar(conversation); } }; private AtomicBoolean mSendingPgpMessage = new AtomicBoolean(false); private OnEditorActionListener mEditorActionListener = (v, actionId, event) -> { if (actionId == EditorInfo.IME_ACTION_SEND) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null && imm.isFullscreenMode()) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } sendMessage(); return true; } else { return false; } }; private OnClickListener mScrollButtonListener = new OnClickListener() { @Override public void onClick(View v) { stopScrolling(); setSelection(binding.messagesView.getCount() - 1, true); } }; private OnClickListener mSendButtonListener = new OnClickListener() { @Override public void onClick(View v) { Object tag = v.getTag(); if (tag instanceof SendButtonAction) { SendButtonAction action = (SendButtonAction) tag; switch (action) { case TAKE_PHOTO: case RECORD_VIDEO: case SEND_LOCATION: case RECORD_VOICE: case CHOOSE_PICTURE: attachFile(action.toChoice()); break; case CANCEL: if (conversation != null) { if (conversation.setCorrectingMessage(null)) { binding.textinput.setText(""); binding.textinput.append(conversation.getDraftMessage()); conversation.setDraftMessage(null); } else if (conversation.getMode() == Conversation.MODE_MULTI) { conversation.setNextCounterpart(null); } updateChatMsgHint(); updateSendButton(); updateEditablity(); } break; default: sendMessage(); } } else { sendMessage(); } } }; private int completionIndex = 0; private int lastCompletionLength = 0; private String incomplete; private int lastCompletionCursor; private boolean firstWord = false; private Message mPendingDownloadableMessage; private static ConversationFragment findConversationFragment(Activity activity) { Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment); if (fragment != null && fragment instanceof ConversationFragment) { return (ConversationFragment) fragment; } fragment = activity.getFragmentManager().findFragmentById(R.id.secondary_fragment); if (fragment != null && fragment instanceof ConversationFragment) { return (ConversationFragment) fragment; } return null; } public static void startStopPending(Activity activity) { ConversationFragment fragment = findConversationFragment(activity); if (fragment != null) { fragment.messageListAdapter.startStopPending(); } } public static void downloadFile(Activity activity, Message message) { ConversationFragment fragment = findConversationFragment(activity); if (fragment != null) { fragment.startDownloadable(message); } } public static void registerPendingMessage(Activity activity, Message message) { ConversationFragment fragment = findConversationFragment(activity); if (fragment != null) { fragment.pendingMessage.push(message); } } public static void openPendingMessage(Activity activity) { ConversationFragment fragment = findConversationFragment(activity); if (fragment != null) { Message message = fragment.pendingMessage.pop(); if (message != null) { fragment.messageListAdapter.openDownloadable(message); } } } public static Conversation getConversation(Activity activity) { return getConversation(activity, R.id.secondary_fragment); } private static Conversation getConversation(Activity activity, @IdRes int res) { final Fragment fragment = activity.getFragmentManager().findFragmentById(res); if (fragment != null && fragment instanceof ConversationFragment) { return ((ConversationFragment) fragment).getConversation(); } else { return null; } } public static ConversationFragment get(Activity activity) { FragmentManager fragmentManager = activity.getFragmentManager(); Fragment fragment = fragmentManager.findFragmentById(R.id.main_fragment); if (fragment != null && fragment instanceof ConversationFragment) { return (ConversationFragment) fragment; } else { fragment = fragmentManager.findFragmentById(R.id.secondary_fragment); return fragment != null && fragment instanceof ConversationFragment ? (ConversationFragment) fragment : null; } } public static Conversation getConversationReliable(Activity activity) { final Conversation conversation = getConversation(activity, R.id.secondary_fragment); if (conversation != null) { return conversation; } return getConversation(activity, R.id.main_fragment); } private static boolean allGranted(int[] grantResults) { for (int grantResult : grantResults) { if (grantResult != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } private static boolean writeGranted(int[] grantResults, String[] permission) { for (int i = 0; i < grantResults.length; ++i) { if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission[i])) { return grantResults[i] == PackageManager.PERMISSION_GRANTED; } } return false; } private static String getFirstDenied(int[] grantResults, String[] permissions) { for (int i = 0; i < grantResults.length; ++i) { if (grantResults[i] == PackageManager.PERMISSION_DENIED) { return permissions[i]; } } return null; } private static boolean scrolledToBottom(AbsListView listView) { final int count = listView.getCount(); if (count == 0) { return true; } else if (listView.getLastVisiblePosition() == count - 1) { final View lastChild = listView.getChildAt(listView.getChildCount() - 1); return lastChild != null && lastChild.getBottom() <= listView.getHeight(); } else { return false; } } private void toggleScrollDownButton() { toggleScrollDownButton(binding.messagesView); } private void toggleScrollDownButton(AbsListView listView) { if (conversation == null) { return; } if (scrolledToBottom(listView)) { lastMessageUuid = null; hideUnreadMessagesCount(); } else { binding.scrollToBottomButton.setEnabled(true); binding.scrollToBottomButton.show(); if (lastMessageUuid == null) { lastMessageUuid = conversation.getLatestMessage().getUuid(); } if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) > 0) { binding.unreadCountCustomView.setVisibility(View.VISIBLE); } } } private int getIndexOf(String uuid, List<Message> messages) { if (uuid == null) { return messages.size() - 1; } for (int i = 0; i < messages.size(); ++i) { if (uuid.equals(messages.get(i).getUuid())) { return i; } else { Message next = messages.get(i); while (next != null && next.wasMergedIntoPrevious()) { if (uuid.equals(next.getUuid())) { return i; } next = next.next(); } } } return -1; } private ScrollState getScrollPosition() { final ListView listView = this.binding.messagesView; if (listView.getCount() == 0 || listView.getLastVisiblePosition() == listView.getCount() - 1) { return null; } else { final int pos = listView.getFirstVisiblePosition(); final View view = listView.getChildAt(0); if (view == null) { return null; } else { return new ScrollState(pos, view.getTop()); } } } private void setScrollPosition(ScrollState scrollPosition, String lastMessageUuid) { if (scrollPosition != null) { this.lastMessageUuid = lastMessageUuid; if (lastMessageUuid != null) { binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid)); } //TODO maybe this needs a 'post' this.binding.messagesView.setSelectionFromTop(scrollPosition.position, scrollPosition.offset); toggleScrollDownButton(); } } private void attachLocationToConversation(Conversation conversation, Uri uri) { if (conversation == null) { return; } activity.xmppConnectionService.attachLocationToConversation(conversation, uri, new UiCallback<Message>() { @Override public void success(Message message) { } @Override public void error(int errorCode, Message object) { //TODO show possible pgp error } @Override public void userInputRequried(PendingIntent pi, Message object) { } }); } private void attachFileToConversation(Conversation conversation, Uri uri, String type) { if (conversation == null) { return; } final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_file), Toast.LENGTH_LONG); prepareFileToast.show(); activity.delegateUriPermissionsToService(uri); activity.xmppConnectionService.attachFileToConversation(conversation, uri, type, new UiInformableCallback<Message>() { @Override public void inform(final String text) { hidePrepareFileToast(prepareFileToast); runOnUiThread(() -> activity.replaceToast(text)); } @Override public void success(Message message) { runOnUiThread(() -> activity.hideToast()); hidePrepareFileToast(prepareFileToast); } @Override public void error(final int errorCode, Message message) { hidePrepareFileToast(prepareFileToast); runOnUiThread(() -> activity.replaceToast(getString(errorCode))); } @Override public void userInputRequried(PendingIntent pi, Message message) { hidePrepareFileToast(prepareFileToast); } }); } public void attachEditorContentToConversation(Uri uri) { mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), uri, Attachment.Type.FILE)); toggleInputMethod(); } private void attachImageToConversation(Conversation conversation, Uri uri) { if (conversation == null) { return; } final Toast prepareFileToast = Toast.makeText(getActivity(), getText(R.string.preparing_image), Toast.LENGTH_LONG); prepareFileToast.show(); activity.delegateUriPermissionsToService(uri); activity.xmppConnectionService.attachImageToConversation(conversation, uri, new UiCallback<Message>() { @Override public void userInputRequried(PendingIntent pi, Message object) { hidePrepareFileToast(prepareFileToast); } @Override public void success(Message message) { hidePrepareFileToast(prepareFileToast); } @Override public void error(final int error, Message message) { hidePrepareFileToast(prepareFileToast); activity.runOnUiThread(() -> activity.replaceToast(getString(error))); } }); } private void hidePrepareFileToast(final Toast prepareFileToast) { if (prepareFileToast != null && activity != null) { activity.runOnUiThread(prepareFileToast::cancel); } } private void sendMessage() { if (mediaPreviewAdapter.hasAttachments()) { commitAttachments(); return; } final Editable text = this.binding.textinput.getText(); final String body = text == null ? "" : text.toString(); final Conversation conversation = this.conversation; if (body.length() == 0 || conversation == null) { return; } if (conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL && trustKeysIfNeeded(REQUEST_TRUST_KEYS_TEXT)) { return; } final Message message; if (conversation.getCorrectingMessage() == null) { message = new Message(conversation, body, conversation.getNextEncryption()); if (conversation.getMode() == Conversation.MODE_MULTI) { final Jid nextCounterpart = conversation.getNextCounterpart(); if (nextCounterpart != null) { message.setCounterpart(nextCounterpart); message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(nextCounterpart)); message.setType(Message.TYPE_PRIVATE); } } } else { message = conversation.getCorrectingMessage(); message.setBody(body); message.setEdited(message.getUuid()); message.setUuid(UUID.randomUUID().toString()); } switch (conversation.getNextEncryption()) { case Message.ENCRYPTION_PGP: sendPgpMessage(message); break; default: sendMessage(message); } } protected boolean trustKeysIfNeeded(int requestCode) { AxolotlService axolotlService = conversation.getAccount().getAxolotlService(); final List<Jid> targets = axolotlService.getCryptoTargets(conversation); boolean hasUnaccepted = !conversation.getAcceptedCryptoTargets().containsAll(targets); boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty(); boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty(); boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(conversation).isEmpty(); boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets); boolean downloadInProgress = axolotlService.hasPendingKeyFetches(targets); if (hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted || downloadInProgress) { axolotlService.createSessionsIfNeeded(conversation); Intent intent = new Intent(getActivity(), TrustKeysActivity.class); String[] contacts = new String[targets.size()]; for (int i = 0; i < contacts.length; ++i) { contacts[i] = targets.get(i).toString(); } intent.putExtra("contacts", contacts); intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().asBareJid().toString()); intent.putExtra("conversation", conversation.getUuid()); startActivityForResult(intent, requestCode); return true; } else { return false; } } public void updateChatMsgHint() { final boolean multi = conversation.getMode() == Conversation.MODE_MULTI; if (conversation.getCorrectingMessage() != null) { this.binding.textinput.setHint(R.string.send_corrected_message); } else if (multi && conversation.getNextCounterpart() != null) { this.binding.textinput.setHint(getString( R.string.send_private_message_to, conversation.getNextCounterpart().getResource())); } else if (multi && !conversation.getMucOptions().participating()) { this.binding.textinput.setHint(R.string.you_are_not_participating); } else { this.binding.textinput.setHint(UIHelper.getMessageHint(getActivity(), conversation)); getActivity().invalidateOptionsMenu(); } } public void setupIme() { this.binding.textinput.refreshIme(); } private void handleActivityResult(ActivityResult activityResult) { if (activityResult.resultCode == Activity.RESULT_OK) { handlePositiveActivityResult(activityResult.requestCode, activityResult.data); } else { handleNegativeActivityResult(activityResult.requestCode); } } private void handlePositiveActivityResult(int requestCode, final Intent data) { switch (requestCode) { case REQUEST_TRUST_KEYS_TEXT: sendMessage(); break; case REQUEST_TRUST_KEYS_ATTACHMENTS: commitAttachments(); break; case ATTACHMENT_CHOICE_CHOOSE_IMAGE: final List<Attachment> imageUris = Attachment.extractAttachments(getActivity(), data, Attachment.Type.IMAGE); mediaPreviewAdapter.addMediaPreviews(imageUris); toggleInputMethod(); break; case ATTACHMENT_CHOICE_TAKE_PHOTO: final Uri takePhotoUri = pendingTakePhotoUri.pop(); if (takePhotoUri != null) { mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), takePhotoUri, Attachment.Type.IMAGE)); toggleInputMethod(); } else { Log.d(Config.LOGTAG, "lost take photo uri. unable to to attach"); } break; case ATTACHMENT_CHOICE_CHOOSE_FILE: case ATTACHMENT_CHOICE_RECORD_VIDEO: case ATTACHMENT_CHOICE_RECORD_VOICE: final Attachment.Type type = requestCode == ATTACHMENT_CHOICE_RECORD_VOICE ? Attachment.Type.RECORDING : Attachment.Type.FILE; final List<Attachment> fileUris = Attachment.extractAttachments(getActivity(), data, type); mediaPreviewAdapter.addMediaPreviews(fileUris); toggleInputMethod(); break; case ATTACHMENT_CHOICE_LOCATION: double latitude = data.getDoubleExtra("latitude", 0); double longitude = data.getDoubleExtra("longitude", 0); Uri geo = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude)); mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), geo, Attachment.Type.LOCATION)); toggleInputMethod(); break; case REQUEST_INVITE_TO_CONVERSATION: XmppActivity.ConferenceInvite invite = XmppActivity.ConferenceInvite.parse(data); if (invite != null) { if (invite.execute(activity)) { activity.mToast = Toast.makeText(activity, R.string.creating_conference, Toast.LENGTH_LONG); activity.mToast.show(); } } break; } } private void commitAttachments() { if (conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL && trustKeysIfNeeded(REQUEST_TRUST_KEYS_ATTACHMENTS)) { return; } final List<Attachment> attachments = mediaPreviewAdapter.getAttachments(); final PresenceSelector.OnPresenceSelected callback = () -> { for (Iterator<Attachment> i = attachments.iterator(); i.hasNext(); i.remove()) { final Attachment attachment = i.next(); if (attachment.getType() == Attachment.Type.LOCATION) { attachLocationToConversation(conversation, attachment.getUri()); } else if (attachment.getType() == Attachment.Type.IMAGE) { Log.d(Config.LOGTAG, "ConversationsActivity.commitAttachments() - attaching image to conversations. CHOOSE_IMAGE"); attachImageToConversation(conversation, attachment.getUri()); } else { Log.d(Config.LOGTAG, "ConversationsActivity.commitAttachments() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE/RECORD_VIDEO"); attachFileToConversation(conversation, attachment.getUri(), attachment.getMime()); } } mediaPreviewAdapter.notifyDataSetChanged(); toggleInputMethod(); }; if (conversation == null || conversation.getMode() == Conversation.MODE_MULTI || FileBackend.allFilesUnderSize(getActivity(), attachments, getMaxHttpUploadSize(conversation))) { callback.onPresenceSelected(); } else { activity.selectPresence(conversation, callback); } } public void toggleInputMethod() { boolean hasAttachments = mediaPreviewAdapter.hasAttachments(); binding.textinput.setVisibility(hasAttachments ? View.GONE : View.VISIBLE); binding.mediaPreview.setVisibility(hasAttachments ? View.VISIBLE : View.GONE); updateSendButton(); } private void handleNegativeActivityResult(int requestCode) { switch (requestCode) { case ATTACHMENT_CHOICE_TAKE_PHOTO: if (pendingTakePhotoUri.clear()) { Log.d(Config.LOGTAG, "cleared pending photo uri after negative activity result"); } break; } } @Override public void onActivityResult(int requestCode, int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); ActivityResult activityResult = ActivityResult.of(requestCode, resultCode, data); if (activity != null && activity.xmppConnectionService != null) { handleActivityResult(activityResult); } else { this.postponedActivityResult.push(activityResult); } } public void unblockConversation(final Blockable conversation) { activity.xmppConnectionService.sendUnblockRequest(conversation); } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d(Config.LOGTAG, "ConversationFragment.onAttach()"); if (activity instanceof ConversationsActivity) { this.activity = (ConversationsActivity) activity; } else { throw new IllegalStateException("Trying to attach fragment to activity that is not the ConversationsActivity"); } } @Override public void onDetach() { super.onDetach(); this.activity = null; //TODO maybe not a good idea since some callbacks really need it } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) { menuInflater.inflate(R.menu.fragment_conversation, menu); final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details); final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details); final MenuItem menuInviteContact = menu.findItem(R.id.action_invite); final MenuItem menuMute = menu.findItem(R.id.action_mute); final MenuItem menuUnmute = menu.findItem(R.id.action_unmute); if (conversation != null) { if (conversation.getMode() == Conversation.MODE_MULTI) { menuContactDetails.setVisible(false); menuInviteContact.setVisible(conversation.getMucOptions().canInvite()); } else { menuContactDetails.setVisible(!this.conversation.withSelf()); menuMucDetails.setVisible(false); final XmppConnectionService service = activity.xmppConnectionService; menuInviteContact.setVisible(service != null && service.findConferenceServer(conversation.getAccount()) != null); } if (conversation.isMuted()) { menuMute.setVisible(false); } else { menuUnmute.setVisible(false); } ConversationMenuConfigurator.configureAttachmentMenu(conversation, menu); ConversationMenuConfigurator.configureEncryptionMenu(conversation, menu); } super.onCreateOptionsMenu(menu, menuInflater); } @Override public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { this.binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false); binding.getRoot().setOnClickListener(null); //TODO why the fuck did we do this? binding.textinput.addTextChangedListener(new StylingHelper.MessageEditorStyler(binding.textinput)); binding.textinput.setOnEditorActionListener(mEditorActionListener); binding.textinput.setRichContentListener(new String[]{"image/*"}, mEditorContentListener); binding.textSendButton.setOnClickListener(this.mSendButtonListener); binding.scrollToBottomButton.setOnClickListener(this.mScrollButtonListener); binding.messagesView.setOnScrollListener(mOnScrollListener); binding.messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL); mediaPreviewAdapter = new MediaPreviewAdapter(this); binding.mediaPreview.setAdapter(mediaPreviewAdapter); messageListAdapter = new MessageAdapter((XmppActivity) getActivity(), this.messageList); messageListAdapter.setOnContactPictureClicked(message -> { String fingerprint; if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) { fingerprint = "pgp"; } else { fingerprint = message.getFingerprint(); } final boolean received = message.getStatus() <= Message.STATUS_RECEIVED; if (received) { if (message.getConversation() instanceof Conversation && message.getConversation().getMode() == Conversation.MODE_MULTI) { Jid tcp = message.getTrueCounterpart(); Jid user = message.getCounterpart(); if (user != null && !user.isBareJid()) { final MucOptions mucOptions = ((Conversation) message.getConversation()).getMucOptions(); if (mucOptions.participating() || ((Conversation) message.getConversation()).getNextCounterpart() != null) { if (!mucOptions.isUserInRoom(user) && mucOptions.findUserByRealJid(tcp == null ? null : tcp.asBareJid()) == null) { Toast.makeText(getActivity(), activity.getString(R.string.user_has_left_conference, user.getResource()), Toast.LENGTH_SHORT).show(); } highlightInConference(user.getResource()); } else { Toast.makeText(getActivity(), R.string.you_are_not_participating, Toast.LENGTH_SHORT).show(); } } return; } else { if (!message.getContact().isSelf()) { activity.switchToContactDetails(message.getContact(), fingerprint); return; } } } activity.switchToAccount(message.getConversation().getAccount(), fingerprint); }); messageListAdapter.setOnContactPictureLongClicked((v, message) -> { if (message.getStatus() <= Message.STATUS_RECEIVED) { if (message.getConversation().getMode() == Conversation.MODE_MULTI) { Jid tcp = message.getTrueCounterpart(); Jid cp = message.getCounterpart(); if (cp != null && !cp.isBareJid()) { User userByRealJid = tcp != null ? conversation.getMucOptions().findOrCreateUserByRealJid(tcp, cp) : null; final User user = userByRealJid != null ? userByRealJid : conversation.getMucOptions().findUserByFullJid(cp); final PopupMenu popupMenu = new PopupMenu(getActivity(), v); popupMenu.inflate(R.menu.muc_details_context); final Menu menu = popupMenu.getMenu(); MucDetailsContextMenuHelper.configureMucDetailsContextMenu(activity, menu, conversation, user); popupMenu.setOnMenuItemClickListener(menuItem -> MucDetailsContextMenuHelper.onContextItemSelected(menuItem, user, conversation, activity)); popupMenu.show(); } } } else { activity.showQrCode(conversation.getAccount().getShareableUri()); } }); messageListAdapter.setOnQuoteListener(this::quoteText); binding.messagesView.setAdapter(messageListAdapter); registerForContextMenu(binding.messagesView); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { this.binding.textinput.setCustomInsertionActionModeCallback(new EditMessageActionModeCallback(this.binding.textinput)); } return binding.getRoot(); } private void quoteText(String text) { if (binding.textinput.isEnabled()) { binding.textinput.insertAsQuote(text); binding.textinput.requestFocus(); InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null) { inputMethodManager.showSoftInput(binding.textinput, InputMethodManager.SHOW_IMPLICIT); } } } private void quoteMessage(Message message) { quoteText(MessageUtils.prepareQuote(message)); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { synchronized (this.messageList) { super.onCreateContextMenu(menu, v, menuInfo); AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo; this.selectedMessage = this.messageList.get(acmi.position); populateContextMenu(menu); } } private void populateContextMenu(ContextMenu menu) { final Message m = this.selectedMessage; final Transferable t = m.getTransferable(); Message relevantForCorrection = m; while (relevantForCorrection.mergeable(relevantForCorrection.next())) { relevantForCorrection = relevantForCorrection.next(); } if (m.getType() != Message.TYPE_STATUS) { if (m.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE) { return; } final boolean deleted = t != null && t instanceof TransferablePlaceholder; final boolean encrypted = m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED || m.getEncryption() == Message.ENCRYPTION_PGP; final boolean receiving = m.getStatus() == Message.STATUS_RECEIVED && (t instanceof JingleConnection || t instanceof HttpDownloadConnection); activity.getMenuInflater().inflate(R.menu.message_context, menu); menu.setHeaderTitle(R.string.message_options); MenuItem copyMessage = menu.findItem(R.id.copy_message); MenuItem copyLink = menu.findItem(R.id.copy_link); MenuItem quoteMessage = menu.findItem(R.id.quote_message); MenuItem retryDecryption = menu.findItem(R.id.retry_decryption); MenuItem correctMessage = menu.findItem(R.id.correct_message); MenuItem shareWith = menu.findItem(R.id.share_with); MenuItem sendAgain = menu.findItem(R.id.send_again); MenuItem copyUrl = menu.findItem(R.id.copy_url); MenuItem downloadFile = menu.findItem(R.id.download_file); MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission); MenuItem deleteFile = menu.findItem(R.id.delete_file); MenuItem showErrorMessage = menu.findItem(R.id.show_error_message); if (!m.isFileOrImage() && !encrypted && !m.isGeoUri() && !m.treatAsDownloadable()) { copyMessage.setVisible(true); quoteMessage.setVisible(MessageUtils.prepareQuote(m).length() > 0); String body = m.getMergedBody().toString(); if (ShareUtil.containsXmppUri(body)) { copyLink.setTitle(R.string.copy_jabber_id); copyLink.setVisible(true); } else if (Patterns.AUTOLINK_WEB_URL.matcher(body).find()) { copyLink.setVisible(true); } } if (m.getEncryption() == Message.ENCRYPTION_DECRYPTION_FAILED) { retryDecryption.setVisible(true); } if (relevantForCorrection.getType() == Message.TYPE_TEXT && relevantForCorrection.isLastCorrectableMessage() && m.getConversation() instanceof Conversation && (((Conversation) m.getConversation()).getMucOptions().nonanonymous() || m.getConversation().getMode() == Conversation.MODE_SINGLE)) { correctMessage.setVisible(true); } if ((m.isFileOrImage() && !deleted && !receiving) || (m.getType() == Message.TYPE_TEXT && !m.treatAsDownloadable())) { shareWith.setVisible(true); } if (m.getStatus() == Message.STATUS_SEND_FAILED) { sendAgain.setVisible(true); } if (m.hasFileOnRemoteHost() || m.isGeoUri() || m.treatAsDownloadable() || t instanceof HttpDownloadConnection) { copyUrl.setVisible(true); } if (m.isFileOrImage() && deleted && m.hasFileOnRemoteHost()) { downloadFile.setVisible(true); downloadFile.setTitle(activity.getString(R.string.download_x_file, UIHelper.getFileDescriptionString(activity, m))); } final boolean waitingOfferedSending = m.getStatus() == Message.STATUS_WAITING || m.getStatus() == Message.STATUS_UNSEND || m.getStatus() == Message.STATUS_OFFERED; final boolean cancelable = (t != null && !deleted) || waitingOfferedSending && m.needsUploading(); if (cancelable) { cancelTransmission.setVisible(true); } if (m.isFileOrImage() && !deleted && !cancelable) { String path = m.getRelativeFilePath(); if (path == null || !path.startsWith("/") || FileBackend.isInDirectoryThatShouldNotBeScanned(getActivity(), path)) { deleteFile.setVisible(true); deleteFile.setTitle(activity.getString(R.string.delete_x_file, UIHelper.getFileDescriptionString(activity, m))); } } if (m.getStatus() == Message.STATUS_SEND_FAILED && m.getErrorMessage() != null && !Message.ERROR_MESSAGE_CANCELLED.equals(m.getErrorMessage())) { showErrorMessage.setVisible(true); } } } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.share_with: ShareUtil.share(activity, selectedMessage); return true; case R.id.correct_message: correctMessage(selectedMessage); return true; case R.id.copy_message: ShareUtil.copyToClipboard(activity, selectedMessage); return true; case R.id.copy_link: ShareUtil.copyLinkToClipboard(activity, selectedMessage); return true; case R.id.quote_message: quoteMessage(selectedMessage); return true; case R.id.send_again: resendMessage(selectedMessage); return true; case R.id.copy_url: ShareUtil.copyUrlToClipboard(activity, selectedMessage); return true; case R.id.download_file: startDownloadable(selectedMessage); return true; case R.id.cancel_transmission: cancelTransmission(selectedMessage); return true; case R.id.retry_decryption: retryDecryption(selectedMessage); return true; case R.id.delete_file: deleteFile(selectedMessage); return true; case R.id.show_error_message: showErrorMessage(selectedMessage); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onOptionsItemSelected(final MenuItem item) { if (MenuDoubleTabUtil.shouldIgnoreTap()) { return false; } else if (conversation == null) { return super.onOptionsItemSelected(item); } switch (item.getItemId()) { case R.id.encryption_choice_axolotl: case R.id.encryption_choice_pgp: case R.id.encryption_choice_none: handleEncryptionSelection(item); break; case R.id.attach_choose_picture: case R.id.attach_take_picture: case R.id.attach_record_video: case R.id.attach_choose_file: case R.id.attach_record_voice: case R.id.attach_location: handleAttachmentSelection(item); break; case R.id.action_archive: activity.xmppConnectionService.archiveConversation(conversation); break; case R.id.action_contact_details: activity.switchToContactDetails(conversation.getContact()); break; case R.id.action_muc_details: Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class); intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC); intent.putExtra("uuid", conversation.getUuid()); startActivity(intent); break; case R.id.action_invite: startActivityForResult(ChooseContactActivity.create(activity, conversation), REQUEST_INVITE_TO_CONVERSATION); break; case R.id.action_clear_history: clearHistoryDialog(conversation); break; case R.id.action_mute: muteConversationDialog(conversation); break; case R.id.action_unmute: unmuteConversation(conversation); break; case R.id.action_block: case R.id.action_unblock: final Activity activity = getActivity(); if (activity instanceof XmppActivity) { BlockContactDialog.show((XmppActivity) activity, conversation); } break; default: break; } return super.onOptionsItemSelected(item); } private void handleAttachmentSelection(MenuItem item) { switch (item.getItemId()) { case R.id.attach_choose_picture: attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE); break; case R.id.attach_take_picture: attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO); break; case R.id.attach_record_video: attachFile(ATTACHMENT_CHOICE_RECORD_VIDEO); break; case R.id.attach_choose_file: attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE); break; case R.id.attach_record_voice: attachFile(ATTACHMENT_CHOICE_RECORD_VOICE); break; case R.id.attach_location: attachFile(ATTACHMENT_CHOICE_LOCATION); break; } } private void handleEncryptionSelection(MenuItem item) { if (conversation == null) { return; } switch (item.getItemId()) { case R.id.encryption_choice_none: conversation.setNextEncryption(Message.ENCRYPTION_NONE); item.setChecked(true); break; case R.id.encryption_choice_pgp: if (activity.hasPgp()) { if (conversation.getAccount().getPgpSignature() != null) { conversation.setNextEncryption(Message.ENCRYPTION_PGP); item.setChecked(true); } else { activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished); } } else { activity.showInstallPgpDialog(); } break; case R.id.encryption_choice_axolotl: Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount()) + "Enabled axolotl for Contact " + conversation.getContact().getJid()); conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL); item.setChecked(true); break; default: conversation.setNextEncryption(Message.ENCRYPTION_NONE); break; } activity.xmppConnectionService.updateConversation(conversation); updateChatMsgHint(); getActivity().invalidateOptionsMenu(); activity.refreshUi(); } public void attachFile(final int attachmentChoice) { if (attachmentChoice == ATTACHMENT_CHOICE_RECORD_VOICE) { if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)) { return; } } else if (attachmentChoice == ATTACHMENT_CHOICE_TAKE_PHOTO || attachmentChoice == ATTACHMENT_CHOICE_RECORD_VIDEO) { if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) { return; } } else if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) { if (!hasPermissions(attachmentChoice, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { return; } } try { activity.getPreferences().edit() .putString(RECENTLY_USED_QUICK_ACTION, SendButtonAction.of(attachmentChoice).toString()) .apply(); } catch (IllegalArgumentException e) { //just do not save } final int encryption = conversation.getNextEncryption(); final int mode = conversation.getMode(); if (encryption == Message.ENCRYPTION_PGP) { if (activity.hasPgp()) { if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) { activity.xmppConnectionService.getPgpEngine().hasKey( conversation.getContact(), new UiCallback<Contact>() { @Override public void userInputRequried(PendingIntent pi, Contact contact) { startPendingIntent(pi, attachmentChoice); } @Override public void success(Contact contact) { selectPresenceToAttachFile(attachmentChoice); } @Override public void error(int error, Contact contact) { activity.replaceToast(getString(error)); } }); } else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) { if (!conversation.getMucOptions().everybodyHasKeys()) { Toast warning = Toast.makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG); warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0); warning.show(); } selectPresenceToAttachFile(attachmentChoice); } else { showNoPGPKeyDialog(false, (dialog, which) -> { conversation.setNextEncryption(Message.ENCRYPTION_NONE); activity.xmppConnectionService.updateConversation(conversation); selectPresenceToAttachFile(attachmentChoice); }); } } else { activity.showInstallPgpDialog(); } } else { selectPresenceToAttachFile(attachmentChoice); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { if (grantResults.length > 0) { if (allGranted(grantResults)) { if (requestCode == REQUEST_START_DOWNLOAD) { if (this.mPendingDownloadableMessage != null) { startDownloadable(this.mPendingDownloadableMessage); } } else if (requestCode == REQUEST_ADD_EDITOR_CONTENT) { if (this.mPendingEditorContent != null) { attachEditorContentToConversation(this.mPendingEditorContent); } } else { attachFile(requestCode); } } else { @StringRes int res; String firstDenied = getFirstDenied(grantResults, permissions); if (Manifest.permission.RECORD_AUDIO.equals(firstDenied)) { res = R.string.no_microphone_permission; } else if (Manifest.permission.CAMERA.equals(firstDenied)) { res = R.string.no_camera_permission; } else { res = R.string.no_storage_permission; } Toast.makeText(getActivity(), res, Toast.LENGTH_SHORT).show(); } } if (writeGranted(grantResults, permissions)) { if (activity != null && activity.xmppConnectionService != null) { activity.xmppConnectionService.restartFileObserver(); } } } public void startDownloadable(Message message) { if (!hasPermissions(REQUEST_START_DOWNLOAD, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { this.mPendingDownloadableMessage = message; return; } Transferable transferable = message.getTransferable(); if (transferable != null) { if (transferable instanceof TransferablePlaceholder && message.hasFileOnRemoteHost()) { createNewConnection(message); return; } if (!transferable.start()) { Log.d(Config.LOGTAG, "type: " + transferable.getClass().getName()); Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show(); } } else if (message.treatAsDownloadable()) { createNewConnection(message); } } private void createNewConnection(final Message message) { if (!activity.xmppConnectionService.getHttpConnectionManager().checkConnection(message)) { Toast.makeText(getActivity(), R.string.not_connected_try_again, Toast.LENGTH_SHORT).show(); return; } activity.xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true); } @SuppressLint("InflateParams") protected void clearHistoryDialog(final Conversation conversation) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getString(R.string.clear_conversation_history)); final View dialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_clear_history, null); final CheckBox endConversationCheckBox = dialogView.findViewById(R.id.end_conversation_checkbox); builder.setView(dialogView); builder.setNegativeButton(getString(R.string.cancel), null); builder.setPositiveButton(getString(R.string.confirm), (dialog, which) -> { this.activity.xmppConnectionService.clearConversationHistory(conversation); if (endConversationCheckBox.isChecked()) { this.activity.xmppConnectionService.archiveConversation(conversation); this.activity.onConversationArchived(conversation); } else { activity.onConversationsListItemUpdated(); refresh(); } }); builder.create().show(); } protected void muteConversationDialog(final Conversation conversation) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.disable_notifications); final int[] durations = getResources().getIntArray(R.array.mute_options_durations); final CharSequence[] labels = new CharSequence[durations.length]; for (int i = 0; i < durations.length; ++i) { if (durations[i] == -1) { labels[i] = getString(R.string.until_further_notice); } else { labels[i] = TimeframeUtils.resolve(activity, 1000L * durations[i]); } } builder.setItems(labels, (dialog, which) -> { final long till; if (durations[which] == -1) { till = Long.MAX_VALUE; } else { till = System.currentTimeMillis() + (durations[which] * 1000); } conversation.setMutedTill(till); activity.xmppConnectionService.updateConversation(conversation); activity.onConversationsListItemUpdated(); refresh(); getActivity().invalidateOptionsMenu(); }); builder.create().show(); } private boolean hasPermissions(int requestCode, String... permissions) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final List<String> missingPermissions = new ArrayList<>(); for (String permission : permissions) { if (Config.ONLY_INTERNAL_STORAGE && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { continue; } if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { missingPermissions.add(permission); } } if (missingPermissions.size() == 0) { return true; } else { requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), requestCode); return false; } } else { return true; } } public void unmuteConversation(final Conversation conversation) { conversation.setMutedTill(0); this.activity.xmppConnectionService.updateConversation(conversation); this.activity.onConversationsListItemUpdated(); refresh(); getActivity().invalidateOptionsMenu(); } protected void selectPresenceToAttachFile(final int attachmentChoice) { final Account account = conversation.getAccount(); final PresenceSelector.OnPresenceSelected callback = () -> { Intent intent = new Intent(); boolean chooser = false; switch (attachmentChoice) { case ATTACHMENT_CHOICE_CHOOSE_IMAGE: intent.setAction(Intent.ACTION_GET_CONTENT); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); intent.setType("image/*"); chooser = true; break; case ATTACHMENT_CHOICE_RECORD_VIDEO: intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE); break; case ATTACHMENT_CHOICE_TAKE_PHOTO: final Uri uri = activity.xmppConnectionService.getFileBackend().getTakePhotoUri(); pendingTakePhotoUri.push(uri); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); break; case ATTACHMENT_CHOICE_CHOOSE_FILE: chooser = true; intent.setType("*/*"); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setAction(Intent.ACTION_GET_CONTENT); break; case ATTACHMENT_CHOICE_RECORD_VOICE: intent = new Intent(getActivity(), RecordingActivity.class); break; case ATTACHMENT_CHOICE_LOCATION: intent = GeoHelper.getFetchIntent(activity); break; } if (intent.resolveActivity(getActivity().getPackageManager()) != null) { if (chooser) { startActivityForResult( Intent.createChooser(intent, getString(R.string.perform_action_with)), attachmentChoice); } else { startActivityForResult(intent, attachmentChoice); } } }; if (account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) { conversation.setNextCounterpart(null); callback.onPresenceSelected(); } else { activity.selectPresence(conversation, callback); } } @Override public void onResume() { super.onResume(); binding.messagesView.post(this::fireReadEvent); } private void fireReadEvent() { if (activity != null && this.conversation != null) { String uuid = getLastVisibleMessageUuid(); if (uuid != null) { activity.onConversationRead(this.conversation, uuid); } } } private String getLastVisibleMessageUuid() { if (binding == null) { return null; } synchronized (this.messageList) { int pos = binding.messagesView.getLastVisiblePosition(); if (pos >= 0) { Message message = null; for (int i = pos; i >= 0; --i) { try { message = (Message) binding.messagesView.getItemAtPosition(i); } catch (IndexOutOfBoundsException e) { //should not happen if we synchronize properly. however if that fails we just gonna try item -1 continue; } if (message.getType() != Message.TYPE_STATUS) { break; } } if (message != null) { while (message.next() != null && message.next().wasMergedIntoPrevious()) { message = message.next(); } return message.getUuid(); } } } return null; } private void showErrorMessage(final Message message) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.error_message); builder.setMessage(message.getErrorMessage()); builder.setPositiveButton(R.string.confirm, null); builder.create().show(); } private void deleteFile(final Message message) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setNegativeButton(R.string.cancel, null); builder.setTitle(R.string.delete_file_dialog); builder.setMessage(R.string.delete_file_dialog_msg); builder.setPositiveButton(R.string.confirm, (dialog, which) -> { if (activity.xmppConnectionService.getFileBackend().deleteFile(message)) { message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED)); activity.onConversationsListItemUpdated(); refresh(); } }); builder.create().show(); } private void resendMessage(final Message message) { if (message.isFileOrImage()) { if (!(message.getConversation() instanceof Conversation)) { return; } final Conversation conversation = (Conversation) message.getConversation(); DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message); if (file.exists()) { final XmppConnection xmppConnection = conversation.getAccount().getXmppConnection(); if (!message.hasFileOnRemoteHost() && xmppConnection != null && !xmppConnection.getFeatures().httpUpload(message.getFileParams().size)) { activity.selectPresence(conversation, () -> { message.setCounterpart(conversation.getNextCounterpart()); activity.xmppConnectionService.resendFailedMessages(message); new Handler().post(() -> { int size = messageList.size(); this.binding.messagesView.setSelection(size - 1); }); }); return; } } else { Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show(); message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED)); activity.onConversationsListItemUpdated(); refresh(); return; } } activity.xmppConnectionService.resendFailedMessages(message); new Handler().post(() -> { int size = messageList.size(); this.binding.messagesView.setSelection(size - 1); }); } private void cancelTransmission(Message message) { Transferable transferable = message.getTransferable(); if (transferable != null) { transferable.cancel(); } else if (message.getStatus() != Message.STATUS_RECEIVED) { activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, Message.ERROR_MESSAGE_CANCELLED); } } private void retryDecryption(Message message) { message.setEncryption(Message.ENCRYPTION_PGP); activity.onConversationsListItemUpdated(); refresh(); conversation.getAccount().getPgpDecryptionService().decrypt(message, false); } public void privateMessageWith(final Jid counterpart) { if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) { activity.xmppConnectionService.sendChatState(conversation); } this.binding.textinput.setText(""); this.conversation.setNextCounterpart(counterpart); updateChatMsgHint(); updateSendButton(); updateEditablity(); } private void correctMessage(Message message) { while (message.mergeable(message.next())) { message = message.next(); } this.conversation.setCorrectingMessage(message); final Editable editable = binding.textinput.getText(); this.conversation.setDraftMessage(editable.toString()); this.binding.textinput.setText(""); this.binding.textinput.append(message.getBody()); } private void highlightInConference(String nick) { final Editable editable = this.binding.textinput.getText(); String oldString = editable.toString().trim(); final int pos = this.binding.textinput.getSelectionStart(); if (oldString.isEmpty() || pos == 0) { editable.insert(0, nick + ": "); } else { final char before = editable.charAt(pos - 1); final char after = editable.length() > pos ? editable.charAt(pos) : '\0'; if (before == '\n') { editable.insert(pos, nick + ": "); } else { if (pos > 2 && editable.subSequence(pos - 2, pos).toString().equals(": ")) { if (NickValidityChecker.check(conversation, Arrays.asList(editable.subSequence(0, pos - 2).toString().split(", ")))) { editable.insert(pos - 2, ", " + nick); return; } } editable.insert(pos, (Character.isWhitespace(before) ? "" : " ") + nick + (Character.isWhitespace(after) ? "" : " ")); if (Character.isWhitespace(after)) { this.binding.textinput.setSelection(this.binding.textinput.getSelectionStart() + 1); } } } } @Override public void startActivityForResult(Intent intent, int requestCode) { final Activity activity = getActivity(); if (activity instanceof ConversationsActivity) { ((ConversationsActivity) activity).clearPendingViewIntent(); } super.startActivityForResult(intent, requestCode); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (conversation != null) { outState.putString(STATE_CONVERSATION_UUID, conversation.getUuid()); outState.putString(STATE_LAST_MESSAGE_UUID, lastMessageUuid); final Uri uri = pendingTakePhotoUri.peek(); if (uri != null) { outState.putString(STATE_PHOTO_URI, uri.toString()); } final ScrollState scrollState = getScrollPosition(); if (scrollState != null) { outState.putParcelable(STATE_SCROLL_POSITION, scrollState); } final ArrayList<Attachment> attachments = mediaPreviewAdapter.getAttachments(); if (attachments.size() > 0) { outState.putParcelableArrayList(STATE_MEDIA_PREVIEWS, attachments); } } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState == null) { return; } String uuid = savedInstanceState.getString(STATE_CONVERSATION_UUID); ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_MEDIA_PREVIEWS); pendingLastMessageUuid.push(savedInstanceState.getString(STATE_LAST_MESSAGE_UUID, null)); if (uuid != null) { QuickLoader.set(uuid); this.pendingConversationsUuid.push(uuid); if (attachments != null && attachments.size() > 0) { this.pendingMediaPreviews.push(attachments); } String takePhotoUri = savedInstanceState.getString(STATE_PHOTO_URI); if (takePhotoUri != null) { pendingTakePhotoUri.push(Uri.parse(takePhotoUri)); } pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION)); } } @Override public void onStart() { super.onStart(); if (this.reInitRequiredOnStart && this.conversation != null) { final Bundle extras = pendingExtras.pop(); reInit(this.conversation, extras != null); if (extras != null) { processExtras(extras); } } else if (conversation == null && activity != null && activity.xmppConnectionService != null) { final String uuid = pendingConversationsUuid.pop(); Log.d(Config.LOGTAG, "ConversationFragment.onStart() - activity was bound but no conversation loaded. uuid=" + uuid); if (uuid != null) { findAndReInitByUuidOrArchive(uuid); } } } @Override public void onStop() { super.onStop(); final Activity activity = getActivity(); messageListAdapter.unregisterListenerInAudioPlayer(); if (activity == null || !activity.isChangingConfigurations()) { hideSoftKeyboard(activity); messageListAdapter.stopAudioPlayer(); } if (this.conversation != null) { final String msg = this.binding.textinput.getText().toString(); storeNextMessage(msg); updateChatState(this.conversation, msg); this.activity.xmppConnectionService.getNotificationService().setOpenConversation(null); } this.reInitRequiredOnStart = true; } private void updateChatState(final Conversation conversation, final String msg) { ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED; Account.State status = conversation.getAccount().getStatus(); if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) { activity.xmppConnectionService.sendChatState(conversation); } } private void saveMessageDraftStopAudioPlayer() { final Conversation previousConversation = this.conversation; if (this.activity == null || this.binding == null || previousConversation == null) { return; } Log.d(Config.LOGTAG, "ConversationFragment.saveMessageDraftStopAudioPlayer()"); final String msg = this.binding.textinput.getText().toString(); storeNextMessage(msg); updateChatState(this.conversation, msg); messageListAdapter.stopAudioPlayer(); mediaPreviewAdapter.clearPreviews(); toggleInputMethod(); } public void reInit(Conversation conversation, Bundle extras) { QuickLoader.set(conversation.getUuid()); this.saveMessageDraftStopAudioPlayer(); this.clearPending(); if (this.reInit(conversation, extras != null)) { if (extras != null) { processExtras(extras); } this.reInitRequiredOnStart = false; } else { this.reInitRequiredOnStart = true; pendingExtras.push(extras); } resetUnreadMessagesCount(); } private void reInit(Conversation conversation) { reInit(conversation, false); } private boolean reInit(final Conversation conversation, final boolean hasExtras) { if (conversation == null) { return false; } this.conversation = conversation; //once we set the conversation all is good and it will automatically do the right thing in onStart() if (this.activity == null || this.binding == null) { return false; } if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) { activity.onConversationArchived(this.conversation); return false; } stopScrolling(); Log.d(Config.LOGTAG, "reInit(hasExtras=" + Boolean.toString(hasExtras) + ")"); if (this.conversation.isRead() && hasExtras) { Log.d(Config.LOGTAG, "trimming conversation"); this.conversation.trim(); } setupIme(); final boolean scrolledToBottomAndNoPending = this.scrolledToBottom() && pendingScrollState.peek() == null; this.binding.textSendButton.setContentDescription(activity.getString(R.string.send_message_to_x, conversation.getName())); this.binding.textinput.setKeyboardListener(null); this.binding.textinput.setText(""); final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating(); if (participating) { this.binding.textinput.append(this.conversation.getNextMessage()); } this.binding.textinput.setKeyboardListener(this); messageListAdapter.updatePreferences(); refresh(false); this.conversation.messagesLoaded.set(true); Log.d(Config.LOGTAG, "scrolledToBottomAndNoPending=" + Boolean.toString(scrolledToBottomAndNoPending)); if (hasExtras || scrolledToBottomAndNoPending) { resetUnreadMessagesCount(); synchronized (this.messageList) { Log.d(Config.LOGTAG, "jump to first unread message"); final Message first = conversation.getFirstUnreadMessage(); final int bottom = Math.max(0, this.messageList.size() - 1); final int pos; final boolean jumpToBottom; if (first == null) { pos = bottom; jumpToBottom = true; } else { int i = getIndexOf(first.getUuid(), this.messageList); pos = i < 0 ? bottom : i; jumpToBottom = false; } setSelection(pos, jumpToBottom); } } this.binding.messagesView.post(this::fireReadEvent); //TODO if we only do this when this fragment is running on main it won't *bing* in tablet layout which might be unnecessary since we can *see* it activity.xmppConnectionService.getNotificationService().setOpenConversation(this.conversation); return true; } private void resetUnreadMessagesCount() { lastMessageUuid = null; hideUnreadMessagesCount(); } private void hideUnreadMessagesCount() { if (this.binding == null) { return; } this.binding.scrollToBottomButton.setEnabled(false); this.binding.scrollToBottomButton.hide(); this.binding.unreadCountCustomView.setVisibility(View.GONE); } private void setSelection(int pos, boolean jumpToBottom) { ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom); this.binding.messagesView.post(() -> ListViewUtils.setSelection(this.binding.messagesView, pos, jumpToBottom)); this.binding.messagesView.post(this::fireReadEvent); } private boolean scrolledToBottom() { return this.binding != null && scrolledToBottom(this.binding.messagesView); } private void processExtras(Bundle extras) { final String downloadUuid = extras.getString(ConversationsActivity.EXTRA_DOWNLOAD_UUID); final String text = extras.getString(Intent.EXTRA_TEXT); final String nick = extras.getString(ConversationsActivity.EXTRA_NICK); final boolean asQuote = extras.getBoolean(ConversationsActivity.EXTRA_AS_QUOTE); final boolean pm = extras.getBoolean(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, false); final boolean doNotAppend = extras.getBoolean(ConversationsActivity.EXTRA_DO_NOT_APPEND, false); final List<Uri> uris = extractUris(extras); if (uris != null && uris.size() > 0) { final List<Uri> cleanedUris = cleanUris(new ArrayList<>(uris)); mediaPreviewAdapter.addMediaPreviews(Attachment.of(getActivity(), cleanedUris)); toggleInputMethod(); return; } if (nick != null) { if (pm) { Jid jid = conversation.getJid(); try { Jid next = Jid.of(jid.getLocal(), jid.getDomain(), nick); privateMessageWith(next); } catch (final IllegalArgumentException ignored) { //do nothing } } else { final MucOptions mucOptions = conversation.getMucOptions(); if (mucOptions.participating() || conversation.getNextCounterpart() != null) { highlightInConference(nick); } } } else { if (text != null && asQuote) { quoteText(text); } else { appendText(text, doNotAppend); } } final Message message = downloadUuid == null ? null : conversation.findMessageWithFileAndUuid(downloadUuid); if (message != null) { startDownloadable(message); } } private List<Uri> extractUris(Bundle extras) { final List<Uri> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM); if (uris != null) { return uris; } final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM); if (uri != null) { return Collections.singletonList(uri); } else { return null; } } private List<Uri> cleanUris(List<Uri> uris) { Iterator<Uri> iterator = uris.iterator(); while(iterator.hasNext()) { final Uri uri = iterator.next(); if (FileBackend.weOwnFile(getActivity(), uri)) { iterator.remove(); Toast.makeText(getActivity(), R.string.security_violation_not_attaching_file, Toast.LENGTH_SHORT).show(); } } return uris; } private boolean showBlockSubmenu(View view) { final Jid jid = conversation.getJid(); if (jid.getLocal() == null) { BlockContactDialog.show(activity, conversation); } else { PopupMenu popupMenu = new PopupMenu(getActivity(), view); popupMenu.inflate(R.menu.block); popupMenu.setOnMenuItemClickListener(menuItem -> { Blockable blockable; switch (menuItem.getItemId()) { case R.id.block_domain: blockable = conversation.getAccount().getRoster().getContact(Jid.ofDomain(jid.getDomain())); break; default: blockable = conversation; } BlockContactDialog.show(activity, blockable); return true; }); popupMenu.show(); } return true; } private void updateSnackBar(final Conversation conversation) { final Account account = conversation.getAccount(); final XmppConnection connection = account.getXmppConnection(); final int mode = conversation.getMode(); final Contact contact = mode == Conversation.MODE_SINGLE ? conversation.getContact() : null; if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) { return; } if (account.getStatus() == Account.State.DISABLED) { showSnackbar(R.string.this_account_is_disabled, R.string.enable, this.mEnableAccountListener); } else if (conversation.isBlocked()) { showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener); } else if (contact != null && !contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) { showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener, this.mLongPressBlockListener); } else if (contact != null && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) { showSnackbar(R.string.contact_asks_for_presence_subscription, R.string.allow, this.mAllowPresenceSubscription, this.mLongPressBlockListener); } else if (mode == Conversation.MODE_MULTI && !conversation.getMucOptions().online() && account.getStatus() == Account.State.ONLINE) { switch (conversation.getMucOptions().getError()) { case NICK_IN_USE: showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc); break; case NO_RESPONSE: showSnackbar(R.string.joining_conference, 0, null); break; case SERVER_NOT_FOUND: if (conversation.receivedMessagesCount() > 0) { showSnackbar(R.string.remote_server_not_found, R.string.try_again, joinMuc); } else { showSnackbar(R.string.remote_server_not_found, R.string.leave, leaveMuc); } break; case REMOTE_SERVER_TIMEOUT: if (conversation.receivedMessagesCount() > 0) { showSnackbar(R.string.remote_server_timeout, R.string.try_again, joinMuc); } else { showSnackbar(R.string.remote_server_timeout, R.string.leave, leaveMuc); } break; case PASSWORD_REQUIRED: showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword); break; case BANNED: showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc); break; case MEMBERS_ONLY: showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc); break; case RESOURCE_CONSTRAINT: showSnackbar(R.string.conference_resource_constraint, R.string.try_again, joinMuc); break; case KICKED: showSnackbar(R.string.conference_kicked, R.string.join, joinMuc); break; case UNKNOWN: showSnackbar(R.string.conference_unknown_error, R.string.try_again, joinMuc); break; case INVALID_NICK: showSnackbar(R.string.invalid_muc_nick, R.string.edit, clickToMuc); case SHUTDOWN: showSnackbar(R.string.conference_shutdown, R.string.try_again, joinMuc); break; case DESTROYED: showSnackbar(R.string.conference_destroyed, R.string.leave, leaveMuc); break; default: hideSnackbar(); break; } } else if (account.hasPendingPgpIntent(conversation)) { showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener); } else if (connection != null && connection.getFeatures().blocking() && conversation.countMessages() != 0 && !conversation.isBlocked() && conversation.isWithStranger()) { showSnackbar(R.string.received_message_from_stranger, R.string.block, mBlockClickListener); } else { hideSnackbar(); } } @Override public void refresh() { if (this.binding == null) { Log.d(Config.LOGTAG, "ConversationFragment.refresh() skipped updated because view binding was null"); return; } if (this.conversation != null && this.activity != null && this.activity.xmppConnectionService != null) { if (!activity.xmppConnectionService.isConversationStillOpen(this.conversation)) { activity.onConversationArchived(this.conversation); return; } } this.refresh(true); } private void refresh(boolean notifyConversationRead) { synchronized (this.messageList) { if (this.conversation != null) { conversation.populateWithMessages(this.messageList); updateSnackBar(conversation); updateStatusMessages(); if (conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid) != 0) { binding.unreadCountCustomView.setVisibility(View.VISIBLE); binding.unreadCountCustomView.setUnreadCount(conversation.getReceivedMessagesCountSinceUuid(lastMessageUuid)); } this.messageListAdapter.notifyDataSetChanged(); updateChatMsgHint(); if (notifyConversationRead && activity != null) { binding.messagesView.post(this::fireReadEvent); } updateSendButton(); updateEditablity(); activity.invalidateOptionsMenu(); } } } protected void messageSent() { mSendingPgpMessage.set(false); this.binding.textinput.setText(""); if (conversation.setCorrectingMessage(null)) { this.binding.textinput.append(conversation.getDraftMessage()); conversation.setDraftMessage(null); } storeNextMessage(); updateChatMsgHint(); SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(activity); final boolean prefScrollToBottom = p.getBoolean("scroll_to_bottom", activity.getResources().getBoolean(R.bool.scroll_to_bottom)); if (prefScrollToBottom || scrolledToBottom()) { new Handler().post(() -> { int size = messageList.size(); this.binding.messagesView.setSelection(size - 1); }); } } private boolean storeNextMessage() { return storeNextMessage(this.binding.textinput.getText().toString()); } private boolean storeNextMessage(String msg) { final boolean participating = conversation.getMode() == Conversational.MODE_SINGLE || conversation.getMucOptions().participating(); if (this.conversation.getStatus() != Conversation.STATUS_ARCHIVED && participating && this.conversation.setNextMessage(msg)) { this.activity.xmppConnectionService.updateConversation(this.conversation); return true; } return false; } public void doneSendingPgpMessage() { mSendingPgpMessage.set(false); } public long getMaxHttpUploadSize(Conversation conversation) { final XmppConnection connection = conversation.getAccount().getXmppConnection(); return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize(); } private void updateEditablity() { boolean canWrite = this.conversation.getMode() == Conversation.MODE_SINGLE || this.conversation.getMucOptions().participating() || this.conversation.getNextCounterpart() != null; this.binding.textinput.setFocusable(canWrite); this.binding.textinput.setFocusableInTouchMode(canWrite); this.binding.textSendButton.setEnabled(canWrite); this.binding.textinput.setCursorVisible(canWrite); this.binding.textinput.setEnabled(canWrite); } public void updateSendButton() { boolean hasAttachments = mediaPreviewAdapter != null && mediaPreviewAdapter.hasAttachments(); boolean useSendButtonToIndicateStatus = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("send_button_status", getResources().getBoolean(R.bool.send_button_status)); final Conversation c = this.conversation; final Presence.Status status; final String text = this.binding.textinput == null ? "" : this.binding.textinput.getText().toString(); final SendButtonAction action; if (hasAttachments) { action = SendButtonAction.TEXT; } else { action = SendButtonTool.getAction(getActivity(), c, text); } if (useSendButtonToIndicateStatus && c.getAccount().getStatus() == Account.State.ONLINE) { if (activity.xmppConnectionService != null && activity.xmppConnectionService.getMessageArchiveService().isCatchingUp(c)) { status = Presence.Status.OFFLINE; } else if (c.getMode() == Conversation.MODE_SINGLE) { status = c.getContact().getShownStatus(); } else { status = c.getMucOptions().online() ? Presence.Status.ONLINE : Presence.Status.OFFLINE; } } else { status = Presence.Status.OFFLINE; } this.binding.textSendButton.setTag(action); this.binding.textSendButton.setImageResource(SendButtonTool.getSendButtonImageResource(getActivity(), action, status)); } protected void updateDateSeparators() { synchronized (this.messageList) { DateSeparator.addAll(this.messageList); } } protected void updateStatusMessages() { updateDateSeparators(); synchronized (this.messageList) { if (showLoadMoreMessages(conversation)) { this.messageList.add(0, Message.createLoadMoreMessage(conversation)); } if (conversation.getMode() == Conversation.MODE_SINGLE) { ChatState state = conversation.getIncomingChatState(); if (state == ChatState.COMPOSING) { this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName()))); } else if (state == ChatState.PAUSED) { this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName()))); } else { for (int i = this.messageList.size() - 1; i >= 0; --i) { final Message message = this.messageList.get(i); if (message.getType() != Message.TYPE_STATUS) { if (message.getStatus() == Message.STATUS_RECEIVED) { return; } else { if (message.getStatus() == Message.STATUS_SEND_DISPLAYED) { this.messageList.add(i + 1, Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName()))); return; } } } } } } else { final MucOptions mucOptions = conversation.getMucOptions(); final List<MucOptions.User> allUsers = mucOptions.getUsers(); final Set<ReadByMarker> addedMarkers = new HashSet<>(); ChatState state = ChatState.COMPOSING; List<MucOptions.User> users = conversation.getMucOptions().getUsersWithChatState(state, 5); if (users.size() == 0) { state = ChatState.PAUSED; users = conversation.getMucOptions().getUsersWithChatState(state, 5); } if (mucOptions.isPrivateAndNonAnonymous()) { for (int i = this.messageList.size() - 1; i >= 0; --i) { final Set<ReadByMarker> markersForMessage = messageList.get(i).getReadByMarkers(); final List<MucOptions.User> shownMarkers = new ArrayList<>(); for (ReadByMarker marker : markersForMessage) { if (!ReadByMarker.contains(marker, addedMarkers)) { addedMarkers.add(marker); //may be put outside this condition. set should do dedup anyway MucOptions.User user = mucOptions.findUser(marker); if (user != null && !users.contains(user)) { shownMarkers.add(user); } } } final ReadByMarker markerForSender = ReadByMarker.from(messageList.get(i)); final Message statusMessage; final int size = shownMarkers.size(); if (size > 1) { final String body; if (size <= 4) { body = getString(R.string.contacts_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers)); } else if (ReadByMarker.allUsersRepresented(allUsers, markersForMessage, markerForSender)) { body = getString(R.string.everyone_has_read_up_to_this_point); } else { body = getString(R.string.contacts_and_n_more_have_read_up_to_this_point, UIHelper.concatNames(shownMarkers, 3), size - 3); } statusMessage = Message.createStatusMessage(conversation, body); statusMessage.setCounterparts(shownMarkers); } else if (size == 1) { statusMessage = Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, UIHelper.getDisplayName(shownMarkers.get(0)))); statusMessage.setCounterpart(shownMarkers.get(0).getFullJid()); statusMessage.setTrueCounterpart(shownMarkers.get(0).getRealJid()); } else { statusMessage = null; } if (statusMessage != null) { this.messageList.add(i + 1, statusMessage); } addedMarkers.add(markerForSender); if (ReadByMarker.allUsersRepresented(allUsers, addedMarkers)) { break; } } } if (users.size() > 0) { Message statusMessage; if (users.size() == 1) { MucOptions.User user = users.get(0); int id = state == ChatState.COMPOSING ? R.string.contact_is_typing : R.string.contact_has_stopped_typing; statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.getDisplayName(user))); statusMessage.setTrueCounterpart(user.getRealJid()); statusMessage.setCounterpart(user.getFullJid()); } else { int id = state == ChatState.COMPOSING ? R.string.contacts_are_typing : R.string.contacts_have_stopped_typing; statusMessage = Message.createStatusMessage(conversation, getString(id, UIHelper.concatNames(users))); statusMessage.setCounterparts(users); } this.messageList.add(statusMessage); } } } } private void stopScrolling() { long now = SystemClock.uptimeMillis(); MotionEvent cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0, 0, 0); binding.messagesView.dispatchTouchEvent(cancel); } private boolean showLoadMoreMessages(final Conversation c) { if (activity == null || activity.xmppConnectionService == null) { return false; } final boolean mam = hasMamSupport(c) && !c.getContact().isBlocked(); final MessageArchiveService service = activity.xmppConnectionService.getMessageArchiveService(); return mam && (c.getLastClearHistory().getTimestamp() != 0 || (c.countMessages() == 0 && c.messagesLoaded.get() && c.hasMessagesLeftOnServer() && !service.queryInProgress(c))); } private boolean hasMamSupport(final Conversation c) { if (c.getMode() == Conversation.MODE_SINGLE) { final XmppConnection connection = c.getAccount().getXmppConnection(); return connection != null && connection.getFeatures().mam(); } else { return c.getMucOptions().mamSupport(); } } protected void showSnackbar(final int message, final int action, final OnClickListener clickListener) { showSnackbar(message, action, clickListener, null); } protected void showSnackbar(final int message, final int action, final OnClickListener clickListener, final View.OnLongClickListener longClickListener) { this.binding.snackbar.setVisibility(View.VISIBLE); this.binding.snackbar.setOnClickListener(null); this.binding.snackbarMessage.setText(message); this.binding.snackbarMessage.setOnClickListener(null); this.binding.snackbarAction.setVisibility(clickListener == null ? View.GONE : View.VISIBLE); if (action != 0) { this.binding.snackbarAction.setText(action); } this.binding.snackbarAction.setOnClickListener(clickListener); this.binding.snackbarAction.setOnLongClickListener(longClickListener); } protected void hideSnackbar() { this.binding.snackbar.setVisibility(View.GONE); } protected void sendMessage(Message message) { activity.xmppConnectionService.sendMessage(message); messageSent(); } protected void sendPgpMessage(final Message message) { final XmppConnectionService xmppService = activity.xmppConnectionService; final Contact contact = message.getConversation().getContact(); if (!activity.hasPgp()) { activity.showInstallPgpDialog(); return; } if (conversation.getAccount().getPgpSignature() == null) { activity.announcePgp(conversation.getAccount(), conversation, null, activity.onOpenPGPKeyPublished); return; } if (!mSendingPgpMessage.compareAndSet(false, true)) { Log.d(Config.LOGTAG, "sending pgp message already in progress"); } if (conversation.getMode() == Conversation.MODE_SINGLE) { if (contact.getPgpKeyId() != 0) { xmppService.getPgpEngine().hasKey(contact, new UiCallback<Contact>() { @Override public void userInputRequried(PendingIntent pi, Contact contact) { startPendingIntent(pi, REQUEST_ENCRYPT_MESSAGE); } @Override public void success(Contact contact) { encryptTextMessage(message); } @Override public void error(int error, Contact contact) { activity.runOnUiThread(() -> Toast.makeText(activity, R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT ).show()); mSendingPgpMessage.set(false); } }); } else { showNoPGPKeyDialog(false, (dialog, which) -> { conversation.setNextEncryption(Message.ENCRYPTION_NONE); xmppService.updateConversation(conversation); message.setEncryption(Message.ENCRYPTION_NONE); xmppService.sendMessage(message); messageSent(); }); } } else { if (conversation.getMucOptions().pgpKeysInUse()) { if (!conversation.getMucOptions().everybodyHasKeys()) { Toast warning = Toast .makeText(getActivity(), R.string.missing_public_keys, Toast.LENGTH_LONG); warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0); warning.show(); } encryptTextMessage(message); } else { showNoPGPKeyDialog(true, (dialog, which) -> { conversation.setNextEncryption(Message.ENCRYPTION_NONE); message.setEncryption(Message.ENCRYPTION_NONE); xmppService.updateConversation(conversation); xmppService.sendMessage(message); messageSent(); }); } } } public void encryptTextMessage(Message message) { activity.xmppConnectionService.getPgpEngine().encrypt(message, new UiCallback<Message>() { @Override public void userInputRequried(PendingIntent pi, Message message) { startPendingIntent(pi, REQUEST_SEND_MESSAGE); } @Override public void success(Message message) { //TODO the following two call can be made before the callback getActivity().runOnUiThread(() -> messageSent()); } @Override public void error(final int error, Message message) { getActivity().runOnUiThread(() -> { doneSendingPgpMessage(); Toast.makeText(getActivity(), R.string.unable_to_connect_to_keychain, Toast.LENGTH_SHORT).show(); }); } }); } public void showNoPGPKeyDialog(boolean plural, DialogInterface.OnClickListener listener) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setIconAttribute(android.R.attr.alertDialogIcon); if (plural) { builder.setTitle(getString(R.string.no_pgp_keys)); builder.setMessage(getText(R.string.contacts_have_no_pgp_keys)); } else { builder.setTitle(getString(R.string.no_pgp_key)); builder.setMessage(getText(R.string.contact_has_no_pgp_key)); } builder.setNegativeButton(getString(R.string.cancel), null); builder.setPositiveButton(getString(R.string.send_unencrypted), listener); builder.create().show(); } public void appendText(String text, final boolean doNotAppend) { if (text == null) { return; } final Editable editable = this.binding.textinput.getText(); String previous = editable == null ? "" : editable.toString(); if (doNotAppend && !TextUtils.isEmpty(previous)) { Toast.makeText(getActivity(),R.string.already_drafting_message, Toast.LENGTH_LONG).show(); return; } if (UIHelper.isLastLineQuote(previous)) { text = '\n' + text; } else if (previous.length() != 0 && !Character.isWhitespace(previous.charAt(previous.length() - 1))) { text = " " + text; } this.binding.textinput.append(text); } @Override public boolean onEnterPressed() { SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getActivity()); final boolean enterIsSend = p.getBoolean("enter_is_send", getResources().getBoolean(R.bool.enter_is_send)); if (enterIsSend) { sendMessage(); return true; } else { return false; } } @Override public void onTypingStarted() { final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService; if (service == null) { return; } Account.State status = conversation.getAccount().getStatus(); if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) { service.sendChatState(conversation); } updateSendButton(); } @Override public void onTypingStopped() { final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService; if (service == null) { return; } Account.State status = conversation.getAccount().getStatus(); if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) { service.sendChatState(conversation); } } @Override public void onTextDeleted() { final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService; if (service == null) { return; } Account.State status = conversation.getAccount().getStatus(); if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) { service.sendChatState(conversation); } if (storeNextMessage()) { activity.onConversationsListItemUpdated(); } updateSendButton(); } @Override public void onTextChanged() { if (conversation != null && conversation.getCorrectingMessage() != null) { updateSendButton(); } } @Override public boolean onTabPressed(boolean repeated) { if (conversation == null || conversation.getMode() == Conversation.MODE_SINGLE) { return false; } if (repeated) { completionIndex++; } else { lastCompletionLength = 0; completionIndex = 0; final String content = this.binding.textinput.getText().toString(); lastCompletionCursor = this.binding.textinput.getSelectionEnd(); int start = lastCompletionCursor > 0 ? content.lastIndexOf(" ", lastCompletionCursor - 1) + 1 : 0; firstWord = start == 0; incomplete = content.substring(start, lastCompletionCursor); } List<String> completions = new ArrayList<>(); for (MucOptions.User user : conversation.getMucOptions().getUsers()) { String name = user.getName(); if (name != null && name.startsWith(incomplete)) { completions.add(name + (firstWord ? ": " : " ")); } } Collections.sort(completions); if (completions.size() > completionIndex) { String completion = completions.get(completionIndex).substring(incomplete.length()); this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength); this.binding.textinput.getEditableText().insert(lastCompletionCursor, completion); lastCompletionLength = completion.length(); } else { completionIndex = -1; this.binding.textinput.getEditableText().delete(lastCompletionCursor, lastCompletionCursor + lastCompletionLength); lastCompletionLength = 0; } return true; } private void startPendingIntent(PendingIntent pendingIntent, int requestCode) { try { getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, null, 0, 0, 0); } catch (final SendIntentException ignored) { } } @Override public void onBackendConnected() { Log.d(Config.LOGTAG, "ConversationFragment.onBackendConnected()"); String uuid = pendingConversationsUuid.pop(); if (uuid != null) { if (!findAndReInitByUuidOrArchive(uuid)) { return; } } else { if (!activity.xmppConnectionService.isConversationStillOpen(conversation)) { clearPending(); activity.onConversationArchived(conversation); return; } } ActivityResult activityResult = postponedActivityResult.pop(); if (activityResult != null) { handleActivityResult(activityResult); } clearPending(); } private boolean findAndReInitByUuidOrArchive(@NonNull final String uuid) { Conversation conversation = activity.xmppConnectionService.findConversationByUuid(uuid); if (conversation == null) { clearPending(); activity.onConversationArchived(null); return false; } reInit(conversation); ScrollState scrollState = pendingScrollState.pop(); String lastMessageUuid = pendingLastMessageUuid.pop(); List<Attachment> attachments = pendingMediaPreviews.pop(); if (scrollState != null) { setScrollPosition(scrollState, lastMessageUuid); } if (attachments != null && attachments.size() > 0) { Log.d(Config.LOGTAG, "had attachments on restore"); mediaPreviewAdapter.addMediaPreviews(attachments); toggleInputMethod(); } return true; } private void clearPending() { if (postponedActivityResult.clear()) { Log.e(Config.LOGTAG, "cleared pending intent with unhandled result left"); } if (pendingScrollState.clear()) { Log.e(Config.LOGTAG, "cleared scroll state"); } if (pendingTakePhotoUri.clear()) { Log.e(Config.LOGTAG, "cleared pending photo uri"); } } public Conversation getConversation() { return conversation; } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_418_0
crossvul-java_data_good_761_0
/** * Copyright (c) 2001-2019 Mathew A. Nelson and Robocode contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * https://robocode.sourceforge.io/license/epl-v10.html */ package net.sf.robocode.host.security; import net.sf.robocode.host.IHostedThread; import net.sf.robocode.host.IThreadManager; import net.sf.robocode.io.RobocodeProperties; import java.net.SocketPermission; import java.security.AccessControlException; import java.security.Permission; /** * @author Mathew A. Nelson (original) * @author Flemming N. Larsen (contributor) * @author Robert D. Maupin (contributor) * @author Pavel Savara (contributor) */ public class RobocodeSecurityManager extends SecurityManager { private final IThreadManager threadManager; public RobocodeSecurityManager(IThreadManager threadManager) { super(); this.threadManager = threadManager; ThreadGroup tg = Thread.currentThread().getThreadGroup(); while (tg != null) { threadManager.addSafeThreadGroup(tg); tg = tg.getParent(); } // We need to exercise it in order to load all used classes on this thread isSafeThread(Thread.currentThread()); if (RobocodeProperties.isSecurityOn()) { System.setSecurityManager(this); } } @Override public void checkAccess(Thread t) { if (RobocodeProperties.isSecurityOff()) { return; } Thread c = Thread.currentThread(); if (isSafeThread(c)) { return; } super.checkAccess(t); // Threads belonging to other thread groups is not allowed to access threads belonging to other thread groups // Bug fix [3021140] Possible for robot to kill other robot threads. // In the following the thread group of the current thread must be in the thread group hierarchy of the // attacker thread; otherwise an AccessControlException must be thrown. boolean found = false; ThreadGroup cg = c.getThreadGroup(); ThreadGroup tg = t.getThreadGroup(); while (tg != null) { if (tg == cg) { found = true; break; } try { tg = tg.getParent(); } catch (AccessControlException e) { // We expect an AccessControlException due to missing RuntimePermission modifyThreadGroup break; } } if (!found) { String message = "Preventing " + c.getName() + " from access to " + t.getName(); IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c); if (robotProxy != null) { robotProxy.punishSecurityViolation(message); } throw new SecurityException(message); } } @Override public void checkAccess(ThreadGroup g) { if (RobocodeProperties.isSecurityOff()) { return; } Thread c = Thread.currentThread(); if (isSafeThread(c)) { return; } super.checkAccess(g); final ThreadGroup cg = c.getThreadGroup(); if (cg == null) { // What the heck is going on here? JDK 1.3 is sending me a dead thread. // This crashes the entire jvm if I don't return here. return; } // Bug fix #382 Unable to run robocode.bat -- Access Control Exception if ("SeedGenerator Thread".equals(c.getName()) && "SeedGenerator ThreadGroup".equals(cg.getName())) { return; // The SeedGenerator might create a thread, which needs to be silently ignored } IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c); if (robotProxy == null) { throw new AccessControlException("Preventing " + c.getName() + " from access to " + g.getName()); } if (cg.activeCount() > 5) { String message = "Robots are only allowed to create up to 5 threads!"; robotProxy.punishSecurityViolation(message); throw new SecurityException(message); } } public void checkPermission(Permission perm) { if (RobocodeProperties.isSecurityOff()) { return; } Thread c = Thread.currentThread(); if (isSafeThread(c)) { return; } super.checkPermission(perm); if (perm instanceof SocketPermission) { IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c); String message = "Using socket is not allowed"; robotProxy.punishSecurityViolation(message); throw new SecurityException(message); } } private boolean isSafeThread(Thread c) { return threadManager.isSafeThread(c); } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_761_0
crossvul-java_data_good_195_6
/* * Copyright (c) 2011-2017 Contributors to the Eclipse Foundation * * 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, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.test.core; import io.netty.handler.codec.compression.DecompressionException; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http2.Http2Exception; import io.vertx.codegen.annotations.Nullable; import io.vertx.core.*; import io.vertx.core.buffer.Buffer; import io.vertx.core.dns.AddressResolverOptions; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpClientResponse; import io.vertx.core.http.HttpConnection; import io.vertx.core.http.HttpFrame; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.http.HttpVersion; import io.vertx.core.http.impl.HeadersAdaptor; import io.vertx.core.net.NetClient; import io.vertx.core.net.NetSocket; import io.vertx.core.net.SocketAddress; import io.vertx.test.netty.TestLoggerFactory; import org.junit.Assume; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.URLEncoder; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.IntStream; import static io.vertx.test.core.TestUtils.*; import static java.util.Collections.*; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public abstract class HttpTest extends HttpTestBase { @Rule public TemporaryFolder testFolder = new TemporaryFolder(); protected File testDir; @Override public void setUp() throws Exception { super.setUp(); testDir = testFolder.newFolder(); } protected HttpServerOptions createBaseServerOptions() { return new HttpServerOptions().setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST); } protected HttpClientOptions createBaseClientOptions() { return new HttpClientOptions(); } @Test public void testClientRequestArguments() throws Exception { HttpClientRequest req = client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()); assertNullPointerException(() -> req.putHeader((String) null, "someValue")); assertNullPointerException(() -> req.putHeader((CharSequence) null, "someValue")); assertNullPointerException(() -> req.putHeader("someKey", (Iterable<String>) null)); assertNullPointerException(() -> req.write((Buffer) null)); assertNullPointerException(() -> req.write((String) null)); assertNullPointerException(() -> req.write(null, "UTF-8")); assertNullPointerException(() -> req.write("someString", null)); assertNullPointerException(() -> req.end((Buffer) null)); assertNullPointerException(() -> req.end((String) null)); assertNullPointerException(() -> req.end(null, "UTF-8")); assertNullPointerException(() -> req.end("someString", null)); assertIllegalArgumentException(() -> req.setTimeout(0)); } @Test public void testClientChaining() { server.requestHandler(noOpHandler()); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()); assertTrue(req.setChunked(true) == req); assertTrue(req.sendHead() == req); assertTrue(req.write("foo", "UTF-8") == req); assertTrue(req.write("foo") == req); assertTrue(req.write(Buffer.buffer("foo")) == req); testComplete(); })); await(); } @Test public void testListenSocketAddress() { NetClient netClient = vertx.createNetClient(); server = vertx.createHttpServer().requestHandler(req -> req.response().end()); SocketAddress sockAddress = SocketAddress.inetSocketAddress(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST); server.listen(sockAddress, onSuccess(server -> { netClient.connect(sockAddress, onSuccess(sock -> { sock.handler(buf -> { assertTrue("Response is not an http 200", buf.toString("UTF-8").startsWith("HTTP/1.1 200 OK")); testComplete(); }); sock.write("GET / HTTP/1.1\r\n\r\n"); })); })); try { await(); } finally { netClient.close(); } } @Test public void testListenDomainSocketAddress() throws Exception { Vertx vx = Vertx.vertx(new VertxOptions().setPreferNativeTransport(true)); Assume.assumeTrue("Native transport must be enabled", vx.isNativeTransportEnabled()); NetClient netClient = vx.createNetClient(); HttpServer httpserver = vx.createHttpServer().requestHandler(req -> req.response().end()); File sockFile = TestUtils.tmpFile("vertx", ".sock"); SocketAddress sockAddress = SocketAddress.domainSocketAddress(sockFile.getAbsolutePath()); httpserver.listen(sockAddress, onSuccess(server -> { netClient.connect(sockAddress, onSuccess(sock -> { sock.handler(buf -> { assertTrue("Response is not an http 200", buf.toString("UTF-8").startsWith("HTTP/1.1 200 OK")); testComplete(); }); sock.write("GET / HTTP/1.1\r\n\r\n"); })); })); try { await(); } finally { vx.close(); } } @Test public void testLowerCaseHeaders() { server.requestHandler(req -> { assertEquals("foo", req.headers().get("Foo")); assertEquals("foo", req.headers().get("foo")); assertEquals("foo", req.headers().get("fOO")); assertTrue(req.headers().contains("Foo")); assertTrue(req.headers().contains("foo")); assertTrue(req.headers().contains("fOO")); req.response().putHeader("Quux", "quux"); assertEquals("quux", req.response().headers().get("Quux")); assertEquals("quux", req.response().headers().get("quux")); assertEquals("quux", req.response().headers().get("qUUX")); assertTrue(req.response().headers().contains("Quux")); assertTrue(req.response().headers().contains("quux")); assertTrue(req.response().headers().contains("qUUX")); req.response().end(); }); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertEquals("quux", resp.headers().get("Quux")); assertEquals("quux", resp.headers().get("quux")); assertEquals("quux", resp.headers().get("qUUX")); assertTrue(resp.headers().contains("Quux")); assertTrue(resp.headers().contains("quux")); assertTrue(resp.headers().contains("qUUX")); testComplete(); }); req.putHeader("Foo", "foo"); assertEquals("foo", req.headers().get("Foo")); assertEquals("foo", req.headers().get("foo")); assertEquals("foo", req.headers().get("fOO")); assertTrue(req.headers().contains("Foo")); assertTrue(req.headers().contains("foo")); assertTrue(req.headers().contains("fOO")); req.end(); })); await(); } @Test public void testServerActualPortWhenSet() { server .requestHandler(request -> { request.response().end("hello"); }) .listen(ar -> { assertEquals(ar.result().actualPort(), DEFAULT_HTTP_PORT); vertx.createHttpClient(createBaseClientOptions()).getNow(ar.result().actualPort(), DEFAULT_HTTP_HOST, "/", response -> { assertEquals(response.statusCode(), 200); response.bodyHandler(body -> { assertEquals(body.toString("UTF-8"), "hello"); testComplete(); }); }); }); await(); } @Test public void testServerActualPortWhenZero() { server = vertx.createHttpServer(createBaseServerOptions().setPort(0).setHost(DEFAULT_HTTP_HOST)); server .requestHandler(request -> { request.response().end("hello"); }) .listen(ar -> { assertTrue(ar.result().actualPort() != 0); vertx.createHttpClient(createBaseClientOptions()).getNow(ar.result().actualPort(), DEFAULT_HTTP_HOST, "/", response -> { assertEquals(response.statusCode(), 200); response.bodyHandler(body -> { assertEquals(body.toString("UTF-8"), "hello"); testComplete(); }); }); }); await(); } @Test public void testServerActualPortWhenZeroPassedInListen() { server = vertx.createHttpServer(new HttpServerOptions(createBaseServerOptions()).setHost(DEFAULT_HTTP_HOST)); server .requestHandler(request -> { request.response().end("hello"); }) .listen(0, ar -> { assertTrue(ar.result().actualPort() != 0); vertx.createHttpClient(createBaseClientOptions()).getNow(ar.result().actualPort(), DEFAULT_HTTP_HOST, "/", response -> { assertEquals(response.statusCode(), 200); response.bodyHandler(body -> { assertEquals(body.toString("UTF-8"), "hello"); testComplete(); }); }); }); await(); } @Test public void testRequestNPE() { String uri = "/some-uri?foo=bar"; TestUtils.assertNullPointerException(() -> client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, uri, null)); TestUtils.assertNullPointerException(() -> client.request((HttpMethod)null, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, uri, resp -> {})); TestUtils.assertNullPointerException(() -> client.requestAbs((HttpMethod) null, "http://someuri", resp -> { })); TestUtils.assertNullPointerException(() -> client.request(HttpMethod.GET, 8080, "localhost", "/somepath", null)); TestUtils.assertNullPointerException(() -> client.request((HttpMethod) null, 8080, "localhost", "/somepath", resp -> { })); TestUtils.assertNullPointerException(() -> client.request(HttpMethod.GET, 8080, null, "/somepath", resp -> { })); TestUtils.assertNullPointerException(() -> client.request(HttpMethod.GET, 8080, "localhost", null, resp -> { })); } @Test public void testInvalidAbsoluteURI() { try { client.requestAbs(HttpMethod.GET, "ijdijwidjqwoijd192d192192ej12d", resp -> { }).end(); fail("Should throw exception"); } catch (VertxException e) { //OK } } @Test public void testPutHeadersOnRequest() { server.requestHandler(req -> { assertEquals("bar", req.headers().get("foo")); assertEquals("bar", req.getHeader("foo")); req.response().end(); }); server.listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertEquals(200, resp.statusCode()); testComplete(); }).putHeader("foo", "bar").end(); })); await(); } @Test public void testPutHeaderReplacesPreviousHeaders() throws Exception { server.requestHandler(req -> req.response() .putHeader("Location", "http://example1.org") .putHeader("location", "http://example2.org") .end()); server.listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertEquals(singletonList("http://example2.org"), resp.headers().getAll("LocatioN")); testComplete(); }).end(); })); await(); } @Test public void testSimpleGET() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.GET, resp -> testComplete()); } @Test public void testSimplePUT() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.PUT, resp -> testComplete()); } @Test public void testSimplePOST() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.POST, resp -> testComplete()); } @Test public void testSimpleDELETE() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.DELETE, resp -> testComplete()); } @Test public void testSimpleHEAD() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.HEAD, resp -> testComplete()); } @Test public void testSimpleTRACE() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.TRACE, resp -> testComplete()); } @Test public void testSimpleCONNECT() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.CONNECT, resp -> testComplete()); } @Test public void testSimpleOPTIONS() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.OPTIONS, resp -> testComplete()); } @Test public void testSimplePATCH() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.PATCH, resp -> testComplete()); } @Test public void testSimpleGETAbsolute() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.GET, true, resp -> testComplete()); } @Test public void testEmptyPathGETAbsolute() { String uri = ""; testSimpleRequest(uri, HttpMethod.GET, true, resp -> testComplete()); } @Test public void testNoPathButQueryGETAbsolute() { String uri = "?foo=bar"; testSimpleRequest(uri, HttpMethod.GET, true, resp -> testComplete()); } @Test public void testSimplePUTAbsolute() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.PUT, true, resp -> testComplete()); } @Test public void testSimplePOSTAbsolute() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.POST, true, resp -> testComplete()); } @Test public void testSimpleDELETEAbsolute() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.DELETE, true, resp -> testComplete()); } @Test public void testSimpleHEADAbsolute() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.HEAD, true, resp -> testComplete()); } @Test public void testSimpleTRACEAbsolute() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.TRACE, true, resp -> testComplete()); } @Test public void testSimpleCONNECTAbsolute() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.CONNECT, true, resp -> testComplete()); } @Test public void testSimpleOPTIONSAbsolute() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.OPTIONS, true, resp -> testComplete()); } @Test public void testSimplePATCHAbsolute() { String uri = "/some-uri?foo=bar"; testSimpleRequest(uri, HttpMethod.PATCH, true, resp -> testComplete()); } private void testSimpleRequest(String uri, HttpMethod method, Handler<HttpClientResponse> handler) { testSimpleRequest(uri, method, false, handler); } private void testSimpleRequest(String uri, HttpMethod method, boolean absolute, Handler<HttpClientResponse> handler) { boolean ssl = this instanceof Http2Test; HttpClientRequest req; if (absolute) { req = client.requestAbs(method, (ssl ? "https://" : "http://") + DEFAULT_HTTP_HOST + ":" + DEFAULT_HTTP_PORT + uri, handler); } else { req = client.request(method, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, uri, handler); } testSimpleRequest(uri, method, req, absolute); } private void testSimpleRequest(String uri, HttpMethod method, HttpClientRequest request, boolean absolute) { int index = uri.indexOf('?'); String query; String path; if (index == -1) { path = uri; query = null; } else { path = uri.substring(0, index); query = uri.substring(index + 1); } String resource = absolute && path.isEmpty() ? "/" + path : path; server.requestHandler(req -> { String expectedPath = req.method() == HttpMethod.CONNECT && req.version() == HttpVersion.HTTP_2 ? null : resource; String expectedQuery = req.method() == HttpMethod.CONNECT && req.version() == HttpVersion.HTTP_2 ? null : query; assertEquals(expectedPath, req.path()); assertEquals(method, req.method()); assertEquals(expectedQuery, req.query()); req.response().end(); }); server.listen(onSuccess(server -> request.end())); await(); } @Test public void testServerChaining() { server.requestHandler(req -> { assertTrue(req.response().setChunked(true) == req.response()); assertTrue(req.response().write("foo", "UTF-8") == req.response()); assertTrue(req.response().write("foo") == req.response()); testComplete(); }); server.listen(onSuccess(server -> { client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()).end(); })); await(); } @Test public void testServerChainingSendFile() throws Exception { File file = setupFile("test-server-chaining.dat", "blah"); server.requestHandler(req -> { assertTrue(req.response().sendFile(file.getAbsolutePath()) == req.response()); assertTrue(req.response().ended()); file.delete(); testComplete(); }); server.listen(onSuccess(server -> { client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()).end(); })); await(); } @Test public void testResponseEndHandlers1() { waitFor(2); AtomicInteger cnt = new AtomicInteger(); server.requestHandler(req -> { req.response().headersEndHandler(v -> { // Insert another header req.response().putHeader("extraheader", "wibble"); assertEquals(0, cnt.getAndIncrement()); }); req.response().bodyEndHandler(v -> { assertEquals(0, req.response().bytesWritten()); assertEquals(1, cnt.getAndIncrement()); complete(); }); req.response().end(); }).listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> { assertEquals(200, res.statusCode()); assertEquals("wibble", res.headers().get("extraheader")); complete(); }).end(); })); await(); } @Test public void testResponseEndHandlers2() { waitFor(2); AtomicInteger cnt = new AtomicInteger(); String content = "blah"; server.requestHandler(req -> { req.response().headersEndHandler(v -> { // Insert another header req.response().putHeader("extraheader", "wibble"); assertEquals(0, cnt.getAndIncrement()); }); req.response().bodyEndHandler(v -> { assertEquals(content.length(), req.response().bytesWritten()); assertEquals(1, cnt.getAndIncrement()); complete(); }); req.response().end(content); }).listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> { assertEquals(200, res.statusCode()); assertEquals("wibble", res.headers().get("extraheader")); res.bodyHandler(buff -> { assertEquals(Buffer.buffer(content), buff); complete(); }); }).end(); })); await(); } @Test public void testResponseEndHandlersChunkedResponse() { waitFor(2); AtomicInteger cnt = new AtomicInteger(); String chunk = "blah"; int numChunks = 6; StringBuilder content = new StringBuilder(chunk.length() * numChunks); IntStream.range(0, numChunks).forEach(i -> content.append(chunk)); server.requestHandler(req -> { req.response().headersEndHandler(v -> { // Insert another header req.response().putHeader("extraheader", "wibble"); assertEquals(0, cnt.getAndIncrement()); }); req.response().bodyEndHandler(v -> { assertEquals(content.length(), req.response().bytesWritten()); assertEquals(1, cnt.getAndIncrement()); complete(); }); req.response().setChunked(true); // note that we have a -1 here because the last chunk is written via end(chunk) IntStream.range(0, numChunks - 1).forEach(x -> req.response().write(chunk)); // End with a chunk to ensure size is correctly calculated req.response().end(chunk); }).listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> { assertEquals(200, res.statusCode()); assertEquals("wibble", res.headers().get("extraheader")); res.bodyHandler(buff -> { assertEquals(Buffer.buffer(content.toString()), buff); complete(); }); }).end(); })); await(); } @Test public void testResponseEndHandlersSendFile() throws Exception { waitFor(2); AtomicInteger cnt = new AtomicInteger(); String content = "iqdioqwdqwiojqwijdwqd"; File toSend = setupFile("somefile.txt", content); server.requestHandler(req -> { req.response().headersEndHandler(v -> { // Insert another header req.response().putHeader("extraheader", "wibble"); assertEquals(0, cnt.getAndIncrement()); }); req.response().bodyEndHandler(v -> { assertEquals(content.length(), req.response().bytesWritten()); assertEquals(1, cnt.getAndIncrement()); complete(); }); req.response().sendFile(toSend.getAbsolutePath()); }).listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> { assertEquals(200, res.statusCode()); assertEquals("wibble", res.headers().get("extraheader")); res.bodyHandler(buff -> { assertEquals(Buffer.buffer(content), buff); complete(); }); }).end(); })); await(); } @Test public void testAbsoluteURI() { testURIAndPath("http://localhost:" + DEFAULT_HTTP_PORT + "/this/is/a/path/foo.html", "/this/is/a/path/foo.html"); } @Test public void testRelativeURI() { testURIAndPath("/this/is/a/path/foo.html", "/this/is/a/path/foo.html"); } @Test public void testAbsoluteURIWithHttpSchemaInQuery() { testURIAndPath("http://localhost:" + DEFAULT_HTTP_PORT + "/correct/path?url=http://localhost:8008/wrong/path", "/correct/path"); } @Test public void testRelativeURIWithHttpSchemaInQuery() { testURIAndPath("/correct/path?url=http://localhost:8008/wrong/path", "/correct/path"); } @Test public void testAbsoluteURIEmptyPath() { testURIAndPath("http://localhost:" + DEFAULT_HTTP_PORT + "/", "/"); } private void testURIAndPath(String uri, String path) { server.requestHandler(req -> { assertEquals(uri, req.uri()); assertEquals(path, req.path()); req.response().end(); }); server.listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, uri, resp -> testComplete()).end(); })); await(); } @Test public void testParamUmlauteDecoding() throws UnsupportedEncodingException { testParamDecoding("\u00e4\u00fc\u00f6"); } @Test public void testParamPlusDecoding() throws UnsupportedEncodingException { testParamDecoding("+"); } @Test public void testParamPercentDecoding() throws UnsupportedEncodingException { testParamDecoding("%"); } @Test public void testParamSpaceDecoding() throws UnsupportedEncodingException { testParamDecoding(" "); } @Test public void testParamNormalDecoding() throws UnsupportedEncodingException { testParamDecoding("hello"); } @Test public void testParamAltogetherDecoding() throws UnsupportedEncodingException { testParamDecoding("\u00e4\u00fc\u00f6+% hello"); } private void testParamDecoding(String value) throws UnsupportedEncodingException { server.requestHandler(req -> { req.setExpectMultipart(true); req.endHandler(v -> { MultiMap formAttributes = req.formAttributes(); assertEquals(value, formAttributes.get("param")); }); req.response().end(); }); String postData = "param=" + URLEncoder.encode(value,"UTF-8"); server.listen(onSuccess(server -> { client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/") .putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaders.APPLICATION_X_WWW_FORM_URLENCODED) .putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(postData.length())) .handler(resp -> { testComplete(); }) .write(postData).end(); })); await(); } @Test public void testParamsAmpersand() { testParams('&'); } @Test public void testParamsSemiColon() { testParams(';'); } private void testParams(char delim) { Map<String, String> params = genMap(10); String query = generateQueryString(params, delim); server.requestHandler(req -> { assertEquals(query, req.query()); assertEquals(params.size(), req.params().size()); for (Map.Entry<String, String> entry : req.params()) { assertEquals(entry.getValue(), params.get(entry.getKey())); } req.response().end(); }); server.listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "some-uri/?" + query, resp -> testComplete()).end(); })); await(); } @Test public void testNoParams() { server.requestHandler(req -> { assertNull(req.query()); assertTrue(req.params().isEmpty()); req.response().end(); }); server.listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete()).end(); })); await(); } @Test public void testDefaultRequestHeaders() { server.requestHandler(req -> { if (req.version() == HttpVersion.HTTP_1_1) { assertEquals(1, req.headers().size()); assertEquals("localhost:" + DEFAULT_HTTP_PORT, req.headers().get("host")); } else { assertEquals(4, req.headers().size()); assertEquals("https", req.headers().get(":scheme")); assertEquals("GET", req.headers().get(":method")); assertEquals("some-uri", req.headers().get(":path")); assertEquals("localhost:" + DEFAULT_HTTP_PORT, req.headers().get(":authority")); } req.response().end(); }); server.listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete()).end(); })); await(); } @Test public void testRequestHeadersWithCharSequence() { HashMap<CharSequence, String> headers = new HashMap<>(); headers.put(HttpHeaders.TEXT_HTML, "text/html"); headers.put(HttpHeaders.USER_AGENT, "User-Agent"); headers.put(HttpHeaders.APPLICATION_X_WWW_FORM_URLENCODED, "application/x-www-form-urlencoded"); server.requestHandler(req -> { assertTrue(headers.size() < req.headers().size()); headers.forEach((k, v) -> assertEquals(v, req.headers().get(k))); headers.forEach((k, v) -> assertEquals(v, req.getHeader(k))); req.response().end(); }); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete()); headers.forEach((k, v) -> req.headers().add(k, v)); req.end(); })); await(); } @Test public void testRequestHeadersPutAll() { testRequestHeaders(false); } @Test public void testRequestHeadersIndividually() { testRequestHeaders(true); } private void testRequestHeaders(boolean individually) { MultiMap headers = getHeaders(10); server.requestHandler(req -> { assertTrue(headers.size() < req.headers().size()); for (Map.Entry<String, String> entry : headers) { assertEquals(entry.getValue(), req.headers().get(entry.getKey())); assertEquals(entry.getValue(), req.getHeader(entry.getKey())); } req.response().end(); }); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete()); if (individually) { for (Map.Entry<String, String> header : headers) { req.headers().add(header.getKey(), header.getValue()); } } else { req.headers().setAll(headers); } req.end(); })); await(); } @Test public void testResponseHeadersPutAll() { testResponseHeaders(false); } @Test public void testResponseHeadersIndividually() { testResponseHeaders(true); } private void testResponseHeaders(boolean individually) { MultiMap headers = getHeaders(10); server.requestHandler(req -> { if (individually) { for (Map.Entry<String, String> header : headers) { req.response().headers().add(header.getKey(), header.getValue()); } } else { req.response().headers().setAll(headers); } req.response().end(); }); server.listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertTrue(headers.size() < resp.headers().size()); for (Map.Entry<String, String> entry : headers) { assertEquals(entry.getValue(), resp.headers().get(entry.getKey())); assertEquals(entry.getValue(), resp.getHeader(entry.getKey())); } testComplete(); }).end(); })); await(); } @Test public void testResponseHeadersWithCharSequence() { HashMap<CharSequence, String> headers = new HashMap<>(); headers.put(HttpHeaders.TEXT_HTML, "text/html"); headers.put(HttpHeaders.USER_AGENT, "User-Agent"); headers.put(HttpHeaders.APPLICATION_X_WWW_FORM_URLENCODED, "application/x-www-form-urlencoded"); server.requestHandler(req -> { headers.forEach((k, v) -> req.response().headers().add(k, v)); req.response().end(); }); server.listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertTrue(headers.size() < resp.headers().size()); headers.forEach((k,v) -> assertEquals(v, resp.headers().get(k))); headers.forEach((k,v) -> assertEquals(v, resp.getHeader(k))); testComplete(); }).end(); })); await(); } @Test public void testResponseMultipleSetCookieInHeader() { testResponseMultipleSetCookie(true, false); } @Test public void testResponseMultipleSetCookieInTrailer() { testResponseMultipleSetCookie(false, true); } @Test public void testResponseMultipleSetCookieInHeaderAndTrailer() { testResponseMultipleSetCookie(true, true); } private void testResponseMultipleSetCookie(boolean inHeader, boolean inTrailer) { List<String> cookies = new ArrayList<>(); server.requestHandler(req -> { if (inHeader) { List<String> headers = new ArrayList<>(); headers.add("h1=h1v1"); headers.add("h2=h2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT"); cookies.addAll(headers); req.response().headers().set("Set-Cookie", headers); } if (inTrailer) { req.response().setChunked(true); List<String> trailers = new ArrayList<>(); trailers.add("t1=t1v1"); trailers.add("t2=t2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT"); cookies.addAll(trailers); req.response().trailers().set("Set-Cookie", trailers); } req.response().end(); }); server.listen(onSuccess(server -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.endHandler(v -> { assertEquals(cookies.size(), resp.cookies().size()); for (int i = 0; i < cookies.size(); ++i) { assertEquals(cookies.get(i), resp.cookies().get(i)); } testComplete(); }); }).end(); })); await(); } @Test public void testUseRequestAfterComplete() { server.requestHandler(noOpHandler()); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()); req.end(); Buffer buff = Buffer.buffer(); assertIllegalStateException(() -> req.end()); assertIllegalStateException(() -> req.continueHandler(noOpHandler())); assertIllegalStateException(() -> req.drainHandler(noOpHandler())); assertIllegalStateException(() -> req.end("foo")); assertIllegalStateException(() -> req.end(buff)); assertIllegalStateException(() -> req.end("foo", "UTF-8")); assertIllegalStateException(() -> req.sendHead()); assertIllegalStateException(() -> req.setChunked(false)); assertIllegalStateException(() -> req.setWriteQueueMaxSize(123)); assertIllegalStateException(() -> req.write(buff)); assertIllegalStateException(() -> req.write("foo")); assertIllegalStateException(() -> req.write("foo", "UTF-8")); assertIllegalStateException(() -> req.write(buff)); assertIllegalStateException(() -> req.writeQueueFull()); testComplete(); })); await(); } @Test public void testRequestBodyBufferAtEnd() { Buffer body = TestUtils.randomBuffer(1000); server.requestHandler(req -> req.bodyHandler(buffer -> { assertEquals(body, buffer); req.response().end(); })); server.listen(onSuccess(server -> { client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete()).end(body); })); await(); } @Test public void testRequestBodyStringDefaultEncodingAtEnd() { testRequestBodyStringAtEnd(null); } @Test public void testRequestBodyStringUTF8AtEnd() { testRequestBodyStringAtEnd("UTF-8"); } @Test public void testRequestBodyStringUTF16AtEnd() { testRequestBodyStringAtEnd("UTF-16"); } private void testRequestBodyStringAtEnd(String encoding) { String body = TestUtils.randomUnicodeString(1000); Buffer bodyBuff; if (encoding == null) { bodyBuff = Buffer.buffer(body); } else { bodyBuff = Buffer.buffer(body, encoding); } server.requestHandler(req -> { req.bodyHandler(buffer -> { assertEquals(bodyBuff, buffer); testComplete(); }); }); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()); if (encoding == null) { req.end(body); } else { req.end(body, encoding); } })); await(); } @Test public void testRequestBodyWriteChunked() { testRequestBodyWrite(true); } @Test public void testRequestBodyWriteNonChunked() { testRequestBodyWrite(false); } private void testRequestBodyWrite(boolean chunked) { Buffer body = Buffer.buffer(); server.requestHandler(req -> { req.bodyHandler(buffer -> { assertEquals(body, buffer); req.response().end(); }); }); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete()); int numWrites = 10; int chunkSize = 100; if (chunked) { req.setChunked(true); } else { req.headers().set("Content-Length", String.valueOf(numWrites * chunkSize)); } for (int i = 0; i < numWrites; i++) { Buffer b = TestUtils.randomBuffer(chunkSize); body.appendBuffer(b); req.write(b); } req.end(); })); await(); } @Test public void testRequestBodyWriteStringChunkedDefaultEncoding() { testRequestBodyWriteString(true, null); } @Test public void testRequestBodyWriteStringChunkedUTF8() { testRequestBodyWriteString(true, "UTF-8"); } @Test public void testRequestBodyWriteStringChunkedUTF16() { testRequestBodyWriteString(true, "UTF-16"); } @Test public void testRequestBodyWriteStringNonChunkedDefaultEncoding() { testRequestBodyWriteString(false, null); } @Test public void testRequestBodyWriteStringNonChunkedUTF8() { testRequestBodyWriteString(false, "UTF-8"); } @Test public void testRequestBodyWriteStringNonChunkedUTF16() { testRequestBodyWriteString(false, "UTF-16"); } private void testRequestBodyWriteString(boolean chunked, String encoding) { String body = TestUtils.randomUnicodeString(1000); Buffer bodyBuff; if (encoding == null) { bodyBuff = Buffer.buffer(body); } else { bodyBuff = Buffer.buffer(body, encoding); } server.requestHandler(req -> { req.bodyHandler(buff -> { assertEquals(bodyBuff, buff); testComplete(); }); }); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()); if (chunked) { req.setChunked(true); } else { req.headers().set("Content-Length", String.valueOf(bodyBuff.length())); } if (encoding == null) { req.write(body); } else { req.write(body, encoding); } req.end(); })); await(); } @Test public void testRequestWrite() { int times = 3; Buffer chunk = TestUtils.randomBuffer(1000); server.requestHandler(req -> { req.bodyHandler(buff -> { Buffer expected = Buffer.buffer(); for (int i = 0;i < times;i++) { expected.appendBuffer(chunk); } assertEquals(expected, buff); testComplete(); }); }); server.listen(onSuccess(s -> { HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()); req.setChunked(true); int padding = 5; for (int i = 0;i < times;i++) { Buffer paddedChunk = TestUtils.leftPad(padding, chunk); assertEquals(paddedChunk.getByteBuf().readerIndex(), padding); req.write(paddedChunk); } req.end(); })); await(); } @Test public void testConnectWithoutResponseHandler() throws Exception { try { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).end(); fail(); } catch (IllegalStateException expected) { } try { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).end("whatever"); fail(); } catch (IllegalStateException expected) { } try { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).end("whatever", "UTF-8"); fail(); } catch (IllegalStateException expected) { } try { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).end(Buffer.buffer("whatever")); fail(); } catch (IllegalStateException expected) { } try { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).sendHead(); fail(); } catch (IllegalStateException expected) { } try { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).write(Buffer.buffer("whatever")); fail(); } catch (IllegalStateException expected) { } try { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).write("whatever"); fail(); } catch (IllegalStateException expected) { } try { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI).write("whatever", "UTF-8"); fail(); } catch (IllegalStateException expected) { } } @Test public void testClientExceptionHandlerCalledWhenFailingToConnect() throws Exception { client.request(HttpMethod.GET, 9998, "255.255.255.255", DEFAULT_TEST_URI, resp -> fail("Connect should not be called")). exceptionHandler(error -> testComplete()). endHandler(done -> fail()). end(); await(); } @Test public void testClientExceptionHandlerCalledWhenServerTerminatesConnection() throws Exception { int numReqs = 10; CountDownLatch latch = new CountDownLatch(numReqs); server.requestHandler(request -> { request.response().close(); }).listen(DEFAULT_HTTP_PORT, onSuccess(s -> { // Exception handler should be called for any requests in the pipeline if connection is closed for (int i = 0; i < numReqs; i++) { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> fail("Connect should not be called")). exceptionHandler(error -> latch.countDown()).endHandler(done -> fail()).end(); } })); awaitLatch(latch); } @Test public void testClientExceptionHandlerCalledWhenServerTerminatesConnectionAfterPartialResponse() throws Exception { server.requestHandler(request -> { //Write partial response then close connection before completing it request.response().setChunked(true).write("foo").close(); }).listen(DEFAULT_HTTP_PORT, onSuccess(s -> { // Exception handler should be called for any requests in the pipeline if connection is closed client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> resp.exceptionHandler(t -> testComplete())).exceptionHandler(error -> fail()).end(); })); await(); } @Test public void testClientExceptionHandlerCalledWhenExceptionOnDataHandler() throws Exception { server.requestHandler(request -> { request.response().end("foo"); }).listen(DEFAULT_HTTP_PORT, onSuccess(s -> { // Exception handler should be called for any exceptions in the data handler client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.handler(data -> { throw new RuntimeException("should be caught"); }); resp.exceptionHandler(t -> testComplete()); }).exceptionHandler(error -> fail()).end(); })); await(); } @Test public void testClientExceptionHandlerCalledWhenExceptionOnBodyHandler() throws Exception { server.requestHandler(request -> { request.response().end("foo"); }).listen(DEFAULT_HTTP_PORT, onSuccess(s -> { // Exception handler should be called for any exceptions in the data handler client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.bodyHandler(data -> { throw new RuntimeException("should be caught"); }); resp.exceptionHandler(t -> testComplete()); }).exceptionHandler(error -> fail()).end(); })); await(); } @Test public void testNoExceptionHandlerCalledWhenResponseReceivedOK() throws Exception { server.requestHandler(request -> { request.response().end(); }).listen(DEFAULT_HTTP_PORT, onSuccess(s -> { client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.endHandler(v -> { vertx.setTimer(100, tid -> testComplete()); }); resp.exceptionHandler(t -> { fail("Should not be called"); }); }).exceptionHandler(t -> { fail("Should not be called"); }).end(); })); await(); } @Test public void testServerExceptionHandlerOnClose() { vertx.createHttpServer().requestHandler(req -> { HttpServerResponse resp = req.response(); AtomicInteger reqExceptionHandlerCount = new AtomicInteger(); AtomicInteger respExceptionHandlerCount = new AtomicInteger(); AtomicInteger respEndHandlerCount = new AtomicInteger(); req.exceptionHandler(err -> { assertEquals(1, reqExceptionHandlerCount.incrementAndGet()); assertEquals(0, respExceptionHandlerCount.get()); assertEquals(0, respEndHandlerCount.get()); assertTrue(resp.closed()); assertFalse(resp.ended()); try { resp.end(); } catch (IllegalStateException ignore) { // Expected } }); resp.exceptionHandler(err -> { assertEquals(1, reqExceptionHandlerCount.get()); assertEquals(1, respExceptionHandlerCount.incrementAndGet()); assertEquals(0, respEndHandlerCount.get()); }); resp.endHandler(v -> { assertEquals(1, reqExceptionHandlerCount.get()); assertEquals(1, respExceptionHandlerCount.get()); assertEquals(1, respEndHandlerCount.incrementAndGet()); }); req.connection().closeHandler(v -> { assertEquals(1, reqExceptionHandlerCount.get()); assertEquals(1, respExceptionHandlerCount.get()); assertEquals(1, respEndHandlerCount.get()); testComplete(); }); }).listen(DEFAULT_HTTP_PORT, ar -> { HttpClient client = vertx.createHttpClient(); HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somerui", handler -> { }).setChunked(true); req.sendHead(v -> { req.connection().close(); }); }); await(); } @Test public void testClientRequestExceptionHandlerCalledWhenConnectionClosed() throws Exception { server.requestHandler(req -> { req.handler(buff -> { req.connection().close(); }); }); startServer(); HttpClientRequest req = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { resp.handler(chunk -> { resp.request().connection().close(); }); }).setChunked(true); req.exceptionHandler(err -> { testComplete(); }); req.write("chunk"); await(); } @Test public void testClientResponseExceptionHandlerCalledWhenConnectionClosed() throws Exception { AtomicReference<HttpConnection> conn = new AtomicReference<>(); server.requestHandler(req -> { conn.set(req.connection()); req.response().setChunked(true).write("chunk"); }); startServer(); client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { resp.handler(buff -> { conn.get().close(); }); resp.exceptionHandler(err -> { testComplete(); }); }); await(); } @Test public void testDefaultStatus() { testStatusCode(-1, null); } @Test public void testDefaultOther() { // Doesn't really matter which one we choose testStatusCode(405, null); } @Test public void testOverrideStatusMessage() { testStatusCode(404, "some message"); } @Test public void testOverrideDefaultStatusMessage() { testStatusCode(-1, "some other message"); } private void testStatusCode(int code, String statusMessage) { server.requestHandler(req -> { if (code != -1) { req.response().setStatusCode(code); } if (statusMessage != null) { req.response().setStatusMessage(statusMessage); } req.response().end(); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { int theCode; if (code == -1) { // Default code - 200 assertEquals(200, resp.statusCode()); theCode = 200; } else { theCode = code; } if (statusMessage != null && resp.version() != HttpVersion.HTTP_2) { assertEquals(statusMessage, resp.statusMessage()); } else { assertEquals(HttpResponseStatus.valueOf(theCode).reasonPhrase(), resp.statusMessage()); } testComplete(); }).end(); })); await(); } @Test public void testResponseTrailersPutAll() { testResponseTrailers(false); } @Test public void testResponseTrailersPutIndividually() { testResponseTrailers(true); } private void testResponseTrailers(boolean individually) { MultiMap trailers = getHeaders(10); server.requestHandler(req -> { req.response().setChunked(true); if (individually) { for (Map.Entry<String, String> header : trailers) { req.response().trailers().add(header.getKey(), header.getValue()); } } else { req.response().trailers().setAll(trailers); } req.response().end(); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.endHandler(v -> { assertEquals(trailers.size(), resp.trailers().size()); for (Map.Entry<String, String> entry : trailers) { assertEquals(entry.getValue(), resp.trailers().get(entry.getKey())); assertEquals(entry.getValue(), resp.getTrailer(entry.getKey())); } testComplete(); }); }).end(); })); await(); } @Test public void testResponseNoTrailers() { server.requestHandler(req -> { req.response().setChunked(true); req.response().end(); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.endHandler(v -> { assertTrue(resp.trailers().isEmpty()); testComplete(); }); }).end(); })); await(); } @Test public void testUseResponseAfterComplete() throws Exception { server.requestHandler(req -> { HttpServerResponse resp = req.response(); assertFalse(resp.ended()); resp.end(); assertTrue(resp.ended()); checkHttpServerResponse(resp); testComplete(); }); startServer(); client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()); await(); } private void checkHttpServerResponse(HttpServerResponse resp) { Buffer buff = Buffer.buffer(); assertIllegalStateException(() -> resp.drainHandler(noOpHandler())); assertIllegalStateException(() -> resp.end()); assertIllegalStateException(() -> resp.end("foo")); assertIllegalStateException(() -> resp.end(buff)); assertIllegalStateException(() -> resp.end("foo", "UTF-8")); assertIllegalStateException(() -> resp.exceptionHandler(noOpHandler())); assertIllegalStateException(() -> resp.setChunked(false)); assertIllegalStateException(() -> resp.setWriteQueueMaxSize(123)); assertIllegalStateException(() -> resp.write(buff)); assertIllegalStateException(() -> resp.write("foo")); assertIllegalStateException(() -> resp.write("foo", "UTF-8")); assertIllegalStateException(() -> resp.write(buff)); assertIllegalStateException(() -> resp.writeQueueFull()); assertIllegalStateException(() -> resp.sendFile("asokdasokd")); } @Test public void testResponseBodyBufferAtEnd() { Buffer body = TestUtils.randomBuffer(1000); server.requestHandler(req -> { req.response().end(body); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.bodyHandler(buff -> { assertEquals(body, buff); testComplete(); }); }).end(); })); await(); } @Test public void testResponseBodyWriteChunked() { testResponseBodyWrite(true); } @Test public void testResponseBodyWriteNonChunked() { testResponseBodyWrite(false); } private void testResponseBodyWrite(boolean chunked) { Buffer body = Buffer.buffer(); int numWrites = 10; int chunkSize = 100; server.requestHandler(req -> { assertFalse(req.response().headWritten()); if (chunked) { req.response().setChunked(true); } else { req.response().headers().set("Content-Length", String.valueOf(numWrites * chunkSize)); } assertFalse(req.response().headWritten()); for (int i = 0; i < numWrites; i++) { Buffer b = TestUtils.randomBuffer(chunkSize); body.appendBuffer(b); req.response().write(b); assertTrue(req.response().headWritten()); } req.response().end(); assertTrue(req.response().headWritten()); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.bodyHandler(buff -> { assertEquals(body, buff); testComplete(); }); }).end(); })); await(); } @Test public void testResponseBodyWriteStringChunkedDefaultEncoding() { testResponseBodyWriteString(true, null); } @Test public void testResponseBodyWriteStringChunkedUTF8() { testResponseBodyWriteString(true, "UTF-8"); } @Test public void testResponseBodyWriteStringChunkedUTF16() { testResponseBodyWriteString(true, "UTF-16"); } @Test public void testResponseBodyWriteStringNonChunkedDefaultEncoding() { testResponseBodyWriteString(false, null); } @Test public void testResponseBodyWriteStringNonChunkedUTF8() { testResponseBodyWriteString(false, "UTF-8"); } @Test public void testResponseBodyWriteStringNonChunkedUTF16() { testResponseBodyWriteString(false, "UTF-16"); } private void testResponseBodyWriteString(boolean chunked, String encoding) { String body = TestUtils.randomUnicodeString(1000); Buffer bodyBuff; if (encoding == null) { bodyBuff = Buffer.buffer(body); } else { bodyBuff = Buffer.buffer(body, encoding); } server.requestHandler(req -> { if (chunked) { req.response().setChunked(true); } else { req.response().headers().set("Content-Length", String.valueOf(bodyBuff.length())); } if (encoding == null) { req.response().write(body); } else { req.response().write(body, encoding); } req.response().end(); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.bodyHandler(buff -> { assertEquals(bodyBuff, buff); testComplete(); }); }).end(); })); await(); } @Test public void testResponseWrite() { Buffer body = TestUtils.randomBuffer(1000); server.requestHandler(req -> { req.response().setChunked(true); req.response().write(body); req.response().end(); }); server.listen(onSuccess(s -> { client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.bodyHandler(buff -> { assertEquals(body, buff); testComplete(); }); }).end(); })); await(); } @Test public void testSendFile() throws Exception { String content = TestUtils.randomUnicodeString(10000); sendFile("test-send-file.html", content, false); } @Test public void testSendFileWithHandler() throws Exception { String content = TestUtils.randomUnicodeString(10000); sendFile("test-send-file.html", content, true); } private void sendFile(String fileName, String contentExpected, boolean handler) throws Exception { File fileToSend = setupFile(fileName, contentExpected); CountDownLatch latch; if (handler) { latch = new CountDownLatch(2); } else { latch = new CountDownLatch(1); } server.requestHandler(req -> { if (handler) { Handler<AsyncResult<Void>> completionHandler = onSuccess(v -> latch.countDown()); req.response().sendFile(fileToSend.getAbsolutePath(), completionHandler); } else { req.response().sendFile(fileToSend.getAbsolutePath()); } }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertEquals(200, resp.statusCode()); assertEquals("text/html", resp.headers().get("Content-Type")); resp.bodyHandler(buff -> { assertEquals(contentExpected, buff.toString()); assertEquals(fileToSend.length(), Long.parseLong(resp.headers().get("content-length"))); latch.countDown(); }); }).end(); })); assertTrue("Timed out waiting for test to complete.", latch.await(10, TimeUnit.SECONDS)); testComplete(); } @Test public void testSendNonExistingFile() throws Exception { server.requestHandler(req -> { final Context ctx = vertx.getOrCreateContext(); req.response().sendFile("/not/existing/path", event -> { assertEquals(ctx, vertx.getOrCreateContext()); if (event.failed()) { req.response().end("failed"); } }); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.bodyHandler(buff -> { assertEquals("failed", buff.toString()); testComplete(); }); }).end(); })); await(); } @Test public void testSendFileOverrideHeaders() throws Exception { String content = TestUtils.randomUnicodeString(10000); File file = setupFile("test-send-file.html", content); server.requestHandler(req -> { req.response().putHeader("Content-Type", "wibble"); req.response().sendFile(file.getAbsolutePath()); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertEquals(file.length(), Long.parseLong(resp.headers().get("content-length"))); assertEquals("wibble", resp.headers().get("content-type")); resp.bodyHandler(buff -> { assertEquals(content, buff.toString()); file.delete(); testComplete(); }); }).end(); })); await(); } @Test public void testSendFileNotFound() throws Exception { server.requestHandler(req -> { req.response().putHeader("Content-Type", "wibble"); req.response().sendFile("nosuchfile.html"); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { fail("Should not receive response"); }).end(); vertx.setTimer(100, tid -> testComplete()); })); await(); } @Test public void testSendFileNotFoundWithHandler() throws Exception { server.requestHandler(req -> { req.response().putHeader("Content-Type", "wibble"); req.response().sendFile("nosuchfile.html", onFailure(t -> { assertTrue(t instanceof FileNotFoundException); testComplete(); })); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { fail("Should not receive response"); }).end(); })); await(); } @Test public void testSendFileDirectoryWithHandler() throws Exception { File dir = testFolder.newFolder(); server.requestHandler(req -> { req.response().putHeader("Content-Type", "wibble"); req.response().sendFile(dir.getAbsolutePath(), onFailure(t -> { assertTrue(t instanceof FileNotFoundException); testComplete(); })); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { fail("Should not receive response"); }).end(); })); await(); } @Test public void testSendOpenRangeFileFromClasspath() { vertx.createHttpServer(new HttpServerOptions().setPort(8080)).requestHandler(res -> { res.response().sendFile("webroot/somefile.html", 6); }).listen(onSuccess(res -> { vertx.createHttpClient(new HttpClientOptions()).request(HttpMethod.GET, 8080, "localhost", "/", resp -> { resp.bodyHandler(buff -> { assertTrue(buff.toString().startsWith("<body>blah</body></html>")); testComplete(); }); }).end(); })); await(); } @Test public void testSendRangeFileFromClasspath() { vertx.createHttpServer(new HttpServerOptions().setPort(8080)).requestHandler(res -> { res.response().sendFile("webroot/somefile.html", 6, 6); }).listen(onSuccess(res -> { vertx.createHttpClient(new HttpClientOptions()).request(HttpMethod.GET, 8080, "localhost", "/", resp -> { resp.bodyHandler(buff -> { assertEquals("<body>", buff.toString()); testComplete(); }); }).end(); })); await(); } @Test public void test100ContinueHandledAutomatically() throws Exception { Buffer toSend = TestUtils.randomBuffer(1000); server.requestHandler(req -> { req.bodyHandler(data -> { assertEquals(toSend, data); req.response().end(); }); }); server.listen(onSuccess(s -> { HttpClientRequest req = client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.endHandler(v -> testComplete()); }); req.headers().set("Expect", "100-continue"); req.setChunked(true); req.continueHandler(v -> { req.write(toSend); req.end(); }); req.sendHead(); })); await(); } @Test public void test100ContinueHandledManually() throws Exception { server.close(); server = vertx.createHttpServer(createBaseServerOptions()); Buffer toSend = TestUtils.randomBuffer(1000); server.requestHandler(req -> { assertEquals("100-continue", req.getHeader("expect")); req.response().writeContinue(); req.bodyHandler(data -> { assertEquals(toSend, data); req.response().end(); }); }); server.listen(onSuccess(s -> { HttpClientRequest req = client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.endHandler(v -> testComplete()); }); req.headers().set("Expect", "100-continue"); req.setChunked(true); req.continueHandler(v -> { req.write(toSend); req.end(); }); req.sendHead(); })); await(); } @Test public void test100ContinueRejectedManually() throws Exception { server.close(); server = vertx.createHttpServer(createBaseServerOptions()); server.requestHandler(req -> { req.response().setStatusCode(405).end(); req.bodyHandler(data -> { fail("body should not be received"); }); }); server.listen(onSuccess(s -> { HttpClientRequest req = client.request(HttpMethod.PUT, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertEquals(405, resp.statusCode()); testComplete(); }); req.headers().set("Expect", "100-continue"); req.setChunked(true); req.continueHandler(v -> { fail("should not be called"); }); req.sendHead(); })); await(); } @Test public void testClientDrainHandler() { pausingServer(resumeFuture -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()); req.setChunked(true); assertFalse(req.writeQueueFull()); req.setWriteQueueMaxSize(1000); Buffer buff = TestUtils.randomBuffer(10000); vertx.setPeriodic(1, id -> { req.write(buff); if (req.writeQueueFull()) { vertx.cancelTimer(id); req.drainHandler(v -> { assertFalse(req.writeQueueFull()); testComplete(); }); // Tell the server to resume resumeFuture.complete(); } }); }); await(); } @Test public void testClientRequestExceptionHandlerCalledWhenExceptionOnDrainHandler() { pausingServer(resumeFuture -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()); req.setChunked(true); assertFalse(req.writeQueueFull()); req.setWriteQueueMaxSize(1000); Buffer buff = TestUtils.randomBuffer(10000); AtomicBoolean failed = new AtomicBoolean(); vertx.setPeriodic(1, id -> { req.write(buff); if (req.writeQueueFull()) { vertx.cancelTimer(id); req.drainHandler(v -> { throw new RuntimeException("error"); }) .exceptionHandler(t -> { // Called a second times when testComplete is called and close the http client if (failed.compareAndSet(false, true)) { testComplete(); } }); // Tell the server to resume resumeFuture.complete(); } }); }); await(); } private void pausingServer(Consumer<Future<Void>> consumer) { Future<Void> resumeFuture = Future.future(); server.requestHandler(req -> { req.response().setChunked(true); req.pause(); Context ctx = vertx.getOrCreateContext(); resumeFuture.setHandler(v1 -> { ctx.runOnContext(v2 -> { req.resume(); }); }); req.handler(buff -> { req.response().write(buff); }); }); server.listen(onSuccess(s -> consumer.accept(resumeFuture))); } @Test public void testServerDrainHandler() { drainingServer(resumeFuture -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.pause(); resumeFuture.setHandler(ar -> resp.resume()); }).end(); }); await(); } private void drainingServer(Consumer<Future<Void>> consumer) { Future<Void> resumeFuture = Future.future(); server.requestHandler(req -> { req.response().setChunked(true); assertFalse(req.response().writeQueueFull()); req.response().setWriteQueueMaxSize(1000); Buffer buff = TestUtils.randomBuffer(10000); //Send data until the buffer is full vertx.setPeriodic(1, id -> { req.response().write(buff); if (req.response().writeQueueFull()) { vertx.cancelTimer(id); req.response().drainHandler(v -> { assertFalse(req.response().writeQueueFull()); testComplete(); }); // Tell the client to resume resumeFuture.complete(); } }); }); server.listen(onSuccess(s -> consumer.accept(resumeFuture))); } @Test public void testConnectionErrorsGetReportedToRequest() throws InterruptedException { AtomicInteger req1Exceptions = new AtomicInteger(); AtomicInteger req2Exceptions = new AtomicInteger(); AtomicInteger req3Exceptions = new AtomicInteger(); CountDownLatch latch = new CountDownLatch(3); // This one should cause an error in the Client Exception handler, because it has no exception handler set specifically. HttpClientRequest req1 = client.request(HttpMethod.GET, 9998, DEFAULT_HTTP_HOST, "someurl1", resp -> { fail("Should never get a response on a bad port, if you see this message than you are running an http server on port 9998"); }); req1.exceptionHandler(t -> { assertEquals("More than one call to req1 exception handler was not expected", 1, req1Exceptions.incrementAndGet()); latch.countDown(); }); HttpClientRequest req2 = client.request(HttpMethod.GET, 9998, DEFAULT_HTTP_HOST, "someurl2", resp -> { fail("Should never get a response on a bad port, if you see this message than you are running an http server on port 9998"); }); req2.exceptionHandler(t -> { assertEquals("More than one call to req2 exception handler was not expected", 1, req2Exceptions.incrementAndGet()); latch.countDown(); }); HttpClientRequest req3 = client.request(HttpMethod.GET, 9998, DEFAULT_HTTP_HOST, "someurl2", resp -> { fail("Should never get a response on a bad port, if you see this message than you are running an http server on port 9998"); }); req3.exceptionHandler(t -> { assertEquals("More than one call to req2 exception handler was not expected", 1, req3Exceptions.incrementAndGet()); latch.countDown(); }); req1.end(); req2.end(); req3.end(); awaitLatch(latch); testComplete(); } @Test public void testRequestTimesoutWhenIndicatedPeriodExpiresWithoutAResponseFromRemoteServer() { server.requestHandler(noOpHandler()); // No response handler so timeout triggers AtomicBoolean failed = new AtomicBoolean(); server.listen(onSuccess(s -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { fail("End should not be called because the request should timeout"); }); req.exceptionHandler(t -> { // Catch the first, the second is going to be a connection closed exception when the // server is shutdown on testComplete if (failed.compareAndSet(false, true)) { assertTrue("Expected to end with timeout exception but ended with other exception: " + t, t instanceof TimeoutException); testComplete(); } }); req.setTimeout(1000); req.end(); })); await(); } @Test public void testRequestTimeoutCanceledWhenRequestHasAnOtherError() { AtomicReference<Throwable> exception = new AtomicReference<>(); // There is no server running, should fail to connect HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { fail("End should not be called because the request should fail to connect"); }); req.exceptionHandler(exception::set); req.setTimeout(800); req.end(); vertx.setTimer(1500, id -> { assertNotNull("Expected an exception to be set", exception.get()); assertFalse("Expected to not end with timeout exception, but did: " + exception.get(), exception.get() instanceof TimeoutException); testComplete(); }); await(); } @Test public void testRequestTimeoutCanceledWhenRequestEndsNormally() { server.requestHandler(req -> req.response().end()); server.listen(onSuccess(s -> { AtomicReference<Throwable> exception = new AtomicReference<>(); // There is no server running, should fail to connect HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, noOpHandler()); req.exceptionHandler(exception::set); req.setTimeout(500); req.end(); vertx.setTimer(1000, id -> { assertNull("Did not expect any exception", exception.get()); testComplete(); }); })); await(); } @Test public void testRequestNotReceivedIfTimedout() { server.requestHandler(req -> { vertx.setTimer(500, id -> { req.response().setStatusCode(200); req.response().end("OK"); }); }); server.listen(onSuccess(s -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> fail("Response should not be handled")); req.exceptionHandler(t -> { assertTrue("Expected to end with timeout exception but ended with other exception: " + t, t instanceof TimeoutException); //Delay a bit to let any response come back vertx.setTimer(500, id -> testComplete()); }); req.setTimeout(100); req.end(); })); await(); } @Test public void testConnectInvalidPort() { client.request(HttpMethod.GET, 9998, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> fail("Connect should not be called")). exceptionHandler(t -> testComplete()). end(); await(); } @Test public void testConnectInvalidHost() { client.request(HttpMethod.GET, 9998, "255.255.255.255", DEFAULT_TEST_URI, resp -> fail("Connect should not be called")). exceptionHandler(t -> testComplete()). end(); await(); } @Test public void testSetHandlersAfterListening() throws Exception { server.requestHandler(noOpHandler()); server.listen(onSuccess(s -> { assertIllegalStateException(() -> server.requestHandler(noOpHandler())); assertIllegalStateException(() -> server.websocketHandler(noOpHandler())); testComplete(); })); await(); } @Test public void testSetHandlersAfterListening2() throws Exception { server.requestHandler(noOpHandler()); server.listen(onSuccess(v -> testComplete())); assertIllegalStateException(() -> server.requestHandler(noOpHandler())); assertIllegalStateException(() -> server.websocketHandler(noOpHandler())); await(); } @Test public void testListenNoHandlers() throws Exception { assertIllegalStateException(() -> server.listen(ar -> { })); } @Test public void testListenNoHandlers2() throws Exception { assertIllegalStateException(() -> server.listen()); } @Test public void testListenTwice() throws Exception { server.requestHandler(noOpHandler()); server.listen(onSuccess(v -> testComplete())); assertIllegalStateException(() -> server.listen()); await(); } @Test public void testListenTwice2() throws Exception { server.requestHandler(noOpHandler()); server.listen(ar -> { assertTrue(ar.succeeded()); assertIllegalStateException(() -> server.listen()); testComplete(); }); await(); } @Test public void testHeadNoBody() { server.requestHandler(req -> { assertEquals(HttpMethod.HEAD, req.method()); // Head never contains a body but it can contain a Content-Length header // Since headers from HEAD must correspond EXACTLY with corresponding headers for GET req.response().headers().set("Content-Length", String.valueOf(41)); req.response().end(); }); server.listen(onSuccess(s -> { client.request(HttpMethod.HEAD, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertEquals(41, Integer.parseInt(resp.headers().get("Content-Length"))); resp.endHandler(v -> testComplete()); }).end(); })); await(); } @Test public void testRemoteAddress() { server.requestHandler(req -> { assertEquals("127.0.0.1", req.remoteAddress().host()); req.response().end(); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> resp.endHandler(v -> testComplete())).end(); })); await(); } @Test public void testGetAbsoluteURI() { server.requestHandler(req -> { assertEquals(req.scheme() + "://localhost:" + DEFAULT_HTTP_PORT + "/foo/bar", req.absoluteURI()); req.response().end(); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/foo/bar", resp -> resp.endHandler(v -> testComplete())).end(); })); await(); } @Test public void testListenInvalidPort() throws Exception { /* Port 7 is free for use by any application in Windows, so this test fails. */ Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows")); server.close(); server = vertx.createHttpServer(new HttpServerOptions().setPort(7)); server.requestHandler(noOpHandler()).listen(onFailure(server -> testComplete())); await(); } @Test public void testListenInvalidHost() { server.close(); server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT).setHost("iqwjdoqiwjdoiqwdiojwd")); server.requestHandler(noOpHandler()); server.listen(onFailure(s -> testComplete())); } @Test public void testPauseClientResponse() { int numWrites = 10; int numBytes = 100; server.requestHandler(req -> { req.response().setChunked(true); // Send back a big response in several chunks for (int i = 0; i < numWrites; i++) { req.response().write(TestUtils.randomBuffer(numBytes)); } req.response().end(); }); AtomicBoolean paused = new AtomicBoolean(); Buffer totBuff = Buffer.buffer(); HttpClientRequest clientRequest = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.pause(); paused.set(true); resp.handler(chunk -> { if (paused.get()) { fail("Shouldn't receive chunks when paused"); } else { totBuff.appendBuffer(chunk); } }); resp.endHandler(v -> { if (paused.get()) { fail("Shouldn't receive chunks when paused"); } else { assertEquals(numWrites * numBytes, totBuff.length()); testComplete(); } }); vertx.setTimer(500, id -> { paused.set(false); resp.resume(); }); }); server.listen(onSuccess(s -> clientRequest.end())); await(); } @Test public void testDeliverPausedBufferWhenResume() throws Exception { testDeliverPausedBufferWhenResume(block -> vertx.setTimer(10, id -> block.run())); } @Test public void testDeliverPausedBufferWhenResumeOnOtherThread() throws Exception { ExecutorService exec = Executors.newSingleThreadExecutor(); try { testDeliverPausedBufferWhenResume(block -> exec.execute(() -> { try { Thread.sleep(10); } catch (InterruptedException e) { fail(e); Thread.currentThread().interrupt(); } block.run(); })); } finally { exec.shutdown(); } } private void testDeliverPausedBufferWhenResume(Consumer<Runnable> scheduler) throws Exception { Buffer data = TestUtils.randomBuffer(2048); int num = 10; waitFor(num); List<CompletableFuture<Void>> resumes = Collections.synchronizedList(new ArrayList<>()); for (int i = 0;i < num;i++) { resumes.add(new CompletableFuture<>()); } server.requestHandler(req -> { int idx = Integer.parseInt(req.path().substring(1)); HttpServerResponse resp = req.response(); resumes.get(idx).thenAccept(v -> { resp.end(); }); resp.setChunked(true).write(data); }); startServer(); client.close(); client = vertx.createHttpClient(createBaseClientOptions().setMaxPoolSize(1).setKeepAlive(true)); for (int i = 0;i < num;i++) { int idx = i; client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/" + i, resp -> { Buffer body = Buffer.buffer(); Thread t = Thread.currentThread(); resp.handler(buff -> { assertSame(t, Thread.currentThread()); resumes.get(idx).complete(null); body.appendBuffer(buff); }); resp.endHandler(v -> { // assertEquals(data, body); complete(); }); resp.pause(); scheduler.accept(resp::resume); }).end(); } await(); } @Test public void testClearPausedBuffersWhenResponseEnds() throws Exception { Buffer data = TestUtils.randomBuffer(20); int num = 10; waitFor(num); server.requestHandler(req -> { req.response().end(data); }); startServer(); client.close(); client = vertx.createHttpClient(createBaseClientOptions().setMaxPoolSize(1).setKeepAlive(true)); for (int i = 0;i < num;i++) { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.bodyHandler(buff -> { assertEquals(data, buff); complete(); }); resp.pause(); vertx.setTimer(10, id -> { resp.resume(); }); }).end(); } await(); } @Test public void testPausedHttpServerRequest() throws Exception { CompletableFuture<Void> resumeCF = new CompletableFuture<>(); Buffer expected = Buffer.buffer(); server.requestHandler(req -> { req.pause(); AtomicBoolean paused = new AtomicBoolean(true); Buffer body = Buffer.buffer(); req.handler(buff -> { assertFalse(paused.get()); body.appendBuffer(buff); }); resumeCF.thenAccept(v -> { paused.set(false); req.resume(); }); req.endHandler(v -> { assertEquals(expected, body); req.response().end(); }); }); startServer(); HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTPS_HOST, DEFAULT_TEST_URI, resp -> { resp.endHandler(v -> { testComplete(); }); }).exceptionHandler(this::fail) .setChunked(true); while (!req.writeQueueFull()) { Buffer buff = Buffer.buffer(TestUtils.randomAlphaString(1024)); expected.appendBuffer(buff); req.write(buff); } resumeCF.complete(null); req.end(); await(); } @Test public void testPausedHttpServerRequestDuringLastChunkEndsTheRequest() throws Exception { server.requestHandler(req -> { req.handler(buff -> { assertEquals("small", buff.toString()); req.pause(); }); req.endHandler(v -> { req.response().end(); }); }); startServer(); client.close(); client = vertx.createHttpClient(createBaseClientOptions().setMaxPoolSize(1)); client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/someuri", resp -> { complete(); }).end("small"); await(); } @Test public void testFormUploadSmallFile() throws Exception { testFormUploadFile(TestUtils.randomAlphaString(100), false); } @Test public void testFormUploadLargerFile() throws Exception { testFormUploadFile(TestUtils.randomAlphaString(20000), false); } @Test public void testFormUploadSmallFileStreamToDisk() throws Exception { testFormUploadFile(TestUtils.randomAlphaString(100), true); } @Test public void testFormUploadLargerFileStreamToDisk() throws Exception { testFormUploadFile(TestUtils.randomAlphaString(20000), true); } private void testFormUploadFile(String contentStr, boolean streamToDisk) throws Exception { Buffer content = Buffer.buffer(contentStr); AtomicInteger attributeCount = new AtomicInteger(); server.requestHandler(req -> { if (req.method() == HttpMethod.POST) { assertEquals(req.path(), "/form"); req.response().setChunked(true); req.setExpectMultipart(true); assertTrue(req.isExpectMultipart()); // Now try setting again, it shouldn't have an effect req.setExpectMultipart(true); assertTrue(req.isExpectMultipart()); req.uploadHandler(upload -> { Buffer tot = Buffer.buffer(); assertEquals("file", upload.name()); assertEquals("tmp-0.txt", upload.filename()); assertEquals("image/gif", upload.contentType()); String uploadedFileName; if (!streamToDisk) { upload.handler(buffer -> tot.appendBuffer(buffer)); uploadedFileName = null; } else { uploadedFileName = new File(testDir, UUID.randomUUID().toString()).getPath(); upload.streamToFileSystem(uploadedFileName); } upload.endHandler(v -> { if (streamToDisk) { Buffer uploaded = vertx.fileSystem().readFileBlocking(uploadedFileName); assertEquals(content, uploaded); } else { assertEquals(content, tot); } assertTrue(upload.isSizeAvailable()); assertEquals(content.length(), upload.size()); }); }); req.endHandler(v -> { MultiMap attrs = req.formAttributes(); attributeCount.set(attrs.size()); req.response().end(); }); } }); server.listen(onSuccess(s -> { HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/form", resp -> { // assert the response assertEquals(200, resp.statusCode()); resp.bodyHandler(body -> { assertEquals(0, body.length()); }); assertEquals(0, attributeCount.get()); testComplete(); }); String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO"; Buffer buffer = Buffer.buffer(); String body = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" + "Content-Type: image/gif\r\n" + "\r\n" + contentStr + "\r\n" + "--" + boundary + "--\r\n"; buffer.appendString(body); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "multipart/form-data; boundary=" + boundary); req.write(buffer).end(); })); await(); } @Test public void testFormUploadAttributes() throws Exception { AtomicInteger attributeCount = new AtomicInteger(); server.requestHandler(req -> { if (req.method() == HttpMethod.POST) { assertEquals(req.path(), "/form"); req.response().setChunked(true); req.setExpectMultipart(true); req.uploadHandler(upload -> upload.handler(buffer -> { fail("Should get here"); })); req.endHandler(v -> { MultiMap attrs = req.formAttributes(); attributeCount.set(attrs.size()); assertEquals("vert x", attrs.get("framework")); assertEquals("vert x", req.getFormAttribute("framework")); assertEquals("jvm", attrs.get("runson")); assertEquals("jvm", req.getFormAttribute("runson")); req.response().end(); }); } }); server.listen(onSuccess(s -> { HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/form", resp -> { // assert the response assertEquals(200, resp.statusCode()); resp.bodyHandler(body -> { assertEquals(0, body.length()); }); assertEquals(2, attributeCount.get()); testComplete(); }); try { Buffer buffer = Buffer.buffer(); // Make sure we have one param that needs url encoding buffer.appendString("framework=" + URLEncoder.encode("vert x", "UTF-8") + "&runson=jvm", "UTF-8"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "application/x-www-form-urlencoded"); req.write(buffer).end(); } catch (UnsupportedEncodingException e) { fail(e.getMessage()); } })); await(); } @Test public void testFormUploadAttributes2() throws Exception { AtomicInteger attributeCount = new AtomicInteger(); server.requestHandler(req -> { if (req.method() == HttpMethod.POST) { assertEquals(req.path(), "/form"); req.setExpectMultipart(true); req.uploadHandler(event -> event.handler(buffer -> { fail("Should not get here"); })); req.endHandler(v -> { MultiMap attrs = req.formAttributes(); attributeCount.set(attrs.size()); assertEquals("junit-testUserAlias", attrs.get("origin")); assertEquals("admin@foo.bar", attrs.get("login")); assertEquals("admin", attrs.get("pass word")); req.response().end(); }); } }); server.listen(onSuccess(s -> { HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/form", resp -> { // assert the response assertEquals(200, resp.statusCode()); resp.bodyHandler(body -> { assertEquals(0, body.length()); }); assertEquals(3, attributeCount.get()); testComplete(); }); Buffer buffer = Buffer.buffer(); buffer.appendString("origin=junit-testUserAlias&login=admin%40foo.bar&pass+word=admin"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "application/x-www-form-urlencoded"); req.write(buffer).end(); })); await(); } @Test public void testHostHeaderOverridePossible() { server.requestHandler(req -> { assertEquals("localhost:4444", req.host()); req.response().end(); }); server.listen(onSuccess(s -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> testComplete()); req.setHost("localhost:4444"); req.end(); })); await(); } @Test public void testResponseBodyWriteFixedString() { String body = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; Buffer bodyBuff = Buffer.buffer(body); server.requestHandler(req -> { req.response().setChunked(true); req.response().write(body); req.response().end(); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.bodyHandler(buff -> { assertEquals(bodyBuff, buff); testComplete(); }); }).end(); })); await(); } @Test public void testResponseDataTimeout() { Buffer expected = TestUtils.randomBuffer(1000); server.requestHandler(req -> { req.response().setChunked(true).write(expected); }); server.listen(onSuccess(s -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI); Buffer received = Buffer.buffer(); req.handler(resp -> { req.setTimeout(500); resp.handler(received::appendBuffer); }); AtomicInteger count = new AtomicInteger(); req.exceptionHandler(t -> { if (count.getAndIncrement() == 0) { assertTrue(t instanceof TimeoutException); assertEquals(expected, received); testComplete(); } }); req.sendHead(); })); await(); } @Test public void testClientMultiThreaded() throws Exception { int numThreads = 10; Thread[] threads = new Thread[numThreads]; CountDownLatch latch = new CountDownLatch(numThreads); server.requestHandler(req -> { req.response().putHeader("count", req.headers().get("count")); req.response().end(); }).listen(ar -> { assertTrue(ar.succeeded()); for (int i = 0; i < numThreads; i++) { int index = i; threads[i] = new Thread() { public void run() { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> { assertEquals(200, res.statusCode()); assertEquals(String.valueOf(index), res.headers().get("count")); latch.countDown(); }).putHeader("count", String.valueOf(index)).end(); } }; threads[i].start(); } }); awaitLatch(latch); for (int i = 0; i < numThreads; i++) { threads[i].join(); } } @Test public void testInVerticle() throws Exception { testInVerticle(false); } private void testInVerticle(boolean worker) throws Exception { client.close(); server.close(); class MyVerticle extends AbstractVerticle { Context ctx; @Override public void start() { ctx = Vertx.currentContext(); if (worker) { assertTrue(ctx.isWorkerContext()); } else { assertTrue(ctx.isEventLoopContext()); } Thread thr = Thread.currentThread(); server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT)); server.requestHandler(req -> { req.response().end(); assertSame(ctx, Vertx.currentContext()); if (!worker) { assertSame(thr, Thread.currentThread()); } }); server.listen(ar -> { assertTrue(ar.succeeded()); assertSame(ctx, Vertx.currentContext()); if (!worker) { assertSame(thr, Thread.currentThread()); } client = vertx.createHttpClient(new HttpClientOptions()); client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/", res -> { assertSame(ctx, Vertx.currentContext()); if (!worker) { assertSame(thr, Thread.currentThread()); } assertEquals(200, res.statusCode()); testComplete(); }).end(); }); } } MyVerticle verticle = new MyVerticle(); vertx.deployVerticle(verticle, new DeploymentOptions().setWorker(worker)); await(); } @Test public void testUseInMultithreadedWorker() throws Exception { class MyVerticle extends AbstractVerticle { @Override public void start() { assertIllegalStateException(() -> server = vertx.createHttpServer(new HttpServerOptions())); assertIllegalStateException(() -> client = vertx.createHttpClient(new HttpClientOptions())); testComplete(); } } MyVerticle verticle = new MyVerticle(); vertx.deployVerticle(verticle, new DeploymentOptions().setWorker(true).setMultiThreaded(true)); await(); } @Test public void testMultipleServerClose() { this.server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT)); AtomicInteger times = new AtomicInteger(); // We assume the endHandler and the close completion handler are invoked in the same context task ThreadLocal stack = new ThreadLocal(); stack.set(true); server.requestStream().endHandler(v -> { assertNull(stack.get()); assertTrue(Vertx.currentContext().isEventLoopContext()); times.incrementAndGet(); }); server.close(ar1 -> { assertNull(stack.get()); assertTrue(Vertx.currentContext().isEventLoopContext()); server.close(ar2 -> { server.close(ar3 -> { assertEquals(1, times.get()); testComplete(); }); }); }); await(); } @Test public void testClearHandlersOnEnd() { String path = "/some/path"; server = vertx.createHttpServer(createBaseServerOptions()); server.requestHandler(req -> { req.endHandler(v -> { try { req.endHandler(null); req.exceptionHandler(null); req.handler(null); req.bodyHandler(null); req.uploadHandler(null); } catch (Exception e) { fail("Was expecting to set to null the handlers when the request is completed"); return; } HttpServerResponse resp = req.response(); resp.setStatusCode(200).end(); try { resp.endHandler(null); resp.exceptionHandler(null); resp.drainHandler(null); resp.bodyEndHandler(null); resp.closeHandler(null); resp.headersEndHandler(null); } catch (Exception e) { fail("Was expecting to set to null the handlers when the response is completed"); } }); }); server.listen(ar -> { assertTrue(ar.succeeded()); HttpClientRequest req = client.request(HttpMethod.GET, HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path); AtomicInteger count = new AtomicInteger(); req.handler(resp -> { resp.endHandler(v -> { try { resp.endHandler(null); resp.exceptionHandler(null); resp.handler(null); resp.bodyHandler(null); } catch (Exception e) { fail("Was expecting to set to null the handlers when the response is completed"); return; } if (count.incrementAndGet() == 2) { testComplete(); } }); }); req.endHandler(done -> { try { req.handler(null); req.exceptionHandler(null); req.endHandler(null); req.drainHandler(null); req.connectionHandler(null); req.continueHandler(null); } catch (Exception e) { fail("Was expecting to set to null the handlers when the response is completed"); return; } if (count.incrementAndGet() == 2) { testComplete(); } }); req.end(); }); await(); } @Test public void testSetHandlersOnEnd() throws Exception { String path = "/some/path"; server.requestHandler(req -> req.response().setStatusCode(200).end()); startServer(); HttpClientRequest req = client.request(HttpMethod.GET, HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path); req.handler(resp -> { }); req.endHandler(done -> { try { req.handler(arg -> { }); fail(); } catch (Exception ignore) { } try { req.exceptionHandler(arg -> { }); fail(); } catch (Exception ignore) { } try { req.endHandler(arg -> { }); fail(); } catch (Exception ignore) { } testComplete(); }); req.end(); await(); } @Test public void testRequestEnded() { server.requestHandler(req -> { assertFalse(req.isEnded()); req.endHandler(v -> { assertTrue(req.isEnded()); try { req.endHandler(v2 -> {}); fail("Shouldn't be able to set end handler"); } catch (IllegalStateException e) { // OK } try { req.setExpectMultipart(true); fail("Shouldn't be able to set expect multipart"); } catch (IllegalStateException e) { // OK } try { req.bodyHandler(v2 -> { }); fail("Shouldn't be able to set body handler"); } catch (IllegalStateException e) { // OK } try { req.handler(v2 -> { }); fail("Shouldn't be able to set handler"); } catch (IllegalStateException e) { // OK } req.response().setStatusCode(200).end(); }); }); server.listen(ar -> { assertTrue(ar.succeeded()); client.getNow(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/blah", resp -> { assertEquals(200, resp.statusCode()); testComplete(); }); }); await(); } @Test public void testRequestEndedNoEndHandler() { server.requestHandler(req -> { assertFalse(req.isEnded()); req.response().setStatusCode(200).end(); vertx.setTimer(500, v -> { assertTrue(req.isEnded()); try { req.endHandler(v2 -> { }); fail("Shouldn't be able to set end handler"); } catch (IllegalStateException e) { // OK } try { req.setExpectMultipart(true); fail("Shouldn't be able to set expect multipart"); } catch (IllegalStateException e) { // OK } try { req.bodyHandler(v2 -> { }); fail("Shouldn't be able to set body handler"); } catch (IllegalStateException e) { // OK } try { req.handler(v2 -> { }); fail("Shouldn't be able to set handler"); } catch (IllegalStateException e) { // OK } testComplete(); }); }); server.listen(ar -> { assertTrue(ar.succeeded()); client.getNow(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, "/blah", resp -> { assertEquals(200, resp.statusCode()); }); }); await(); } @Test public void testInMultithreadedWorker() throws Exception { vertx.deployVerticle(new AbstractVerticle() { @Override public void start() throws Exception { assertTrue(Vertx.currentContext().isWorkerContext()); assertTrue(Vertx.currentContext().isMultiThreadedWorkerContext()); assertTrue(Context.isOnWorkerThread()); try { vertx.createHttpServer(); fail("Should throw exception"); } catch (IllegalStateException e) { // OK } try { vertx.createHttpClient(); fail("Should throw exception"); } catch (IllegalStateException e) { // OK } testComplete(); } }, new DeploymentOptions().setWorker(true).setMultiThreaded(true)); await(); } @Test public void testAbsoluteURIServer() { server.close(); // Listen on all addresses server = vertx.createHttpServer(createBaseServerOptions().setHost("0.0.0.0")); server.requestHandler(req -> { String absURI = req.absoluteURI(); assertEquals(req.scheme() + "://localhost:8080/path", absURI); req.response().end(); }); server.listen(onSuccess(s -> { String host = "localhost"; String path = "/path"; int port = 8080; client.getNow(port, host, path, resp -> { assertEquals(200, resp.statusCode()); testComplete(); }); })); await(); } @Test public void testDumpManyRequestsOnQueue() throws Exception { int sendRequests = 10000; AtomicInteger receivedRequests = new AtomicInteger(); vertx.createHttpServer(createBaseServerOptions()).requestHandler(r-> { r.response().end(); if (receivedRequests.incrementAndGet() == sendRequests) { testComplete(); } }).listen(onSuccess(s -> { HttpClientOptions ops = createBaseClientOptions() .setDefaultPort(DEFAULT_HTTP_PORT) .setPipelining(true) .setKeepAlive(true); HttpClient client = vertx.createHttpClient(ops); IntStream.range(0, sendRequests).forEach(x -> client.getNow("/", r -> {})); })); await(); } @Test public void testOtherMethodWithRawMethod() throws Exception { try { client.request(HttpMethod.OTHER, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { }).end(); fail(); } catch (IllegalStateException expected) { } } @Test public void testOtherMethodRequest() throws Exception { server.requestHandler(r -> { assertEquals(HttpMethod.OTHER, r.method()); assertEquals("COPY", r.rawMethod()); r.response().end(); }).listen(onSuccess(s -> { client.request(HttpMethod.OTHER, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { testComplete(); }).setRawMethod("COPY").end(); })); await(); } @Test public void testClientConnectionHandler() throws Exception { server.requestHandler(req -> { req.response().end(); }); CountDownLatch listenLatch = new CountDownLatch(1); server.listen(onSuccess(s -> listenLatch.countDown())); awaitLatch(listenLatch); AtomicInteger status = new AtomicInteger(); HttpClientRequest req = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { assertEquals(1, status.getAndIncrement()); testComplete(); }); req.connectionHandler(conn -> { assertEquals(0, status.getAndIncrement()); }); req.end(); await(); } @Test public void testServerConnectionHandler() throws Exception { AtomicInteger status = new AtomicInteger(); AtomicReference<HttpConnection> connRef = new AtomicReference<>(); server.connectionHandler(conn -> { assertEquals(0, status.getAndIncrement()); assertNull(connRef.getAndSet(conn)); }); server.requestHandler(req -> { assertEquals(1, status.getAndIncrement()); assertSame(connRef.get(), req.connection()); req.response().end(); }); CountDownLatch listenLatch = new CountDownLatch(1); server.listen(onSuccess(s -> listenLatch.countDown())); awaitLatch(listenLatch); client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { testComplete(); }); await(); } @Test public void testClientConnectionClose() throws Exception { // Test client connection close + server close handler CountDownLatch latch = new CountDownLatch(1); server.requestHandler(req -> { AtomicInteger len = new AtomicInteger(); req.handler(buff -> { if (len.addAndGet(buff.length()) == 1024) { latch.countDown(); } }); req.connection().closeHandler(v -> { testComplete(); }); }); CountDownLatch listenLatch = new CountDownLatch(1); server.listen(onSuccess(s -> listenLatch.countDown())); awaitLatch(listenLatch); HttpClientRequest req = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { fail(); }); req.setChunked(true); req.write(TestUtils.randomBuffer(1024)); awaitLatch(latch); req.connection().close(); await(); } @Test public void testServerConnectionClose() throws Exception { // Test server connection close + client close handler server.requestHandler(req -> { req.connection().close(); }); CountDownLatch listenLatch = new CountDownLatch(1); server.listen(onSuccess(s -> listenLatch.countDown())); awaitLatch(listenLatch); HttpClientRequest req = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { fail(); }); req.connectionHandler(conn -> { conn.closeHandler(v -> { testComplete(); }); }); req.sendHead(); await(); } @Test public void testNoLogging() throws Exception { TestLoggerFactory factory = testLogging(); assertFalse(factory.hasName("io.netty.handler.codec.http2.Http2FrameLogger")); } @Test public void testServerLogging() throws Exception { server.close(); server = vertx.createHttpServer(createBaseServerOptions().setLogActivity(true)); TestLoggerFactory factory = testLogging(); if (this instanceof Http1xTest) { assertTrue(factory.hasName("io.netty.handler.logging.LoggingHandler")); } else { assertTrue(factory.hasName("io.netty.handler.codec.http2.Http2FrameLogger")); } } @Test public void testClientLogging() throws Exception { client.close(); client = vertx.createHttpClient(createBaseClientOptions().setLogActivity(true)); TestLoggerFactory factory = testLogging(); if (this instanceof Http1xTest) { assertTrue(factory.hasName("io.netty.handler.logging.LoggingHandler")); } else { assertTrue(factory.hasName("io.netty.handler.codec.http2.Http2FrameLogger")); } } @Test public void testClientLocalAddress() throws Exception { String expectedAddress = InetAddress.getLocalHost().getHostAddress(); client.close(); client = vertx.createHttpClient(createBaseClientOptions().setLocalAddress(expectedAddress)); server.requestHandler(req -> { assertEquals(expectedAddress, req.remoteAddress().host()); req.response().end(); }); startServer(); client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { assertEquals(200, resp.statusCode()); testComplete(); }); await(); } @Test public void testFollowRedirectGetOn301() throws Exception { testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 301, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected"); } @Test public void testFollowRedirectPostOn301() throws Exception { testFollowRedirect(HttpMethod.POST, HttpMethod.GET, 301, 301, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath"); } @Test public void testFollowRedirectPutOn301() throws Exception { testFollowRedirect(HttpMethod.PUT, HttpMethod.GET, 301, 301, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath"); } @Test public void testFollowRedirectGetOn302() throws Exception { testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 302, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected"); } @Test public void testFollowRedirectPostOn302() throws Exception { testFollowRedirect(HttpMethod.POST, HttpMethod.GET, 302, 302, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath"); } @Test public void testFollowRedirectPutOn302() throws Exception { testFollowRedirect(HttpMethod.PUT, HttpMethod.GET, 302, 302, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath"); } @Test public void testFollowRedirectGetOn303() throws Exception { testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 303, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected"); } @Test public void testFollowRedirectPostOn303() throws Exception { testFollowRedirect(HttpMethod.POST, HttpMethod.GET, 303, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected"); } @Test public void testFollowRedirectPutOn303() throws Exception { testFollowRedirect(HttpMethod.PUT, HttpMethod.GET, 303, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected"); } @Test public void testFollowRedirectNotOn304() throws Exception { testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 304, 304, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath"); } @Test public void testFollowRedirectGetOn307() throws Exception { testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 307, 200, 2, "http://localhost:8080/redirected", "http://localhost:8080/redirected"); } @Test public void testFollowRedirectPostOn307() throws Exception { testFollowRedirect(HttpMethod.POST, HttpMethod.POST, 307, 307, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath"); } @Test public void testFollowRedirectPutOn307() throws Exception { testFollowRedirect(HttpMethod.PUT, HttpMethod.PUT, 307, 307, 1, "http://localhost:8080/redirected", "http://localhost:8080/somepath"); } @Test public void testFollowRedirectWithRelativeLocation() throws Exception { testFollowRedirect(HttpMethod.GET, HttpMethod.GET, 301, 200, 2, "/another", "http://localhost:8080/another"); } private void testFollowRedirect( HttpMethod method, HttpMethod expectedMethod, int statusCode, int expectedStatus, int expectedRequests, String location, String expectedURI) throws Exception { String s; if (createBaseServerOptions().isSsl() && location.startsWith("http://")) { s = "https://" + location.substring("http://".length()); } else { s = location; } String t; if (createBaseServerOptions().isSsl() && expectedURI.startsWith("http://")) { t = "https://" + expectedURI.substring("http://".length()); } else { t = expectedURI; } AtomicInteger numRequests = new AtomicInteger(); server.requestHandler(req -> { HttpServerResponse resp = req.response(); if (numRequests.getAndIncrement() == 0) { resp.setStatusCode(statusCode); if (s != null) { resp.putHeader(HttpHeaders.LOCATION, s); } resp.end(); } else { assertEquals(t, req.absoluteURI()); assertEquals("foo_value", req.getHeader("foo")); assertEquals(expectedMethod, req.method()); resp.end(); } }); startServer(); client.request(method, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { assertEquals(resp.request().absoluteURI(), t); assertEquals(expectedRequests, numRequests.get()); assertEquals(expectedStatus, resp.statusCode()); testComplete(); }). putHeader("foo", "foo_value"). setFollowRedirects(true). end(); await(); } @Test public void testFollowRedirectWithBody() throws Exception { testFollowRedirectWithBody(Function.identity()); } @Test public void testFollowRedirectWithPaddedBody() throws Exception { testFollowRedirectWithBody(buff -> TestUtils.leftPad(1, buff)); } private void testFollowRedirectWithBody(Function<Buffer, Buffer> translator) throws Exception { Buffer expected = TestUtils.randomBuffer(2048); AtomicBoolean redirected = new AtomicBoolean(); server.requestHandler(req -> { if (redirected.compareAndSet(false, true)) { assertEquals(HttpMethod.PUT, req.method()); req.bodyHandler(body -> { assertEquals(body, expected); String scheme = createBaseServerOptions().isSsl() ? "https" : "http"; req.response().setStatusCode(303).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:8080/whatever").end(); }); } else { assertEquals(HttpMethod.GET, req.method()); req.response().end(); } }); startServer(); client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { assertEquals(200, resp.statusCode()); testComplete(); }).setFollowRedirects(true).end(translator.apply(expected)); await(); } @Test public void testFollowRedirectWithChunkedBody() throws Exception { Buffer buff1 = Buffer.buffer(TestUtils.randomAlphaString(2048)); Buffer buff2 = Buffer.buffer(TestUtils.randomAlphaString(2048)); Buffer expected = Buffer.buffer().appendBuffer(buff1).appendBuffer(buff2); AtomicBoolean redirected = new AtomicBoolean(); CountDownLatch latch = new CountDownLatch(1); server.requestHandler(req -> { boolean redirect = redirected.compareAndSet(false, true); if (redirect) { latch.countDown(); } if (redirect) { assertEquals(HttpMethod.PUT, req.method()); req.bodyHandler(body -> { assertEquals(body, expected); String scheme = createBaseServerOptions().isSsl() ? "https" : "http"; req.response().setStatusCode(303).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:8080/whatever").end(); }); } else { assertEquals(HttpMethod.GET, req.method()); req.response().end(); } }); startServer(); HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { assertEquals(200, resp.statusCode()); testComplete(); }).setFollowRedirects(true) .setChunked(true) .write(buff1); awaitLatch(latch); req.end(buff2); await(); } @Test public void testFollowRedirectWithRequestNotEnded() throws Exception { testFollowRedirectWithRequestNotEnded(false); } @Test public void testFollowRedirectWithRequestNotEndedFailing() throws Exception { testFollowRedirectWithRequestNotEnded(true); } private void testFollowRedirectWithRequestNotEnded(boolean expectFail) throws Exception { Buffer buff1 = Buffer.buffer(TestUtils.randomAlphaString(2048)); Buffer buff2 = Buffer.buffer(TestUtils.randomAlphaString(2048)); Buffer expected = Buffer.buffer().appendBuffer(buff1).appendBuffer(buff2); AtomicBoolean redirected = new AtomicBoolean(); CountDownLatch latch = new CountDownLatch(1); server.requestHandler(req -> { boolean redirect = redirected.compareAndSet(false, true); if (redirect) { Buffer body = Buffer.buffer(); req.handler(buff -> { if (body.length() == 0) { HttpServerResponse resp = req.response(); String scheme = createBaseServerOptions().isSsl() ? "https" : "http"; resp.setStatusCode(303).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:8080/whatever"); if (expectFail) { resp.setChunked(true).write("whatever"); vertx.runOnContext(v -> { resp.close(); }); } else { resp.end(); } latch.countDown(); } body.appendBuffer(buff); }); req.endHandler(v -> { assertEquals(expected, body); }); } else { req.response().end(); } }); startServer(); AtomicBoolean called = new AtomicBoolean(); HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { assertEquals(200, resp.statusCode()); testComplete(); }).setFollowRedirects(true) .exceptionHandler(err -> { if (expectFail) { if (called.compareAndSet(false, true)) { testComplete(); } } else { fail(err); } }) .setChunked(true) .write(buff1); awaitLatch(latch); // Wait so we end the request while having received the server response (but we can't be notified) if (!expectFail) { Thread.sleep(500); req.end(buff2); } await(); } @Test public void testFollowRedirectSendHeadThenBody() throws Exception { Buffer expected = Buffer.buffer(TestUtils.randomAlphaString(2048)); AtomicBoolean redirected = new AtomicBoolean(); server.requestHandler(req -> { if (redirected.compareAndSet(false, true)) { assertEquals(HttpMethod.PUT, req.method()); req.bodyHandler(body -> { assertEquals(body, expected); req.response().setStatusCode(303).putHeader(HttpHeaders.LOCATION, "/whatever").end(); }); } else { assertEquals(HttpMethod.GET, req.method()); req.response().end(); } }); startServer(); HttpClientRequest req = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { assertEquals(200, resp.statusCode()); testComplete(); }).setFollowRedirects(true); req.putHeader("Content-Length", "" + expected.length()); req.exceptionHandler(this::fail); req.sendHead(v -> { req.end(expected); }); await(); } @Test public void testFollowRedirectLimit() throws Exception { AtomicInteger redirects = new AtomicInteger(); server.requestHandler(req -> { int val = redirects.incrementAndGet(); if (val > 16) { fail(); } else { String scheme = createBaseServerOptions().isSsl() ? "https" : "http"; req.response().setStatusCode(301).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:8080/otherpath").end(); } }); startServer(); client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { assertEquals(16, redirects.get()); assertEquals(301, resp.statusCode()); assertEquals("/otherpath", resp.request().path()); testComplete(); }).setFollowRedirects(true).end(); await(); } @Test public void testFollowRedirectPropagatesTimeout() throws Exception { AtomicInteger redirections = new AtomicInteger(); server.requestHandler(req -> { switch (redirections.getAndIncrement()) { case 0: String scheme = createBaseServerOptions().isSsl() ? "https" : "http"; req.response().setStatusCode(307).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:8080/whatever").end(); break; } }); startServer(); AtomicBoolean done = new AtomicBoolean(); client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { fail(); }).setFollowRedirects(true) .exceptionHandler(err -> { if (done.compareAndSet(false, true)) { assertEquals(2, redirections.get()); testComplete(); } }) .setTimeout(500).end(); await(); } @Test public void testFollowRedirectHost() throws Exception { String scheme = createBaseClientOptions().isSsl() ? "https" : "http"; waitFor(2); HttpServerOptions options = createBaseServerOptions(); int port = options.getPort() + 1; options.setPort(port); AtomicInteger redirects = new AtomicInteger(); server.requestHandler(req -> { redirects.incrementAndGet(); req.response().setStatusCode(301).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:" + port + "/whatever").end(); }); startServer(); HttpServer server2 = vertx.createHttpServer(options); server2.requestHandler(req -> { assertEquals(1, redirects.get()); assertEquals(scheme + "://localhost:" + port + "/whatever", req.absoluteURI()); req.response().end(); complete(); }); startServer(server2); client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { assertEquals(scheme + "://localhost:" + port + "/whatever", resp.request().absoluteURI()); complete(); }).setFollowRedirects(true).setHost("localhost:" + options.getPort()).end(); await(); } @Test public void testFollowRedirectWithCustomHandler() throws Exception { String scheme = createBaseClientOptions().isSsl() ? "https" : "http"; waitFor(2); HttpServerOptions options = createBaseServerOptions(); int port = options.getPort() + 1; options.setPort(port); AtomicInteger redirects = new AtomicInteger(); server.requestHandler(req -> { redirects.incrementAndGet(); req.response().setStatusCode(301).putHeader(HttpHeaders.LOCATION, scheme + "://localhost:" + port + "/whatever").end(); }); startServer(); HttpServer server2 = vertx.createHttpServer(options); server2.requestHandler(req -> { assertEquals(1, redirects.get()); assertEquals(scheme + "://localhost:" + port + "/custom", req.absoluteURI()); req.response().end(); complete(); }); startServer(server2); client.redirectHandler(resp -> { Future<HttpClientRequest> fut = Future.future(); vertx.setTimer(25, id -> { HttpClientRequest req = client.getAbs(scheme + "://localhost:" + port + "/custom"); req.putHeader("foo", "foo_another"); req.setHost("localhost:" + port); fut.complete(req); }); return fut; }); client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { assertEquals(scheme + "://localhost:" + port + "/custom", resp.request().absoluteURI()); complete(); }).setFollowRedirects(true).putHeader("foo", "foo_value").setHost("localhost:" + options.getPort()).end(); await(); } @Test public void testDefaultRedirectHandler() throws Exception { testFoo("http://example.com", "http://example.com"); testFoo("http://example.com/somepath", "http://example.com/somepath"); testFoo("http://example.com:8000", "http://example.com:8000"); testFoo("http://example.com:8000/somepath", "http://example.com:8000/somepath"); testFoo("https://example.com", "https://example.com"); testFoo("https://example.com/somepath", "https://example.com/somepath"); testFoo("https://example.com:8000", "https://example.com:8000"); testFoo("https://example.com:8000/somepath", "https://example.com:8000/somepath"); testFoo("whatever://example.com", null); testFoo("http://", null); testFoo("http://:8080/somepath", null); } private void testFoo(String location, String expected) throws Exception { int status = 301; Map<String, String> headers = Collections.singletonMap("Location", location); HttpMethod method = HttpMethod.GET; String baseURI = "https://localhost:8080"; class MockReq implements HttpClientRequest { public HttpClientRequest exceptionHandler(Handler<Throwable> handler) { throw new UnsupportedOperationException(); } public HttpClientRequest write(Buffer data) { throw new UnsupportedOperationException(); } public HttpClientRequest setWriteQueueMaxSize(int maxSize) { throw new UnsupportedOperationException(); } public HttpClientRequest drainHandler(Handler<Void> handler) { throw new UnsupportedOperationException(); } public HttpClientRequest handler(Handler<HttpClientResponse> handler) { throw new UnsupportedOperationException(); } public HttpClientRequest pause() { throw new UnsupportedOperationException(); } public HttpClientRequest resume() { throw new UnsupportedOperationException(); } public HttpClientRequest endHandler(Handler<Void> endHandler) { throw new UnsupportedOperationException(); } public HttpClientRequest setFollowRedirects(boolean followRedirects) { throw new UnsupportedOperationException(); } public HttpClientRequest setChunked(boolean chunked) { throw new UnsupportedOperationException(); } public boolean isChunked() { return false; } public HttpMethod method() { return method; } public String getRawMethod() { throw new UnsupportedOperationException(); } public HttpClientRequest setRawMethod(String method) { throw new UnsupportedOperationException(); } public String absoluteURI() { return baseURI; } public String uri() { throw new UnsupportedOperationException(); } public String path() { throw new UnsupportedOperationException(); } public String query() { throw new UnsupportedOperationException(); } public HttpClientRequest setHost(String host) { throw new UnsupportedOperationException(); } public String getHost() { throw new UnsupportedOperationException(); } public MultiMap headers() { throw new UnsupportedOperationException(); } public HttpClientRequest putHeader(String name, String value) { throw new UnsupportedOperationException(); } public HttpClientRequest putHeader(CharSequence name, CharSequence value) { throw new UnsupportedOperationException(); } public HttpClientRequest putHeader(String name, Iterable<String> values) { throw new UnsupportedOperationException(); } public HttpClientRequest putHeader(CharSequence name, Iterable<CharSequence> values) { throw new UnsupportedOperationException(); } public HttpClientRequest write(String chunk) { throw new UnsupportedOperationException(); } public HttpClientRequest write(String chunk, String enc) { throw new UnsupportedOperationException(); } public HttpClientRequest continueHandler(@Nullable Handler<Void> handler) { throw new UnsupportedOperationException(); } public HttpClientRequest sendHead() { throw new UnsupportedOperationException(); } public HttpClientRequest sendHead(Handler<HttpVersion> completionHandler) { throw new UnsupportedOperationException(); } public void end(String chunk) { throw new UnsupportedOperationException(); } public void end(String chunk, String enc) { throw new UnsupportedOperationException(); } public void end(Buffer chunk) { throw new UnsupportedOperationException(); } public void end() { throw new UnsupportedOperationException(); } public HttpClientRequest setTimeout(long timeoutMs) { throw new UnsupportedOperationException(); } public HttpClientRequest pushHandler(Handler<HttpClientRequest> handler) { throw new UnsupportedOperationException(); } public boolean reset(long code) { return false; } public HttpConnection connection() { throw new UnsupportedOperationException(); } public HttpClientRequest connectionHandler(@Nullable Handler<HttpConnection> handler) { throw new UnsupportedOperationException(); } public HttpClientRequest writeCustomFrame(int type, int flags, Buffer payload) { throw new UnsupportedOperationException(); } public boolean writeQueueFull() { throw new UnsupportedOperationException(); } } HttpClientRequest req = new MockReq(); class MockResp implements HttpClientResponse { public HttpClientResponse resume() { throw new UnsupportedOperationException(); } public HttpClientResponse exceptionHandler(Handler<Throwable> handler) { throw new UnsupportedOperationException(); } public HttpClientResponse handler(Handler<Buffer> handler) { throw new UnsupportedOperationException(); } public HttpClientResponse pause() { throw new UnsupportedOperationException(); } public HttpClientResponse endHandler(Handler<Void> endHandler) { throw new UnsupportedOperationException(); } public HttpVersion version() { throw new UnsupportedOperationException(); } public int statusCode() { return status; } public String statusMessage() { throw new UnsupportedOperationException(); } public MultiMap headers() { throw new UnsupportedOperationException(); } public String getHeader(String headerName) { return headers.get(headerName); } public String getHeader(CharSequence headerName) { return getHeader(headerName.toString()); } public String getTrailer(String trailerName) { throw new UnsupportedOperationException(); } public MultiMap trailers() { throw new UnsupportedOperationException(); } public List<String> cookies() { throw new UnsupportedOperationException(); } public HttpClientResponse bodyHandler(Handler<Buffer> bodyHandler) { throw new UnsupportedOperationException(); } public HttpClientResponse customFrameHandler(Handler<HttpFrame> handler) { throw new UnsupportedOperationException(); } public NetSocket netSocket() { throw new UnsupportedOperationException(); } public HttpClientRequest request() { return req; } } MockResp resp = new MockResp(); Function<HttpClientResponse, Future<HttpClientRequest>> handler = client.redirectHandler(); Future<HttpClientRequest> redirection = handler.apply(resp); if (expected != null) { assertEquals(location, redirection.result().absoluteURI()); } else { assertTrue(redirection == null || redirection.failed()); } } @Test public void testFollowRedirectEncodedParams() throws Exception { String value1 = "\ud55c\uae00", value2 = "A B+C", value3 = "123 \u20ac"; server.requestHandler(req -> { switch (req.path()) { case "/first/call/from/client": StringBuilder location = null; try { location = new StringBuilder() .append(req.scheme()).append("://").append(DEFAULT_HTTP_HOST).append(':').append(DEFAULT_HTTP_PORT) .append("/redirected/from/client?") .append("encoded1=").append(URLEncoder.encode(value1, "UTF-8")).append('&') .append("encoded2=").append(URLEncoder.encode(value2, "UTF-8")).append('&') .append("encoded3=").append(URLEncoder.encode(value3, "UTF-8")); } catch (UnsupportedEncodingException e) { fail(e); } req.response() .setStatusCode(302) .putHeader("location", location.toString()) .end(); break; case "/redirected/from/client": assertEquals(value1, req.params().get("encoded1")); assertEquals(value2, req.params().get("encoded2")); assertEquals(value3, req.params().get("encoded3")); req.response().end(); break; default: fail("Unknown path: " + req.path()); } }); startServer(); client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/first/call/from/client", resp -> { assertEquals(200, resp.statusCode()); testComplete(); }).setFollowRedirects(true).end(); await(); } @Test public void testServerResponseCloseHandlerNotHoldingLock() throws Exception { server.requestHandler(req -> { req.response().closeHandler(v -> { assertFalse(Thread.holdsLock(req.connection())); testComplete(); }); req.response().setChunked(true).write("hello"); }); startServer(); client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { assertEquals(200, resp.statusCode()); resp.request().connection().close(); }); await(); } @Test public void testCloseHandlerWhenConnectionEnds() throws Exception { server.requestHandler(req -> { req.response().endHandler(v -> { testComplete(); }); req.response().end("some-data"); }); startServer(); client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { resp.handler(v -> { resp.request().connection().close(); }); }); await(); } @Test public void testCloseHandlerWhenConnectionClose() throws Exception { server.requestHandler(req -> { HttpServerResponse resp = req.response(); resp.setChunked(true).write("some-data"); resp.closeHandler(v -> { checkHttpServerResponse(resp); testComplete(); }); }); startServer(); client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { resp.handler(v -> { resp.request().connection().close(); }); }); await(); } @Test public abstract void testCloseHandlerNotCalledWhenConnectionClosedAfterEnd() throws Exception; protected void testCloseHandlerNotCalledWhenConnectionClosedAfterEnd(int expected) throws Exception { AtomicInteger closeCount = new AtomicInteger(); AtomicInteger endCount = new AtomicInteger(); server.requestHandler(req -> { req.response().closeHandler(v -> { closeCount.incrementAndGet(); }); req.response().endHandler(v -> { endCount.incrementAndGet(); }); req.connection().closeHandler(v -> { assertEquals(expected, closeCount.get()); assertEquals(1, endCount.get()); testComplete(); }); req.response().end("some-data"); }); startServer(); client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { resp.endHandler(v -> { resp.request().connection().close(); }); }); await(); } private TestLoggerFactory testLogging() throws Exception { return TestUtils.testLogging(() -> { try { server.requestHandler(req -> { req.response().end(); }); startServer(); client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> { testComplete(); }); await(); } catch (Exception e) { throw new RuntimeException(e); } }); } @Test public void testClientDecompressionError() throws Exception { waitFor(2); server.requestHandler(req -> { req.response() .putHeader("Content-Encoding", "gzip") .end("long response with mismatched encoding causes connection leaks"); }); startServer(); client.close(); client = vertx.createHttpClient(createBaseClientOptions().setTryUseCompression(true)); client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.exceptionHandler(err -> { if (err instanceof Http2Exception) { complete(); // Connection is not closed for HTTP/2 only the streams so we need to force it resp.request().connection().close(); } else if (err instanceof DecompressionException) { complete(); } }); }).connectionHandler(conn -> { conn.closeHandler(v -> { complete(); }); }).end(); await(); } @Test public void testContainsValueString() { server.requestHandler(req -> { assertTrue(req.headers().contains("Foo", "foo", false)); assertFalse(req.headers().contains("Foo", "fOo", false)); req.response().putHeader("quux", "quux"); req.response().end(); }); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertTrue(resp.headers().contains("Quux", "quux", false)); assertFalse(resp.headers().contains("Quux", "quUx", false)); testComplete(); }); req.putHeader("foo", "foo"); req.end(); })); await(); } @Test public void testContainsValueStringIgnoreCase() { server.requestHandler(req -> { assertTrue(req.headers().contains("Foo", "foo", true)); assertTrue(req.headers().contains("Foo", "fOo", true)); req.response().putHeader("quux", "quux"); req.response().end(); }); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertTrue(resp.headers().contains("Quux", "quux", true)); assertTrue(resp.headers().contains("Quux", "quUx", true)); testComplete(); }); req.putHeader("foo", "foo"); req.end(); })); await(); } @Test public void testContainsValueCharSequence() { CharSequence Foo = HttpHeaders.createOptimized("Foo"); CharSequence foo = HttpHeaders.createOptimized("foo"); CharSequence fOo = HttpHeaders.createOptimized("fOo"); CharSequence Quux = HttpHeaders.createOptimized("Quux"); CharSequence quux = HttpHeaders.createOptimized("quux"); CharSequence quUx = HttpHeaders.createOptimized("quUx"); server.requestHandler(req -> { assertTrue(req.headers().contains(Foo, foo, false)); assertFalse(req.headers().contains(Foo, fOo, false)); req.response().putHeader(quux, quux); req.response().end(); }); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertTrue(resp.headers().contains(Quux, quux, false)); assertFalse(resp.headers().contains(Quux, quUx, false)); testComplete(); }); req.putHeader(foo, foo); req.end(); })); await(); } @Test public void testContainsValueCharSequenceIgnoreCase() { CharSequence Foo = HttpHeaders.createOptimized("Foo"); CharSequence foo = HttpHeaders.createOptimized("foo"); CharSequence fOo = HttpHeaders.createOptimized("fOo"); CharSequence Quux = HttpHeaders.createOptimized("Quux"); CharSequence quux = HttpHeaders.createOptimized("quux"); CharSequence quUx = HttpHeaders.createOptimized("quUx"); server.requestHandler(req -> { assertTrue(req.headers().contains(Foo, foo, true)); assertTrue(req.headers().contains(Foo, fOo, true)); req.response().putHeader(quux, quux); req.response().end(); }); server.listen(onSuccess(server -> { HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { assertTrue(resp.headers().contains(Quux, quux, true)); assertTrue(resp.headers().contains(Quux, quUx, true)); testComplete(); }); req.putHeader(foo, foo); req.end(); })); await(); } @Test public void testBytesReadRequest() throws Exception { int length = 2048; Buffer expected = Buffer.buffer(TestUtils.randomAlphaString(length));; server.requestHandler(req -> { req.bodyHandler(buffer -> { assertEquals(req.bytesRead(), length); req.response().end(); }); }); startServer(); client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.bodyHandler(buff -> { testComplete(); }); }).exceptionHandler(this::fail) .putHeader("content-length", String.valueOf(length)) .write(expected) .end(); await(); } @Test public void testClientSynchronousConnectFailures() { System.setProperty("vertx.disableDnsResolver", "true"); Vertx vertx = Vertx.vertx(new VertxOptions().setAddressResolverOptions(new AddressResolverOptions().setQueryTimeout(100))); try { int poolSize = 2; HttpClient client = vertx.createHttpClient(new HttpClientOptions().setMaxPoolSize(poolSize)); AtomicInteger failures = new AtomicInteger(); vertx.runOnContext(v -> { for (int i = 0; i < (poolSize + 1); i++) { HttpClientRequest clientRequest = client.getAbs("http://invalid-host-name.foo.bar", resp -> fail()); AtomicBoolean f = new AtomicBoolean(); clientRequest.exceptionHandler(e -> { if (f.compareAndSet(false, true)) { if (failures.incrementAndGet() == poolSize + 1) { testComplete(); } } }); clientRequest.end(); } }); await(); } finally { vertx.close(); System.setProperty("vertx.disableDnsResolver", "false"); } } @Test public void testClientConnectInvalidPort() { client.get(-1, "localhost", "/someuri", resp -> { fail(); }).exceptionHandler(err -> { assertEquals(err.getClass(), IllegalArgumentException.class); assertEquals(err.getMessage(), "port p must be in range 0 <= p <= 65535"); testComplete(); }).end(); await(); } protected File setupFile(String fileName, String content) throws Exception { File file = new File(testDir, fileName); if (file.exists()) { file.delete(); } BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); out.write(content); out.close(); return file; } protected static String generateQueryString(Map<String, String> params, char delim) { StringBuilder sb = new StringBuilder(); int count = 0; for (Map.Entry<String, String> param : params.entrySet()) { sb.append(param.getKey()).append("=").append(param.getValue()); if (++count != params.size()) { sb.append(delim); } } return sb.toString(); } protected static Map<String, String> genMap(int num) { Map<String, String> map = new HashMap<>(); for (int i = 0; i < num; i++) { String key; do { key = TestUtils.randomAlphaString(1 + (int) ((19) * Math.random())).toLowerCase(); } while (map.containsKey(key)); map.put(key, TestUtils.randomAlphaString(1 + (int) ((19) * Math.random()))); } return map; } protected static MultiMap getHeaders(int num) { Map<String, String> map = genMap(num); MultiMap headers = new HeadersAdaptor(new DefaultHttpHeaders()); for (Map.Entry<String, String> entry : map.entrySet()) { headers.add(entry.getKey(), entry.getValue()); } return headers; } @Test public void testHttpClientRequestHeadersDontContainCROrLF() throws Exception { server.requestHandler(req -> { req.headers().forEach(header -> { String name = header.getKey(); switch (name.toLowerCase()) { case "host": case ":method": case ":path": case ":scheme": case ":authority": break; default: fail("Unexpected header " + name); } }); testComplete(); }); startServer(); HttpClientRequest req = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {}); List<BiConsumer<String, String>> list = Arrays.asList( req::putHeader, req.headers()::set, req.headers()::add ); list.forEach(cs -> { try { req.putHeader("header-name: header-value\r\nanother-header", "another-value"); fail(); } catch (IllegalArgumentException e) { } }); assertEquals(0, req.headers().size()); req.end(); await(); } @Test public void testHttpServerResponseHeadersDontContainCROrLF() throws Exception { server.requestHandler(req -> { List<BiConsumer<String, String>> list = Arrays.asList( req.response()::putHeader, req.response().headers()::set, req.response().headers()::add ); list.forEach(cs -> { try { cs.accept("header-name: header-value\r\nanother-header", "another-value"); fail(); } catch (IllegalArgumentException e) { } }); assertEquals(Collections.emptySet(), req.response().headers().names()); req.response().end(); }); startServer(); client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.headers().forEach(header -> { String name = header.getKey(); switch (name.toLowerCase()) { case ":status": case "content-length": break; default: fail("Unexpected header " + name); } }); testComplete(); }); await(); } /* @Test public void testReset() throws Exception { CountDownLatch latch = new CountDownLatch(1); server.requestHandler(req -> { req.exceptionHandler(err -> { System.out.println("GOT ERR"); }); req.endHandler(v -> { System.out.println("GOT END"); latch.countDown(); }); }); startServer(); HttpClientRequest req = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {}); req.end(); awaitLatch(latch); req.reset(); await(); } */ }
./CrossVul/dataset_final_sorted/CWE-20/java/good_195_6
crossvul-java_data_good_418_2
package eu.siacs.conversations.ui; import android.Manifest; import android.annotation.SuppressLint; import android.app.Dialog; import android.app.PendingIntent; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.databinding.DataBindingUtil; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.ListFragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.SpannableString; import android.text.Spanned; import android.text.TextWatcher; import android.text.style.TypefaceSpan; import android.util.Log; import android.util.Pair; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import eu.siacs.conversations.Config; import eu.siacs.conversations.R; import eu.siacs.conversations.databinding.ActivityStartConversationBinding; import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Bookmark; import eu.siacs.conversations.entities.Contact; import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.ListItem; import eu.siacs.conversations.entities.Presence; import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate; import eu.siacs.conversations.ui.adapter.ListItemAdapter; import eu.siacs.conversations.ui.interfaces.OnBackendConnected; import eu.siacs.conversations.ui.service.EmojiService; import eu.siacs.conversations.ui.util.JidDialog; import eu.siacs.conversations.ui.util.MenuDoubleTabUtil; import eu.siacs.conversations.ui.util.PendingItem; import eu.siacs.conversations.ui.util.SoftKeyboardUtils; import eu.siacs.conversations.utils.XmppUri; import eu.siacs.conversations.xmpp.OnUpdateBlocklist; import eu.siacs.conversations.xmpp.XmppConnection; import rocks.xmpp.addr.Jid; public class StartConversationActivity extends XmppActivity implements XmppConnectionService.OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, CreateConferenceDialog.CreateConferenceDialogListener, JoinConferenceDialog.JoinConferenceDialogListener { private final int REQUEST_SYNC_CONTACTS = 0x28cf; private final int REQUEST_CREATE_CONFERENCE = 0x39da; private final PendingItem<Intent> pendingViewIntent = new PendingItem<>(); private final PendingItem<String> mInitialSearchValue = new PendingItem<>(); private final AtomicBoolean oneShotKeyboardSuppress = new AtomicBoolean(); public int conference_context_id; public int contact_context_id; private ListPagerAdapter mListPagerAdapter; private List<ListItem> contacts = new ArrayList<>(); private ListItemAdapter mContactsAdapter; private List<ListItem> conferences = new ArrayList<>(); private ListItemAdapter mConferenceAdapter; private List<String> mActivatedAccounts = new ArrayList<>(); private EditText mSearchEditText; private AtomicBoolean mRequestedContactsPermission = new AtomicBoolean(false); private boolean mHideOfflineContacts = false; private MenuItem.OnActionExpandListener mOnActionExpandListener = new MenuItem.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem item) { mSearchEditText.post(() -> { updateSearchViewHint(); mSearchEditText.requestFocus(); if (oneShotKeyboardSuppress.compareAndSet(true, false)) { return; } InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.showSoftInput(mSearchEditText, InputMethodManager.SHOW_IMPLICIT); } }); return true; } @Override public boolean onMenuItemActionCollapse(MenuItem item) { SoftKeyboardUtils.hideSoftKeyboard(StartConversationActivity.this); mSearchEditText.setText(""); filter(null); return true; } }; private TextWatcher mSearchTextWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable editable) { filter(editable.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }; private MenuItem mMenuSearchView; private ListItemAdapter.OnTagClickedListener mOnTagClickedListener = new ListItemAdapter.OnTagClickedListener() { @Override public void onTagClicked(String tag) { if (mMenuSearchView != null) { mMenuSearchView.expandActionView(); mSearchEditText.setText(""); mSearchEditText.append(tag); filter(tag); } } }; private Pair<Integer, Intent> mPostponedActivityResult; private Toast mToast; private UiCallback<Conversation> mAdhocConferenceCallback = new UiCallback<Conversation>() { @Override public void success(final Conversation conversation) { runOnUiThread(() -> { hideToast(); switchToConversation(conversation); }); } @Override public void error(final int errorCode, Conversation object) { runOnUiThread(() -> replaceToast(getString(errorCode))); } @Override public void userInputRequried(PendingIntent pi, Conversation object) { } }; private ActivityStartConversationBinding binding; private TextView.OnEditorActionListener mSearchDone = new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { int pos = binding.startConversationViewPager.getCurrentItem(); if (pos == 0) { if (contacts.size() == 1) { openConversationForContact((Contact) contacts.get(0)); return true; } else if (contacts.size() == 0 && conferences.size() == 1) { openConversationsForBookmark((Bookmark) conferences.get(0)); return true; } } else { if (conferences.size() == 1) { openConversationsForBookmark((Bookmark) conferences.get(0)); return true; } else if (conferences.size() == 0 && contacts.size() == 1) { openConversationForContact((Contact) contacts.get(0)); return true; } } SoftKeyboardUtils.hideSoftKeyboard(StartConversationActivity.this); mListPagerAdapter.requestFocus(pos); return true; } }; private ViewPager.SimpleOnPageChangeListener mOnPageChangeListener = new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { onTabChanged(); } }; public static void populateAccountSpinner(Context context, List<String> accounts, Spinner spinner) { if (accounts.size() > 0) { ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.layout.simple_list_item, accounts); adapter.setDropDownViewResource(R.layout.simple_list_item); spinner.setAdapter(adapter); spinner.setEnabled(true); } else { ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.layout.simple_list_item, Arrays.asList(context.getString(R.string.no_accounts))); adapter.setDropDownViewResource(R.layout.simple_list_item); spinner.setAdapter(adapter); spinner.setEnabled(false); } } public static void launch(Context context) { final Intent intent = new Intent(context, StartConversationActivity.class); context.startActivity(intent); } private static Intent createLauncherIntent(Context context) { final Intent intent = new Intent(context, StartConversationActivity.class); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); return intent; } private static boolean isViewIntent(final Intent i) { return i != null && (Intent.ACTION_VIEW.equals(i.getAction()) || Intent.ACTION_SENDTO.equals(i.getAction()) || i.hasExtra(WelcomeActivity.EXTRA_INVITE_URI)); } protected void hideToast() { if (mToast != null) { mToast.cancel(); } } protected void replaceToast(String msg) { hideToast(); mToast = Toast.makeText(this, msg, Toast.LENGTH_LONG); mToast.show(); } @Override public void onRosterUpdate() { this.refreshUi(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new EmojiService(this).init(); this.binding = DataBindingUtil.setContentView(this, R.layout.activity_start_conversation); Toolbar toolbar = (Toolbar) binding.toolbar; setSupportActionBar(toolbar); configureActionBar(getSupportActionBar()); this.binding.fab.setOnClickListener((v) -> { if (binding.startConversationViewPager.getCurrentItem() == 0) { String searchString = mSearchEditText != null ? mSearchEditText.getText().toString() : null; if (searchString != null && !searchString.trim().isEmpty()) { try { Jid jid = Jid.of(searchString); if (jid.getLocal() != null && jid.isBareJid() && jid.getDomain().contains(".")) { showCreateContactDialog(jid.toString(), null); return; } } catch (IllegalArgumentException ignored) { //ignore and fall through } } showCreateContactDialog(null, null); } else { showCreateConferenceDialog(); } }); binding.tabLayout.setupWithViewPager(binding.startConversationViewPager); binding.startConversationViewPager.addOnPageChangeListener(mOnPageChangeListener); mListPagerAdapter = new ListPagerAdapter(getSupportFragmentManager()); binding.startConversationViewPager.setAdapter(mListPagerAdapter); mConferenceAdapter = new ListItemAdapter(this, conferences); mContactsAdapter = new ListItemAdapter(this, contacts); mContactsAdapter.setOnTagClickedListener(this.mOnTagClickedListener); final SharedPreferences preferences = getPreferences(); this.mHideOfflineContacts = preferences.getBoolean("hide_offline", false); final boolean startSearching = preferences.getBoolean("start_searching",getResources().getBoolean(R.bool.start_searching)); final Intent intent; if (savedInstanceState == null) { intent = getIntent(); } else { final String search = savedInstanceState.getString("search"); if (search != null) { mInitialSearchValue.push(search); } intent = savedInstanceState.getParcelable("intent"); } if (isViewIntent(intent)) { pendingViewIntent.push(intent); setIntent(createLauncherIntent(this)); } else if (startSearching && mInitialSearchValue.peek() == null) { mInitialSearchValue.push(""); } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { Intent pendingIntent = pendingViewIntent.peek(); savedInstanceState.putParcelable("intent", pendingIntent != null ? pendingIntent : getIntent()); if (mMenuSearchView != null && mMenuSearchView.isActionViewExpanded()) { savedInstanceState.putString("search", mSearchEditText != null ? mSearchEditText.getText().toString() : null); } super.onSaveInstanceState(savedInstanceState); } @Override public void onStart() { super.onStart(); final int theme = findTheme(); if (this.mTheme != theme) { recreate(); } else { if (pendingViewIntent.peek() == null) { askForContactsPermissions(); } } mConferenceAdapter.refreshSettings(); mContactsAdapter.refreshSettings(); } @Override public void onNewIntent(final Intent intent) { if (xmppConnectionServiceBound) { processViewIntent(intent); } else { pendingViewIntent.push(intent); } setIntent(createLauncherIntent(this)); } protected void openConversationForContact(int position) { Contact contact = (Contact) contacts.get(position); openConversationForContact(contact); } protected void openConversationForContact(Contact contact) { Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true); SoftKeyboardUtils.hideSoftKeyboard(this); switchToConversation(conversation); } protected void openConversationForBookmark() { openConversationForBookmark(conference_context_id); } protected void openConversationForBookmark(int position) { Bookmark bookmark = (Bookmark) conferences.get(position); openConversationsForBookmark(bookmark); } protected void shareBookmarkUri() { shareBookmarkUri(conference_context_id); } protected void shareBookmarkUri(int position) { Bookmark bookmark = (Bookmark) conferences.get(position); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, "xmpp:" + bookmark.getJid().asBareJid().toEscapedString() + "?join"); shareIntent.setType("text/plain"); try { startActivity(Intent.createChooser(shareIntent, getText(R.string.share_uri_with))); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show(); } } protected void openConversationsForBookmark(Bookmark bookmark) { Jid jid = bookmark.getJid(); if (jid == null) { Toast.makeText(this, R.string.invalid_jid, Toast.LENGTH_SHORT).show(); return; } Conversation conversation = xmppConnectionService.findOrCreateConversation(bookmark.getAccount(), jid, true, true, true); bookmark.setConversation(conversation); if (!bookmark.autojoin() && getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin))) { bookmark.setAutojoin(true); xmppConnectionService.pushBookmarks(bookmark.getAccount()); } SoftKeyboardUtils.hideSoftKeyboard(this); switchToConversation(conversation); } protected void openDetailsForContact() { int position = contact_context_id; Contact contact = (Contact) contacts.get(position); switchToContactDetails(contact); } protected void showQrForContact() { int position = contact_context_id; Contact contact = (Contact) contacts.get(position); showQrCode("xmpp:"+contact.getJid().asBareJid().toEscapedString()); } protected void toggleContactBlock() { final int position = contact_context_id; BlockContactDialog.show(this, (Contact) contacts.get(position)); } protected void deleteContact() { final int position = contact_context_id; final Contact contact = (Contact) contacts.get(position); final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setNegativeButton(R.string.cancel, null); builder.setTitle(R.string.action_delete_contact); builder.setMessage(JidDialog.style(this, R.string.remove_contact_text, contact.getJid().toEscapedString())); builder.setPositiveButton(R.string.delete, (dialog, which) -> { xmppConnectionService.deleteContactOnServer(contact); filter(mSearchEditText.getText().toString()); }); builder.create().show(); } protected void deleteConference() { int position = conference_context_id; final Bookmark bookmark = (Bookmark) conferences.get(position); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setNegativeButton(R.string.cancel, null); builder.setTitle(R.string.delete_bookmark); builder.setMessage(JidDialog.style(this, R.string.remove_bookmark_text, bookmark.getJid().toEscapedString())); builder.setPositiveButton(R.string.delete, (dialog, which) -> { bookmark.setConversation(null); Account account = bookmark.getAccount(); account.getBookmarks().remove(bookmark); xmppConnectionService.pushBookmarks(account); filter(mSearchEditText.getText().toString()); }); builder.create().show(); } @SuppressLint("InflateParams") protected void showCreateContactDialog(final String prefilledJid, final Invite invite) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); EnterJidDialog dialog = EnterJidDialog.newInstance( mActivatedAccounts, getString(R.string.dialog_title_create_contact), getString(R.string.create), prefilledJid, null, invite == null || !invite.hasFingerprints() ); dialog.setOnEnterJidDialogPositiveListener((accountJid, contactJid) -> { if (!xmppConnectionServiceBound) { return false; } final Account account = xmppConnectionService.findAccountByJid(accountJid); if (account == null) { return true; } final Contact contact = account.getRoster().getContact(contactJid); if (invite != null && invite.getName() != null) { contact.setServerName(invite.getName()); } if (contact.isSelf()) { switchToConversation(contact); return true; } else if (contact.showInRoster()) { throw new EnterJidDialog.JidError(getString(R.string.contact_already_exists)); } else { xmppConnectionService.createContact(contact, true); if (invite != null && invite.hasFingerprints()) { xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints()); } switchToConversationDoNotAppend(contact, invite == null ? null : invite.getBody()); return true; } }); dialog.show(ft, FRAGMENT_TAG_DIALOG); } @SuppressLint("InflateParams") protected void showJoinConferenceDialog(final String prefilledJid) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); JoinConferenceDialog joinConferenceFragment = JoinConferenceDialog.newInstance(prefilledJid, mActivatedAccounts); joinConferenceFragment.show(ft, FRAGMENT_TAG_DIALOG); } private void showCreateConferenceDialog() { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment prev = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); CreateConferenceDialog createConferenceFragment = CreateConferenceDialog.newInstance(mActivatedAccounts); createConferenceFragment.show(ft, FRAGMENT_TAG_DIALOG); } private Account getSelectedAccount(Spinner spinner) { if (!spinner.isEnabled()) { return null; } Jid jid; try { if (Config.DOMAIN_LOCK != null) { jid = Jid.of((String) spinner.getSelectedItem(), Config.DOMAIN_LOCK, null); } else { jid = Jid.of((String) spinner.getSelectedItem()); } } catch (final IllegalArgumentException e) { return null; } return xmppConnectionService.findAccountByJid(jid); } protected void switchToConversation(Contact contact) { Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true); switchToConversation(conversation); } protected void switchToConversationDoNotAppend(Contact contact, String body) { Conversation conversation = xmppConnectionService.findOrCreateConversation(contact.getAccount(), contact.getJid(), false, true); switchToConversationDoNotAppend(conversation, body); } @Override public void invalidateOptionsMenu() { boolean isExpanded = mMenuSearchView != null && mMenuSearchView.isActionViewExpanded(); String text = mSearchEditText != null ? mSearchEditText.getText().toString() : ""; if (isExpanded) { mInitialSearchValue.push(text); oneShotKeyboardSuppress.set(true); } super.invalidateOptionsMenu(); } private void updateSearchViewHint() { if (binding == null || mSearchEditText == null) { return; } if (binding.startConversationViewPager.getCurrentItem() == 0) { mSearchEditText.setHint(R.string.search_contacts); } else { mSearchEditText.setHint(R.string.search_groups); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.start_conversation, menu); MenuItem menuHideOffline = menu.findItem(R.id.action_hide_offline); MenuItem joinGroupChat = menu.findItem(R.id.action_join_conference); MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code); joinGroupChat.setVisible(binding.startConversationViewPager.getCurrentItem() == 1); qrCodeScanMenuItem.setVisible(isCameraFeatureAvailable()); menuHideOffline.setChecked(this.mHideOfflineContacts); mMenuSearchView = menu.findItem(R.id.action_search); mMenuSearchView.setOnActionExpandListener(mOnActionExpandListener); View mSearchView = mMenuSearchView.getActionView(); mSearchEditText = mSearchView.findViewById(R.id.search_field); mSearchEditText.addTextChangedListener(mSearchTextWatcher); mSearchEditText.setOnEditorActionListener(mSearchDone); String initialSearchValue = mInitialSearchValue.pop(); if (initialSearchValue != null) { mMenuSearchView.expandActionView(); mSearchEditText.append(initialSearchValue); filter(initialSearchValue); } updateSearchViewHint(); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (MenuDoubleTabUtil.shouldIgnoreTap()) { return false; } switch (item.getItemId()) { case android.R.id.home: navigateBack(); return true; case R.id.action_join_conference: showJoinConferenceDialog(null); return true; case R.id.action_scan_qr_code: UriHandlerActivity.scan(this); return true; case R.id.action_hide_offline: mHideOfflineContacts = !item.isChecked(); getPreferences().edit().putBoolean("hide_offline", mHideOfflineContacts).commit(); if (mSearchEditText != null) { filter(mSearchEditText.getText().toString()); } invalidateOptionsMenu(); } return super.onOptionsItemSelected(item); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_SEARCH && !event.isLongPress()) { openSearch(); return true; } int c = event.getUnicodeChar(); if (c > 32) { if (mSearchEditText != null && !mSearchEditText.isFocused()) { openSearch(); mSearchEditText.append(Character.toString((char) c)); return true; } } return super.onKeyUp(keyCode, event); } private void openSearch() { if (mMenuSearchView != null) { mMenuSearchView.expandActionView(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (resultCode == RESULT_OK) { if (xmppConnectionServiceBound) { this.mPostponedActivityResult = null; if (requestCode == REQUEST_CREATE_CONFERENCE) { Account account = extractAccount(intent); final String name = intent.getStringExtra(ChooseContactActivity.EXTRA_GROUP_CHAT_NAME); final List<Jid> jids = ChooseContactActivity.extractJabberIds(intent); if (account != null && jids.size() > 0) { if (xmppConnectionService.createAdhocConference(account, name, jids, mAdhocConferenceCallback)) { mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG); mToast.show(); } } } } else { this.mPostponedActivityResult = new Pair<>(requestCode, intent); } } super.onActivityResult(requestCode, requestCode, intent); } private void askForContactsPermissions() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { if (mRequestedContactsPermission.compareAndSet(false, true)) { if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.sync_with_contacts); builder.setMessage(R.string.sync_with_contacts_long); builder.setPositiveButton(R.string.next, (dialog, which) -> requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS)); builder.setOnDismissListener(dialog -> requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS)); builder.create().show(); } else { requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_SYNC_CONTACTS); } } } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { if (grantResults.length > 0) if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { ScanActivity.onRequestPermissionResult(this, requestCode, grantResults); if (requestCode == REQUEST_SYNC_CONTACTS && xmppConnectionServiceBound) { xmppConnectionService.loadPhoneContacts(); xmppConnectionService.startContactObserver(); } } } private void configureHomeButton() { final ActionBar actionBar = getSupportActionBar(); if (actionBar == null) { return; } boolean openConversations = !xmppConnectionService.isConversationsListEmpty(null); actionBar.setDisplayHomeAsUpEnabled(openConversations); actionBar.setDisplayHomeAsUpEnabled(openConversations); } @Override protected void onBackendConnected() { if (mPostponedActivityResult != null) { onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second); this.mPostponedActivityResult = null; } this.mActivatedAccounts.clear(); for (Account account : xmppConnectionService.getAccounts()) { if (account.getStatus() != Account.State.DISABLED) { if (Config.DOMAIN_LOCK != null) { this.mActivatedAccounts.add(account.getJid().getLocal()); } else { this.mActivatedAccounts.add(account.getJid().asBareJid().toString()); } } } configureHomeButton(); Intent intent = pendingViewIntent.pop(); if (intent != null && processViewIntent(intent)) { filter(null); } else { if (mSearchEditText != null) { filter(mSearchEditText.getText().toString()); } else { filter(null); } } Fragment fragment = getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG_DIALOG); if (fragment != null && fragment instanceof OnBackendConnected) { Log.d(Config.LOGTAG, "calling on backend connected on dialog"); ((OnBackendConnected) fragment).onBackendConnected(); } } protected boolean processViewIntent(@NonNull Intent intent) { final String inviteUri = intent.getStringExtra(WelcomeActivity.EXTRA_INVITE_URI); if (inviteUri != null) { Invite invite = new Invite(inviteUri); if (invite.isJidValid()) { return invite.invite(); } } final String action = intent.getAction(); if (action == null) { return false; } switch (action) { case Intent.ACTION_SENDTO: case Intent.ACTION_VIEW: Uri uri = intent.getData(); if (uri != null) { Invite invite = new Invite(intent.getData(), intent.getBooleanExtra("scanned", false)); invite.account = intent.getStringExtra("account"); return invite.invite(); } else { return false; } } return false; } private boolean handleJid(Invite invite) { List<Contact> contacts = xmppConnectionService.findContacts(invite.getJid(), invite.account); if (invite.isAction(XmppUri.ACTION_JOIN)) { Conversation muc = xmppConnectionService.findFirstMuc(invite.getJid()); if (muc != null) { switchToConversationDoNotAppend(muc, invite.getBody()); return true; } else { showJoinConferenceDialog(invite.getJid().asBareJid().toString()); return false; } } else if (contacts.size() == 0) { showCreateContactDialog(invite.getJid().toString(), invite); return false; } else if (contacts.size() == 1) { Contact contact = contacts.get(0); if (!invite.isSafeSource() && invite.hasFingerprints()) { displayVerificationWarningDialog(contact, invite); } else { if (invite.hasFingerprints()) { if (xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints())) { Toast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show(); } } if (invite.account != null) { xmppConnectionService.getShortcutService().report(contact); } switchToConversationDoNotAppend(contact, invite.getBody()); } return true; } else { if (mMenuSearchView != null) { mMenuSearchView.expandActionView(); mSearchEditText.setText(""); mSearchEditText.append(invite.getJid().toString()); filter(invite.getJid().toString()); } else { mInitialSearchValue.push(invite.getJid().toString()); } return true; } } private void displayVerificationWarningDialog(final Contact contact, final Invite invite) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.verify_omemo_keys); View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null); final CheckBox isTrustedSource = view.findViewById(R.id.trusted_source); TextView warning = view.findViewById(R.id.warning); warning.setText(JidDialog.style(this, R.string.verifying_omemo_keys_trusted_source, contact.getJid().asBareJid().toEscapedString(), contact.getDisplayName())); builder.setView(view); builder.setPositiveButton(R.string.confirm, (dialog, which) -> { if (isTrustedSource.isChecked() && invite.hasFingerprints()) { xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints()); } switchToConversationDoNotAppend(contact, invite.getBody()); }); builder.setNegativeButton(R.string.cancel, (dialog, which) -> StartConversationActivity.this.finish()); AlertDialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(false); dialog.setOnCancelListener(dialog1 -> StartConversationActivity.this.finish()); dialog.show(); } protected void filter(String needle) { if (xmppConnectionServiceBound) { this.filterContacts(needle); this.filterConferences(needle); } } protected void filterContacts(String needle) { this.contacts.clear(); final List<Account> accounts = xmppConnectionService.getAccounts(); final boolean singleAccountActive = isSingleAccountActive(accounts); for (Account account : accounts) { if (account.getStatus() != Account.State.DISABLED) { for (Contact contact : account.getRoster().getContacts()) { Presence.Status s = contact.getShownStatus(); if ((contact.showInRoster() || (singleAccountActive && contact.showInPhoneBook())) && contact.match(this, needle) && (!this.mHideOfflineContacts || (needle != null && !needle.trim().isEmpty()) || s.compareTo(Presence.Status.OFFLINE) < 0)) { this.contacts.add(contact); } } } } Collections.sort(this.contacts); mContactsAdapter.notifyDataSetChanged(); } private static boolean isSingleAccountActive(final List<Account> accounts) { int i = 0; for(Account account : accounts) { if (account.getStatus() != Account.State.DISABLED) { ++i; } } return i == 1; } protected void filterConferences(String needle) { this.conferences.clear(); for (Account account : xmppConnectionService.getAccounts()) { if (account.getStatus() != Account.State.DISABLED) { for (Bookmark bookmark : account.getBookmarks()) { if (bookmark.match(this, needle)) { this.conferences.add(bookmark); } } } } Collections.sort(this.conferences); mConferenceAdapter.notifyDataSetChanged(); } private void onTabChanged() { @DrawableRes final int fabDrawable; if (binding.startConversationViewPager.getCurrentItem() == 0) { fabDrawable = R.drawable.ic_person_add_white_24dp; } else { fabDrawable = R.drawable.ic_group_add_white_24dp; } binding.fab.setImageResource(fabDrawable); invalidateOptionsMenu(); } @Override public void OnUpdateBlocklist(final Status status) { refreshUi(); } @Override protected void refreshUiReal() { if (mSearchEditText != null) { filter(mSearchEditText.getText().toString()); } configureHomeButton(); } @Override public void onBackPressed() { navigateBack(); } private void navigateBack() { if (xmppConnectionService != null && !xmppConnectionService.isConversationsListEmpty(null)) { Intent intent = new Intent(this, ConversationsActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent); } finish(); } @Override public void onCreateDialogPositiveClick(Spinner spinner, String name) { if (!xmppConnectionServiceBound) { return; } final Account account = getSelectedAccount(spinner); if (account == null) { return; } Intent intent = new Intent(getApplicationContext(), ChooseContactActivity.class); intent.putExtra(ChooseContactActivity.EXTRA_SHOW_ENTER_JID, false); intent.putExtra(ChooseContactActivity.EXTRA_SELECT_MULTIPLE, true); intent.putExtra(ChooseContactActivity.EXTRA_GROUP_CHAT_NAME, name.trim()); intent.putExtra(ChooseContactActivity.EXTRA_ACCOUNT, account.getJid().asBareJid().toString()); intent.putExtra(ChooseContactActivity.EXTRA_TITLE_RES_ID, R.string.choose_participants); startActivityForResult(intent, REQUEST_CREATE_CONFERENCE); } @Override public void onJoinDialogPositiveClick(Dialog dialog, Spinner spinner, AutoCompleteTextView jid, boolean isBookmarkChecked) { if (!xmppConnectionServiceBound) { return; } final Account account = getSelectedAccount(spinner); if (account == null) { return; } final Jid conferenceJid; try { conferenceJid = Jid.of(jid.getText().toString()); } catch (final IllegalArgumentException e) { jid.setError(getString(R.string.invalid_jid)); return; } if (isBookmarkChecked) { if (account.hasBookmarkFor(conferenceJid)) { jid.setError(getString(R.string.bookmark_already_exists)); } else { final Bookmark bookmark = new Bookmark(account, conferenceJid.asBareJid()); bookmark.setAutojoin(getBooleanPreference("autojoin", R.bool.autojoin)); String nick = conferenceJid.getResource(); if (nick != null && !nick.isEmpty()) { bookmark.setNick(nick); } account.getBookmarks().add(bookmark); xmppConnectionService.pushBookmarks(account); final Conversation conversation = xmppConnectionService .findOrCreateConversation(account, conferenceJid, true, true, true); bookmark.setConversation(conversation); dialog.dismiss(); switchToConversation(conversation); } } else { final Conversation conversation = xmppConnectionService .findOrCreateConversation(account, conferenceJid, true, true, true); dialog.dismiss(); switchToConversation(conversation); } } @Override public void onConversationUpdate() { refreshUi(); } public static class MyListFragment extends ListFragment { private AdapterView.OnItemClickListener mOnItemClickListener; private int mResContextMenu; public void setContextMenu(final int res) { this.mResContextMenu = res; } @Override public void onListItemClick(final ListView l, final View v, final int position, final long id) { if (mOnItemClickListener != null) { mOnItemClickListener.onItemClick(l, v, position, id); } } public void setOnListItemClickListener(AdapterView.OnItemClickListener l) { this.mOnItemClickListener = l; } @Override public void onViewCreated(@NonNull final View view, final Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); registerForContextMenu(getListView()); getListView().setFastScrollEnabled(true); getListView().setDivider(null); getListView().setDividerHeight(0); } @Override public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); final StartConversationActivity activity = (StartConversationActivity) getActivity(); if (activity == null) { return; } activity.getMenuInflater().inflate(mResContextMenu, menu); final AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo; if (mResContextMenu == R.menu.conference_context) { activity.conference_context_id = acmi.position; } else if (mResContextMenu == R.menu.contact_context) { activity.contact_context_id = acmi.position; final Contact contact = (Contact) activity.contacts.get(acmi.position); final MenuItem blockUnblockItem = menu.findItem(R.id.context_contact_block_unblock); final MenuItem showContactDetailsItem = menu.findItem(R.id.context_contact_details); final MenuItem deleteContactMenuItem = menu.findItem(R.id.context_delete_contact); if (contact.isSelf()) { showContactDetailsItem.setVisible(false); } deleteContactMenuItem.setVisible(contact.showInRoster()); XmppConnection xmpp = contact.getAccount().getXmppConnection(); if (xmpp != null && xmpp.getFeatures().blocking() && !contact.isSelf()) { if (contact.isBlocked()) { blockUnblockItem.setTitle(R.string.unblock_contact); } else { blockUnblockItem.setTitle(R.string.block_contact); } } else { blockUnblockItem.setVisible(false); } } } @Override public boolean onContextItemSelected(final MenuItem item) { StartConversationActivity activity = (StartConversationActivity) getActivity(); if (activity == null) { return true; } switch (item.getItemId()) { case R.id.context_contact_details: activity.openDetailsForContact(); break; case R.id.context_show_qr: activity.showQrForContact(); break; case R.id.context_contact_block_unblock: activity.toggleContactBlock(); break; case R.id.context_delete_contact: activity.deleteContact(); break; case R.id.context_join_conference: activity.openConversationForBookmark(); break; case R.id.context_share_uri: activity.shareBookmarkUri(); break; case R.id.context_delete_conference: activity.deleteConference(); } return true; } } public class ListPagerAdapter extends PagerAdapter { FragmentManager fragmentManager; MyListFragment[] fragments; public ListPagerAdapter(FragmentManager fm) { fragmentManager = fm; fragments = new MyListFragment[2]; } public void requestFocus(int pos) { if (fragments.length > pos) { fragments[pos].getListView().requestFocus(); } } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { FragmentTransaction trans = fragmentManager.beginTransaction(); trans.remove(fragments[position]); trans.commit(); fragments[position] = null; } @NonNull @Override public Fragment instantiateItem(@NonNull ViewGroup container, int position) { Fragment fragment = getItem(position); FragmentTransaction trans = fragmentManager.beginTransaction(); trans.add(container.getId(), fragment, "fragment:" + position); trans.commit(); return fragment; } @Override public int getCount() { return fragments.length; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object fragment) { return ((Fragment) fragment).getView() == view; } @Nullable @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return getResources().getString(R.string.contacts); case 1: return getResources().getString(R.string.conferences); default: return super.getPageTitle(position); } } Fragment getItem(int position) { if (fragments[position] == null) { final MyListFragment listFragment = new MyListFragment(); if (position == 1) { listFragment.setListAdapter(mConferenceAdapter); listFragment.setContextMenu(R.menu.conference_context); listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForBookmark(p)); } else { listFragment.setListAdapter(mContactsAdapter); listFragment.setContextMenu(R.menu.contact_context); listFragment.setOnListItemClickListener((arg0, arg1, p, arg3) -> openConversationForContact(p)); } fragments[position] = listFragment; } return fragments[position]; } } private class Invite extends XmppUri { public String account; public Invite(final Uri uri) { super(uri); } public Invite(final String uri) { super(uri); } public Invite(Uri uri, boolean safeSource) { super(uri, safeSource); } boolean invite() { if (!isJidValid()) { Toast.makeText(StartConversationActivity.this, R.string.invalid_jid, Toast.LENGTH_SHORT).show(); return false; } if (getJid() != null) { return handleJid(this); } return false; } } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_418_2
crossvul-java_data_bad_195_4
/* * Copyright (c) 2011-2017 Contributors to the Eclipse Foundation * * 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, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core.http.impl; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.compression.ZlibWrapper; import io.netty.handler.codec.http.HttpContentCompressor; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http2.Http2Headers; import io.netty.handler.codec.http2.Http2Settings; import io.netty.util.AsciiString; import io.vertx.core.MultiMap; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.CaseInsensitiveHeaders; import io.vertx.core.http.HttpServerRequest; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.Base64; import java.util.List; import java.util.Map; import static io.vertx.core.http.Http2Settings.*; /** * Various http utils. * * @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a> */ public final class HttpUtils { private HttpUtils() { } private static int indexOfSlash(CharSequence str, int start) { for (int i = start; i < str.length(); i++) { if (str.charAt(i) == '/') { return i; } } return -1; } private static boolean matches(CharSequence path, int start, String what) { return matches(path, start, what, false); } private static boolean matches(CharSequence path, int start, String what, boolean exact) { if (exact) { if (path.length() - start != what.length()) { return false; } } if (path.length() - start >= what.length()) { for (int i = 0; i < what.length(); i++) { if (path.charAt(start + i) != what.charAt(i)) { return false; } } return true; } return false; } /** * Removed dots as per <a href="http://tools.ietf.org/html/rfc3986#section-5.2.4>rfc3986</a>. * * There are 2 extra transformations that are not part of the spec but kept for backwards compatibility: * * double slash // will be converted to single slash and the path will always start with slash. * * @param path raw path * @return normalized path */ public static String removeDots(CharSequence path) { if (path == null) { return null; } final StringBuilder obuf = new StringBuilder(path.length()); int i = 0; while (i < path.length()) { // remove dots as described in // http://tools.ietf.org/html/rfc3986#section-5.2.4 if (matches(path, i, "./")) { i += 2; } else if (matches(path, i, "../")) { i += 3; } else if (matches(path, i, "/./")) { // preserve last slash i += 2; } else if (matches(path, i,"/.", true)) { path = "/"; i = 0; } else if (matches(path, i, "/../")) { // preserve last slash i += 3; int pos = obuf.lastIndexOf("/"); if (pos != -1) { obuf.delete(pos, obuf.length()); } } else if (matches(path, i, "/..", true)) { path = "/"; i = 0; int pos = obuf.lastIndexOf("/"); if (pos != -1) { obuf.delete(pos, obuf.length()); } } else if (matches(path, i, ".", true) || matches(path, i, "..", true)) { break; } else { if (path.charAt(i) == '/') { i++; // Not standard!!! // but common // -> / if (obuf.length() == 0 || obuf.charAt(obuf.length() - 1) != '/') { obuf.append('/'); } } int pos = indexOfSlash(path, i); if (pos != -1) { obuf.append(path, i, pos); i = pos; } else { obuf.append(path, i, path.length()); break; } } } return obuf.toString(); } /** * Resolve an URI reference as per <a href="http://tools.ietf.org/html/rfc3986#section-5.2.4>rfc3986</a> */ public static URI resolveURIReference(String base, String ref) throws URISyntaxException { return resolveURIReference(URI.create(base), ref); } /** * Resolve an URI reference as per <a href="http://tools.ietf.org/html/rfc3986#section-5.2.4>rfc3986</a> */ public static URI resolveURIReference(URI base, String ref) throws URISyntaxException { URI _ref = URI.create(ref); String scheme; String authority; String path; String query; if (_ref.getScheme() != null) { scheme = _ref.getScheme(); authority = _ref.getAuthority(); path = removeDots(_ref.getPath()); query = _ref.getRawQuery(); } else { if (_ref.getAuthority() != null) { authority = _ref.getAuthority(); path = _ref.getPath(); query = _ref.getRawQuery(); } else { if (_ref.getPath().length() == 0) { path = base.getPath(); if (_ref.getRawQuery() != null) { query = _ref.getRawQuery(); } else { query = base.getRawQuery(); } } else { if (_ref.getPath().startsWith("/")) { path = removeDots(_ref.getPath()); } else { // Merge paths String mergedPath; String basePath = base.getPath(); if (base.getAuthority() != null && basePath.length() == 0) { mergedPath = "/" + _ref.getPath(); } else { int index = basePath.lastIndexOf('/'); if (index > -1) { mergedPath = basePath.substring(0, index + 1) + _ref.getPath(); } else { mergedPath = _ref.getPath(); } } path = removeDots(mergedPath); } query = _ref.getRawQuery(); } authority = base.getAuthority(); } scheme = base.getScheme(); } return new URI(scheme, authority, path, query, _ref.getFragment()); } /** * Extract the path out of the uri. */ static String parsePath(String uri) { int i; if (uri.charAt(0) == '/') { i = 0; } else { i = uri.indexOf("://"); if (i == -1) { i = 0; } else { i = uri.indexOf('/', i + 3); if (i == -1) { // contains no / return "/"; } } } int queryStart = uri.indexOf('?', i); if (queryStart == -1) { queryStart = uri.length(); } return uri.substring(i, queryStart); } /** * Extract the query out of a uri or returns {@code null} if no query was found. */ static String parseQuery(String uri) { int i = uri.indexOf('?'); if (i == -1) { return null; } else { return uri.substring(i + 1 , uri.length()); } } static String absoluteURI(String serverOrigin, HttpServerRequest req) throws URISyntaxException { String absoluteURI; URI uri = new URI(req.uri()); String scheme = uri.getScheme(); if (scheme != null && (scheme.equals("http") || scheme.equals("https"))) { absoluteURI = uri.toString(); } else { String host = req.host(); if (host != null) { absoluteURI = req.scheme() + "://" + host + uri; } else { // Fall back to the server origin absoluteURI = serverOrigin + uri; } } return absoluteURI; } static MultiMap params(String uri) { QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri); Map<String, List<String>> prms = queryStringDecoder.parameters(); MultiMap params = new CaseInsensitiveHeaders(); if (!prms.isEmpty()) { for (Map.Entry<String, List<String>> entry: prms.entrySet()) { params.add(entry.getKey(), entry.getValue()); } } return params; } public static void fromVertxInitialSettings(boolean server, io.vertx.core.http.Http2Settings vertxSettings, Http2Settings nettySettings) { if (vertxSettings != null) { if (!server && vertxSettings.isPushEnabled() != DEFAULT_ENABLE_PUSH) { nettySettings.pushEnabled(vertxSettings.isPushEnabled()); } if (vertxSettings.getHeaderTableSize() != DEFAULT_HEADER_TABLE_SIZE) { nettySettings.put('\u0001', (Long)vertxSettings.getHeaderTableSize()); } if (vertxSettings.getInitialWindowSize() != DEFAULT_INITIAL_WINDOW_SIZE) { nettySettings.initialWindowSize(vertxSettings.getInitialWindowSize()); } if (vertxSettings.getMaxConcurrentStreams() != DEFAULT_MAX_CONCURRENT_STREAMS) { nettySettings.maxConcurrentStreams(vertxSettings.getMaxConcurrentStreams()); } if (vertxSettings.getMaxFrameSize() != DEFAULT_MAX_FRAME_SIZE) { nettySettings.maxFrameSize(vertxSettings.getMaxFrameSize()); } if (vertxSettings.getMaxHeaderListSize() != DEFAULT_MAX_HEADER_LIST_SIZE) { nettySettings.maxHeaderListSize(vertxSettings.getMaxHeaderListSize()); } Map<Integer, Long> extraSettings = vertxSettings.getExtraSettings(); if (extraSettings != null) { extraSettings.forEach((code, setting) -> { nettySettings.put((char)(int)code, setting); }); } } } public static Http2Settings fromVertxSettings(io.vertx.core.http.Http2Settings settings) { Http2Settings converted = new Http2Settings(); converted.pushEnabled(settings.isPushEnabled()); converted.maxFrameSize(settings.getMaxFrameSize()); converted.initialWindowSize(settings.getInitialWindowSize()); converted.headerTableSize(settings.getHeaderTableSize()); converted.maxConcurrentStreams(settings.getMaxConcurrentStreams()); converted.maxHeaderListSize(settings.getMaxHeaderListSize()); if (settings.getExtraSettings() != null) { settings.getExtraSettings().forEach((key, value) -> { converted.put((char)(int)key, value); }); } return converted; } public static io.vertx.core.http.Http2Settings toVertxSettings(Http2Settings settings) { io.vertx.core.http.Http2Settings converted = new io.vertx.core.http.Http2Settings(); Boolean pushEnabled = settings.pushEnabled(); if (pushEnabled != null) { converted.setPushEnabled(pushEnabled); } Long maxConcurrentStreams = settings.maxConcurrentStreams(); if (maxConcurrentStreams != null) { converted.setMaxConcurrentStreams(maxConcurrentStreams); } Long maxHeaderListSize = settings.maxHeaderListSize(); if (maxHeaderListSize != null) { converted.setMaxHeaderListSize(maxHeaderListSize); } Integer maxFrameSize = settings.maxFrameSize(); if (maxFrameSize != null) { converted.setMaxFrameSize(maxFrameSize); } Integer initialWindowSize = settings.initialWindowSize(); if (initialWindowSize != null) { converted.setInitialWindowSize(initialWindowSize); } Long headerTableSize = settings.headerTableSize(); if (headerTableSize != null) { converted.setHeaderTableSize(headerTableSize); } settings.forEach((key, value) -> { if (key > 6) { converted.set(key, value); } }); return converted; } static Http2Settings decodeSettings(String base64Settings) { try { Http2Settings settings = new Http2Settings(); Buffer buffer = Buffer.buffer(Base64.getUrlDecoder().decode(base64Settings)); int pos = 0; int len = buffer.length(); while (pos < len) { int i = buffer.getUnsignedShort(pos); pos += 2; long j = buffer.getUnsignedInt(pos); pos += 4; settings.put((char)i, (Long)j); } return settings; } catch (Exception ignore) { } return null; } public static String encodeSettings(io.vertx.core.http.Http2Settings settings) { Buffer buffer = Buffer.buffer(); fromVertxSettings(settings).forEach((c, l) -> { buffer.appendUnsignedShort(c); buffer.appendUnsignedInt(l); }); return Base64.getUrlEncoder().encodeToString(buffer.getBytes()); } public static ByteBuf generateWSCloseFrameByteBuf(short statusCode, String reason) { if (reason != null) return Unpooled.copiedBuffer( Unpooled.copyShort(statusCode), // First two bytes are reserved for status code Unpooled.copiedBuffer(reason, Charset.forName("UTF-8")) ); else return Unpooled.copyShort(statusCode); } private static class CustomCompressor extends HttpContentCompressor { @Override public ZlibWrapper determineWrapper(String acceptEncoding) { return super.determineWrapper(acceptEncoding); } } private static final CustomCompressor compressor = new CustomCompressor(); static String determineContentEncoding(Http2Headers headers) { String acceptEncoding = headers.get(HttpHeaderNames.ACCEPT_ENCODING) != null ? headers.get(HttpHeaderNames.ACCEPT_ENCODING).toString() : null; if (acceptEncoding != null) { ZlibWrapper wrapper = compressor.determineWrapper(acceptEncoding); if (wrapper != null) { switch (wrapper) { case GZIP: return "gzip"; case ZLIB: return "deflate"; } } } return null; } static HttpMethod toNettyHttpMethod(io.vertx.core.http.HttpMethod method, String rawMethod) { switch (method) { case CONNECT: { return HttpMethod.CONNECT; } case GET: { return HttpMethod.GET; } case PUT: { return HttpMethod.PUT; } case POST: { return HttpMethod.POST; } case DELETE: { return HttpMethod.DELETE; } case HEAD: { return HttpMethod.HEAD; } case OPTIONS: { return HttpMethod.OPTIONS; } case TRACE: { return HttpMethod.TRACE; } case PATCH: { return HttpMethod.PATCH; } default: { return HttpMethod.valueOf(rawMethod); } } } static HttpVersion toNettyHttpVersion(io.vertx.core.http.HttpVersion version) { switch (version) { case HTTP_1_0: { return HttpVersion.HTTP_1_0; } case HTTP_1_1: { return HttpVersion.HTTP_1_1; } default: throw new IllegalArgumentException("Unsupported HTTP version: " + version); } } static io.vertx.core.http.HttpMethod toVertxMethod(String method) { try { return io.vertx.core.http.HttpMethod.valueOf(method); } catch (IllegalArgumentException e) { return io.vertx.core.http.HttpMethod.OTHER; } } private static final AsciiString TIMEOUT_EQ = AsciiString.of("timeout="); public static int parseKeepAliveHeaderTimeout(CharSequence value) { int len = value.length(); int pos = 0; while (pos < len) { int idx = AsciiString.indexOf(value, ',', pos); int next; if (idx == -1) { idx = next = len; } else { next = idx + 1; } while (pos < idx && value.charAt(pos) == ' ') { pos++; } int to = idx; while (to > pos && value.charAt(to -1) == ' ') { to--; } if (AsciiString.regionMatches(value, true, pos, TIMEOUT_EQ, 0, TIMEOUT_EQ.length())) { pos += TIMEOUT_EQ.length(); if (pos < to) { int ret = 0; while (pos < to) { int ch = value.charAt(pos++); if (ch >= '0' && ch < '9') { ret = ret * 10 + (ch - '0'); } else { ret = -1; break; } } if (ret > -1) { return ret; } } } pos = next; } return -1; } }
./CrossVul/dataset_final_sorted/CWE-20/java/bad_195_4
crossvul-java_data_bad_2626_0
package org.openmrs.module.htmlformentry.web.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.StringWriter; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.SystemUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Patient; import org.openmrs.api.context.Context; import org.openmrs.module.htmlformentry.FormEntryContext.Mode; import org.openmrs.module.htmlformentry.FormEntrySession; import org.openmrs.module.htmlformentry.HtmlForm; import org.openmrs.module.htmlformentry.HtmlFormEntryUtil; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; /** * The controller for previewing a HtmlForm by loading the xml file that defines that HtmlForm from * disk. * <p/> * Handles {@code htmlFormFromFile.form} requests. Renders view {@code htmlFormFromFile.jsp}. */ @Controller public class HtmlFormFromFileController { private static final String TEMP_HTML_FORM_FILE_PREFIX = "html_form_"; /** Logger for this class and subclasses */ protected final Log log = LogFactory.getLog(getClass()); @RequestMapping("/module/htmlformentry/htmlFormFromFile.form") public void handleRequest(Model model, @RequestParam(value = "filePath", required = false) String filePath, @RequestParam(value = "patientId", required = false) Integer pId, @RequestParam(value = "isFileUpload", required = false) boolean isFileUpload, HttpServletRequest request) throws Exception { if (log.isDebugEnabled()) log.debug("In reference data..."); model.addAttribute("previewHtml", ""); String message = ""; File f = null; try { if (isFileUpload) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile("htmlFormFile"); if (multipartFile != null) { //use the same file for the logged in user f = new File(SystemUtils.JAVA_IO_TMPDIR, TEMP_HTML_FORM_FILE_PREFIX + Context.getAuthenticatedUser().getSystemId()); if (!f.exists()) f.createNewFile(); filePath = f.getAbsolutePath(); FileOutputStream fileOut = new FileOutputStream(f); IOUtils.copy(multipartFile.getInputStream(), fileOut); fileOut.close(); } } else { if (StringUtils.hasText(filePath)) { f = new File(filePath); } else { message = "You must specify a file path to preview from file"; } } if (f != null && f.exists() && f.canRead()) { model.addAttribute("filePath", filePath); StringWriter writer = new StringWriter(); IOUtils.copy(new FileInputStream(f), writer, "UTF-8"); String xml = writer.toString(); Patient p = null; if (pId != null) { p = Context.getPatientService().getPatient(pId); } else { p = HtmlFormEntryUtil.getFakePerson(); } HtmlForm fakeForm = new HtmlForm(); fakeForm.setXmlData(xml); FormEntrySession fes = new FormEntrySession(p, null, Mode.ENTER, fakeForm, request.getSession()); String html = fes.getHtmlToDisplay(); if (fes.getFieldAccessorJavascript() != null) { html += "<script>" + fes.getFieldAccessorJavascript() + "</script>"; } model.addAttribute("previewHtml", html); //clear the error message message = ""; } else { message = "Please specify a valid file path or select a valid file."; } } catch (Exception e) { log.error("An error occurred while loading the html.", e); message = "An error occurred while loading the html. " + e.getMessage(); } model.addAttribute("message", message); model.addAttribute("isFileUpload", isFileUpload); } }
./CrossVul/dataset_final_sorted/CWE-20/java/bad_2626_0
crossvul-java_data_good_195_1
/* * Copyright (c) 2011-2017 Contributors to the Eclipse Foundation * * 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, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core.http.impl; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http2.Http2Headers; import io.vertx.core.MultiMap; import java.util.AbstractList; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a> */ public class Http2HeadersAdaptor implements MultiMap { static CharSequence toLowerCase(CharSequence s) { StringBuilder buffer = null; int len = s.length(); for (int index = 0; index < len; index++) { char c = s.charAt(index); if (c >= 'A' && c <= 'Z') { if (buffer == null) { buffer = new StringBuilder(s); } buffer.setCharAt(index, (char)(c + ('a' - 'A'))); } } if (buffer != null) { return buffer.toString(); } else { return s; } } private final Http2Headers headers; private Set<String> names; public Http2HeadersAdaptor(Http2Headers headers) { List<CharSequence> cookies = headers.getAll(HttpHeaderNames.COOKIE); if (cookies != null && cookies.size() > 1) { // combine the cookie values into 1 header entry. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 String value = cookies.stream().collect(Collectors.joining("; ")); headers.set(HttpHeaderNames.COOKIE, value); } this.headers = headers; } @Override public String get(String name) { CharSequence val = headers.get(toLowerCase(name)); return val != null ? val.toString() : null; } @Override public List<String> getAll(String name) { List<CharSequence> all = headers.getAll(toLowerCase(name)); if (all != null) { return new AbstractList<String>() { @Override public String get(int index) { return all.get(index).toString(); } @Override public int size() { return all.size(); } }; } return null; } @Override public List<Map.Entry<String, String>> entries() { return headers.names() .stream() .map(name -> new AbstractMap.SimpleEntry<>(name.toString(), headers.get(name).toString())) .collect(Collectors.toList()); } @Override public boolean contains(String name) { return headers.contains(toLowerCase(name)); } @Override public boolean contains(String name, String value, boolean caseInsensitive) { return headers.contains(toLowerCase(name), value, caseInsensitive); } @Override public boolean isEmpty() { return headers.isEmpty(); } @Override public Set<String> names() { if (names == null) { names = new AbstractSet<String>() { @Override public Iterator<String> iterator() { Iterator<CharSequence> it = headers.names().iterator(); return new Iterator<String>() { @Override public boolean hasNext() { return it.hasNext(); } @Override public String next() { return it.next().toString(); } }; } @Override public int size() { return headers.size(); } }; } return names; } @Override public MultiMap add(String name, String value) { HttpUtils.validateHeader(name, value); headers.add(toLowerCase(name), value); return this; } @Override public MultiMap add(String name, Iterable<String> values) { HttpUtils.validateHeader(name, values); headers.add(toLowerCase(name), values); return this; } @Override public MultiMap addAll(MultiMap headers) { for (Map.Entry<String, String> entry: headers.entries()) { add(entry.getKey(), entry.getValue()); } return this; } @Override public MultiMap addAll(Map<String, String> map) { for (Map.Entry<String, String> entry: map.entrySet()) { add(entry.getKey(), entry.getValue()); } return this; } @Override public MultiMap set(String name, String value) { HttpUtils.validateHeader(name, value); headers.set(toLowerCase(name), value); return this; } @Override public MultiMap set(String name, Iterable<String> values) { HttpUtils.validateHeader(name, values); headers.set(toLowerCase(name), values); return this; } @Override public MultiMap setAll(MultiMap httpHeaders) { clear(); for (Map.Entry<String, String> entry: httpHeaders) { add(entry.getKey(), entry.getValue()); } return this; } @Override public MultiMap remove(String name) { headers.remove(toLowerCase(name)); return this; } @Override public MultiMap clear() { headers.clear(); return this; } @Override public Iterator<Map.Entry<String, String>> iterator() { return entries().iterator(); } @Override public int size() { return names().size(); } @Override public MultiMap setAll(Map<String, String> headers) { for (Map.Entry<String, String> entry: headers.entrySet()) { add(entry.getKey(), entry.getValue()); } return this; } @Override public String get(CharSequence name) { CharSequence val = headers.get(toLowerCase(name)); return val != null ? val.toString() : null; } @Override public List<String> getAll(CharSequence name) { List<CharSequence> all = headers.getAll(toLowerCase(name)); return all != null ? all.stream().map(CharSequence::toString).collect(Collectors.toList()) : null; } @Override public boolean contains(CharSequence name) { return headers.contains(toLowerCase(name)); } @Override public boolean contains(CharSequence name, CharSequence value, boolean caseInsensitive) { return headers.contains(toLowerCase(name), value, caseInsensitive); } @Override public MultiMap add(CharSequence name, CharSequence value) { HttpUtils.validateHeader(name, value); headers.add(toLowerCase(name), value); return this; } @Override public MultiMap add(CharSequence name, Iterable<CharSequence> values) { HttpUtils.validateHeader(name, values); headers.add(toLowerCase(name), values); return this; } @Override public MultiMap set(CharSequence name, CharSequence value) { HttpUtils.validateHeader(name, value); headers.set(toLowerCase(name), value); return this; } @Override public MultiMap set(CharSequence name, Iterable<CharSequence> values) { HttpUtils.validateHeader(name, values); headers.set(toLowerCase(name), values); return this; } @Override public MultiMap remove(CharSequence name) { headers.remove(toLowerCase(name)); return this; } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_195_1
crossvul-java_data_bad_195_1
/* * Copyright (c) 2011-2017 Contributors to the Eclipse Foundation * * 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, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core.http.impl; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http2.Http2Headers; import io.vertx.core.MultiMap; import java.util.AbstractList; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a> */ public class Http2HeadersAdaptor implements MultiMap { static CharSequence toLowerCase(CharSequence s) { StringBuilder buffer = null; int len = s.length(); for (int index = 0; index < len; index++) { char c = s.charAt(index); if (c >= 'A' && c <= 'Z') { if (buffer == null) { buffer = new StringBuilder(s); } buffer.setCharAt(index, (char)(c + ('a' - 'A'))); } } if (buffer != null) { return buffer.toString(); } else { return s; } } private final Http2Headers headers; private Set<String> names; public Http2HeadersAdaptor(Http2Headers headers) { List<CharSequence> cookies = headers.getAll(HttpHeaderNames.COOKIE); if (cookies != null && cookies.size() > 1) { // combine the cookie values into 1 header entry. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 String value = cookies.stream().collect(Collectors.joining("; ")); headers.set(HttpHeaderNames.COOKIE, value); } this.headers = headers; } @Override public String get(String name) { CharSequence val = headers.get(toLowerCase(name)); return val != null ? val.toString() : null; } @Override public List<String> getAll(String name) { List<CharSequence> all = headers.getAll(toLowerCase(name)); if (all != null) { return new AbstractList<String>() { @Override public String get(int index) { return all.get(index).toString(); } @Override public int size() { return all.size(); } }; } return null; } @Override public List<Map.Entry<String, String>> entries() { return headers.names() .stream() .map(name -> new AbstractMap.SimpleEntry<>(name.toString(), headers.get(name).toString())) .collect(Collectors.toList()); } @Override public boolean contains(String name) { return headers.contains(toLowerCase(name)); } @Override public boolean contains(String name, String value, boolean caseInsensitive) { return headers.contains(toLowerCase(name), value, caseInsensitive); } @Override public boolean isEmpty() { return headers.isEmpty(); } @Override public Set<String> names() { if (names == null) { names = new AbstractSet<String>() { @Override public Iterator<String> iterator() { Iterator<CharSequence> it = headers.names().iterator(); return new Iterator<String>() { @Override public boolean hasNext() { return it.hasNext(); } @Override public String next() { return it.next().toString(); } }; } @Override public int size() { return headers.size(); } }; } return names; } @Override public MultiMap add(String name, String value) { headers.add(toLowerCase(name), value); return this; } @Override public MultiMap add(String name, Iterable<String> values) { headers.add(toLowerCase(name), values); return this; } @Override public MultiMap addAll(MultiMap headers) { for (Map.Entry<String, String> entry: headers.entries()) { add(entry.getKey(), entry.getValue()); } return this; } @Override public MultiMap addAll(Map<String, String> map) { for (Map.Entry<String, String> entry: map.entrySet()) { add(entry.getKey(), entry.getValue()); } return this; } @Override public MultiMap set(String name, String value) { headers.set(toLowerCase(name), value); return this; } @Override public MultiMap set(String name, Iterable<String> values) { headers.set(toLowerCase(name), values); return this; } @Override public MultiMap setAll(MultiMap httpHeaders) { clear(); for (Map.Entry<String, String> entry: httpHeaders) { add(entry.getKey(), entry.getValue()); } return this; } @Override public MultiMap remove(String name) { headers.remove(toLowerCase(name)); return this; } @Override public MultiMap clear() { headers.clear(); return this; } @Override public Iterator<Map.Entry<String, String>> iterator() { return entries().iterator(); } @Override public int size() { return names().size(); } @Override public MultiMap setAll(Map<String, String> headers) { for (Map.Entry<String, String> entry: headers.entrySet()) { add(entry.getKey(), entry.getValue()); } return this; } @Override public String get(CharSequence name) { CharSequence val = headers.get(toLowerCase(name)); return val != null ? val.toString() : null; } @Override public List<String> getAll(CharSequence name) { List<CharSequence> all = headers.getAll(toLowerCase(name)); return all != null ? all.stream().map(CharSequence::toString).collect(Collectors.toList()) : null; } @Override public boolean contains(CharSequence name) { return headers.contains(toLowerCase(name)); } @Override public boolean contains(CharSequence name, CharSequence value, boolean caseInsensitive) { return headers.contains(toLowerCase(name), value, caseInsensitive); } @Override public MultiMap add(CharSequence name, CharSequence value) { headers.add(toLowerCase(name), value); return this; } @Override public MultiMap add(CharSequence name, Iterable<CharSequence> values) { headers.add(toLowerCase(name), values); return this; } @Override public MultiMap set(CharSequence name, CharSequence value) { headers.set(toLowerCase(name), value); return this; } @Override public MultiMap set(CharSequence name, Iterable<CharSequence> values) { headers.set(toLowerCase(name), values); return this; } @Override public MultiMap remove(CharSequence name) { headers.remove(toLowerCase(name)); return this; } }
./CrossVul/dataset_final_sorted/CWE-20/java/bad_195_1
crossvul-java_data_bad_761_2
/** * Copyright (c) 2001-2019 Mathew A. Nelson and Robocode contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * https://robocode.sourceforge.io/license/epl-v10.html */ package net.sf.robocode.test.robots; import net.sf.robocode.test.helpers.RobocodeTestBed; import org.junit.Assert; import robocode.control.events.TurnEndedEvent; /** * @author Flemming N. Larsen (original) */ public class TestConstructorHttpAttack extends RobocodeTestBed { private boolean messagedInitialization; private boolean messagedAccessDenied; @Override public String getRobotNames() { return "tested.robots.ConstructorHttpAttack,sample.Target"; } @Override public void onTurnEnded(TurnEndedEvent event) { super.onTurnEnded(event); final String out = event.getTurnSnapshot().getRobots()[0].getOutputStreamSnapshot(); if (out.contains("An error occurred during initialization")) { messagedInitialization = true; } if (out.contains("access denied (java.net.SocketPermission") || out.contains("access denied (\"java.net.SocketPermission\"")) { messagedAccessDenied = true; } } @Override protected void runTeardown() { Assert.assertTrue("Error during initialization", messagedInitialization); Assert.assertTrue("HTTP connection is not allowed", messagedAccessDenied); } @Override protected int getExpectedErrors() { return hasJavaNetURLPermission ? 3 : 2; // Security error must be reported as an error } }
./CrossVul/dataset_final_sorted/CWE-20/java/bad_761_2
crossvul-java_data_good_4128_1
package com.ctrip.framework.apollo.adminservice.filter; import com.ctrip.framework.apollo.biz.config.BizConfig; import com.google.common.base.Splitter; import com.google.common.base.Strings; import java.io.IOException; import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; public class AdminServiceAuthenticationFilter implements Filter { private static final Logger logger = LoggerFactory .getLogger(AdminServiceAuthenticationFilter.class); private static final Splitter ACCESS_TOKEN_SPLITTER = Splitter.on(",").omitEmptyStrings() .trimResults(); private final BizConfig bizConfig; private volatile String lastAccessTokens; private volatile List<String> accessTokenList; public AdminServiceAuthenticationFilter(BizConfig bizConfig) { this.bizConfig = bizConfig; } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (bizConfig.isAdminServiceAccessControlEnabled()) { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String token = request.getHeader(HttpHeaders.AUTHORIZATION); if (!checkAccessToken(token)) { logger.warn("Invalid access token: {} for uri: {}", token, request.getRequestURI()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); return; } } chain.doFilter(req, resp); } private boolean checkAccessToken(String token) { String accessTokens = bizConfig.getAdminServiceAccessTokens(); // if user forget to configure access tokens, then default to pass if (Strings.isNullOrEmpty(accessTokens)) { return true; } // no need to check if (Strings.isNullOrEmpty(token)) { return false; } // update cache if (!accessTokens.equals(lastAccessTokens)) { synchronized (this) { accessTokenList = ACCESS_TOKEN_SPLITTER.splitToList(accessTokens); lastAccessTokens = accessTokens; } } return accessTokenList.contains(token); } @Override public void destroy() { } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_4128_1
crossvul-java_data_bad_195_3
/* * Copyright (c) 2011-2017 Contributors to the Eclipse Foundation * * 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, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core.http.impl; import io.netty.buffer.ByteBuf; import io.netty.buffer.CompositeByteBuf; import io.netty.buffer.Unpooled; import io.vertx.codegen.annotations.Nullable; import io.vertx.core.*; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.CaseInsensitiveHeaders; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpClientResponse; import io.vertx.core.http.HttpConnection; import io.vertx.core.http.HttpFrame; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpVersion; import io.vertx.core.impl.ContextInternal; import io.vertx.core.impl.VertxInternal; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.core.net.NetSocket; import java.util.List; import java.util.Objects; import static io.vertx.core.http.HttpHeaders.*; /** * This class is optimised for performance when used on the same event loop that is was passed to the handler with. * However it can be used safely from other threads. * * The internal state is protected using the synchronized keyword. If always used on the same event loop, then * we benefit from biased locking which makes the overhead of synchronized near zero. * * This class uses {@code this} for synchronization purpose. The {@link #client} or{@link #stream} instead are * called must not be called under this lock to avoid deadlocks. * * @author <a href="http://tfox.org">Tim Fox</a> */ public class HttpClientRequestImpl extends HttpClientRequestBase implements HttpClientRequest { static final Logger log = LoggerFactory.getLogger(ConnectionManager.class); private final VertxInternal vertx; private Handler<HttpClientResponse> respHandler; private Handler<Void> endHandler; private boolean chunked; private String hostHeader; private String rawMethod; private Handler<Void> continueHandler; private Handler<Void> drainHandler; private Handler<HttpClientRequest> pushHandler; private Handler<HttpConnection> connectionHandler; private boolean completed; private Handler<Void> completionHandler; private Long reset; private ByteBuf pendingChunks; private int pendingMaxSize = -1; private int followRedirects; private long written; private CaseInsensitiveHeaders headers; private HttpClientStream stream; private boolean connecting; // completed => drainHandler = null HttpClientRequestImpl(HttpClientImpl client, boolean ssl, HttpMethod method, String host, int port, String relativeURI, VertxInternal vertx) { super(client, ssl, method, host, port, relativeURI); this.chunked = false; this.vertx = vertx; } @Override public int streamId() { HttpClientStream s; synchronized (this) { if ((s = stream) == null) { return -1; } } return s.id(); } @Override public synchronized HttpClientRequest handler(Handler<HttpClientResponse> handler) { if (handler != null) { checkComplete(); respHandler = checkConnect(method, handler); } else { respHandler = null; } return this; } @Override public HttpClientRequest pause() { return this; } @Override public HttpClientRequest resume() { return this; } @Override public HttpClientRequest setFollowRedirects(boolean followRedirects) { synchronized (this) { checkComplete(); if (followRedirects) { this.followRedirects = client.getOptions().getMaxRedirects() - 1; } else { this.followRedirects = 0; } return this; } } @Override public HttpClientRequest endHandler(Handler<Void> handler) { synchronized (this) { if (handler != null) { checkComplete(); } endHandler = handler; return this; } } @Override public HttpClientRequestImpl setChunked(boolean chunked) { synchronized (this) { checkComplete(); if (written > 0) { throw new IllegalStateException("Cannot set chunked after data has been written on request"); } // HTTP 1.0 does not support chunking so we ignore this if HTTP 1.0 if (client.getOptions().getProtocolVersion() != io.vertx.core.http.HttpVersion.HTTP_1_0) { this.chunked = chunked; } return this; } } @Override public synchronized boolean isChunked() { return chunked; } @Override public synchronized String getRawMethod() { return rawMethod; } @Override public synchronized HttpClientRequest setRawMethod(String method) { this.rawMethod = method; return this; } @Override public synchronized HttpClientRequest setHost(String host) { this.hostHeader = host; return this; } @Override public synchronized String getHost() { return hostHeader; } @Override public synchronized MultiMap headers() { if (headers == null) { headers = new CaseInsensitiveHeaders(); } return headers; } @Override public synchronized HttpClientRequest putHeader(String name, String value) { checkComplete(); headers().set(name, value); return this; } @Override public synchronized HttpClientRequest putHeader(String name, Iterable<String> values) { checkComplete(); headers().set(name, values); return this; } @Override public HttpClientRequest setWriteQueueMaxSize(int maxSize) { HttpClientStream s; synchronized (this) { checkComplete(); if ((s = stream) == null) { pendingMaxSize = maxSize; return this; } } s.doSetWriteQueueMaxSize(maxSize); return this; } @Override public boolean writeQueueFull() { HttpClientStream s; synchronized (this) { checkComplete(); if ((s = stream) == null) { // Should actually check with max queue size and not always blindly return false return false; } } return s.isNotWritable(); } @Override public HttpClientRequest drainHandler(Handler<Void> handler) { synchronized (this) { if (handler != null) { checkComplete(); drainHandler = handler; HttpClientStream s; if ((s = stream) == null) { return this; } s.getContext().runOnContext(v -> { synchronized (HttpClientRequestImpl.this) { if (!stream.isNotWritable()) { handleDrained(); } } }); } else { drainHandler = null; } return this; } } @Override public synchronized HttpClientRequest continueHandler(Handler<Void> handler) { if (handler != null) { checkComplete(); } this.continueHandler = handler; return this; } @Override public HttpClientRequest sendHead() { return sendHead(null); } @Override public synchronized HttpClientRequest sendHead(Handler<HttpVersion> headersHandler) { checkComplete(); checkResponseHandler(); if (stream != null) { throw new IllegalStateException("Head already written"); } else { connect(headersHandler); } return this; } @Override public synchronized HttpClientRequest putHeader(CharSequence name, CharSequence value) { checkComplete(); headers().set(name, value); return this; } @Override public synchronized HttpClientRequest putHeader(CharSequence name, Iterable<CharSequence> values) { checkComplete(); headers().set(name, values); return this; } @Override public synchronized HttpClientRequest pushHandler(Handler<HttpClientRequest> handler) { pushHandler = handler; return this; } @Override public boolean reset(long code) { HttpClientStream s; synchronized (this) { if (reset != null) { return false; } reset = code; if (tryComplete()) { if (completionHandler != null) { completionHandler.handle(null); } } s = stream; } if (s != null) { s.reset(code); } return true; } private boolean tryComplete() { if (!completed) { completed = true; drainHandler = null; return true; } else { return false; } } @Override public HttpConnection connection() { HttpClientStream s; synchronized (this) { if ((s = stream) == null) { return null; } } return s.connection(); } @Override public synchronized HttpClientRequest connectionHandler(@Nullable Handler<HttpConnection> handler) { connectionHandler = handler; return this; } @Override public synchronized HttpClientRequest writeCustomFrame(int type, int flags, Buffer payload) { HttpClientStream s; synchronized (this) { checkComplete(); if ((s = stream) == null) { throw new IllegalStateException("Not yet connected"); } } s.writeFrame(type, flags, payload.getByteBuf()); return this; } void handleDrained() { Handler<Void> handler; synchronized (this) { if ((handler = drainHandler) == null) { return; } } try { handler.handle(null); } catch (Throwable t) { handleException(t); } } private void handleNextRequest(HttpClientRequestImpl next, long timeoutMs) { next.handler(respHandler); next.exceptionHandler(exceptionHandler()); exceptionHandler(null); next.endHandler(endHandler); next.pushHandler = pushHandler; next.followRedirects = followRedirects - 1; next.written = written; if (next.hostHeader == null) { next.hostHeader = hostHeader; } if (headers != null && next.headers == null) { next.headers().addAll(headers); } Future<Void> fut = Future.future(); fut.setHandler(ar -> { if (ar.succeeded()) { if (timeoutMs > 0) { next.setTimeout(timeoutMs); } next.end(); } else { next.handleException(ar.cause()); } }); if (exceptionOccurred != null) { fut.fail(exceptionOccurred); } else if (completed) { fut.complete(); } else { exceptionHandler(err -> { if (!fut.isComplete()) { fut.fail(err); } }); completionHandler = v -> { if (!fut.isComplete()) { fut.complete(); } }; } } protected void doHandleResponse(HttpClientResponseImpl resp, long timeoutMs) { if (reset == null) { int statusCode = resp.statusCode(); if (followRedirects > 0 && statusCode >= 300 && statusCode < 400) { Future<HttpClientRequest> next = client.redirectHandler().apply(resp); if (next != null) { next.setHandler(ar -> { if (ar.succeeded()) { handleNextRequest((HttpClientRequestImpl) ar.result(), timeoutMs); } else { handleException(ar.cause()); } }); return; } } if (statusCode == 100) { if (continueHandler != null) { continueHandler.handle(null); } } else { if (respHandler != null) { respHandler.handle(resp); } if (endHandler != null) { endHandler.handle(null); } } } } @Override protected String hostHeader() { return hostHeader != null ? hostHeader : super.hostHeader(); } private Handler<HttpClientResponse> checkConnect(io.vertx.core.http.HttpMethod method, Handler<HttpClientResponse> handler) { if (method == io.vertx.core.http.HttpMethod.CONNECT) { // special handling for CONNECT handler = connectHandler(handler); } return handler; } private Handler<HttpClientResponse> connectHandler(Handler<HttpClientResponse> responseHandler) { Objects.requireNonNull(responseHandler, "no null responseHandler accepted"); return resp -> { HttpClientResponse response; if (resp.statusCode() == 200) { // connect successful force the modification of the ChannelPipeline // beside this also pause the socket for now so the user has a chance to register its dataHandler // after received the NetSocket NetSocket socket = resp.netSocket(); socket.pause(); response = new HttpClientResponse() { private boolean resumed; @Override public HttpClientRequest request() { return resp.request(); } @Override public int statusCode() { return resp.statusCode(); } @Override public String statusMessage() { return resp.statusMessage(); } @Override public MultiMap headers() { return resp.headers(); } @Override public String getHeader(String headerName) { return resp.getHeader(headerName); } @Override public String getHeader(CharSequence headerName) { return resp.getHeader(headerName); } @Override public String getTrailer(String trailerName) { return resp.getTrailer(trailerName); } @Override public MultiMap trailers() { return resp.trailers(); } @Override public List<String> cookies() { return resp.cookies(); } @Override public HttpVersion version() { return resp.version(); } @Override public HttpClientResponse bodyHandler(Handler<Buffer> bodyHandler) { resp.bodyHandler(bodyHandler); return this; } @Override public HttpClientResponse customFrameHandler(Handler<HttpFrame> handler) { resp.customFrameHandler(handler); return this; } @Override public synchronized NetSocket netSocket() { if (!resumed) { resumed = true; vertx.getContext().runOnContext((v) -> socket.resume()); // resume the socket now as the user had the chance to register a dataHandler } return socket; } @Override public HttpClientResponse endHandler(Handler<Void> endHandler) { resp.endHandler(endHandler); return this; } @Override public HttpClientResponse handler(Handler<Buffer> handler) { resp.handler(handler); return this; } @Override public HttpClientResponse pause() { resp.pause(); return this; } @Override public HttpClientResponse resume() { resp.resume(); return this; } @Override public HttpClientResponse exceptionHandler(Handler<Throwable> handler) { resp.exceptionHandler(handler); return this; } }; } else { response = resp; } responseHandler.handle(response); }; } private synchronized void connect(Handler<HttpVersion> headersHandler) { if (!connecting) { if (method == HttpMethod.OTHER && rawMethod == null) { throw new IllegalStateException("You must provide a rawMethod when using an HttpMethod.OTHER method"); } String peerHost; if (hostHeader != null) { int idx = hostHeader.lastIndexOf(':'); if (idx != -1) { peerHost = hostHeader.substring(0, idx); } else { peerHost = hostHeader; } } else { peerHost = host; } // Capture some stuff Handler<HttpConnection> initializer = connectionHandler; ContextInternal connectCtx = vertx.getOrCreateContext(); // We defer actual connection until the first part of body is written or end is called // This gives the user an opportunity to set an exception handler before connecting so // they can capture any exceptions on connection connecting = true; client.getConnectionForRequest(connectCtx, peerHost, ssl, port, host, ar1 -> { if (ar1.succeeded()) { HttpClientStream stream = ar1.result(); ContextInternal ctx = (ContextInternal) stream.getContext(); if (stream.id() == 1 && initializer != null) { ctx.executeFromIO(v -> { initializer.handle(stream.connection()); }); } // No need to synchronize as the thread is the same that set exceptionOccurred to true // exceptionOccurred=true getting the connection => it's a TimeoutException if (exceptionOccurred != null || reset != null) { stream.reset(0); } else { ctx.executeFromIO(v -> { connected(headersHandler, stream); }); } } else { connectCtx.executeFromIO(v -> { handleException(ar1.cause()); }); } }); } } private void connected(Handler<HttpVersion> headersHandler, HttpClientStream stream) { synchronized (this) { this.stream = stream; stream.beginRequest(this); // If anything was written or the request ended before we got the connection, then // we need to write it now if (pendingMaxSize != -1) { stream.doSetWriteQueueMaxSize(pendingMaxSize); } if (pendingChunks != null) { ByteBuf pending = pendingChunks; pendingChunks = null; if (completed) { // we also need to write the head so optimize this and write all out in once stream.writeHead(method, rawMethod, uri, headers, hostHeader(), chunked, pending, true); stream.reportBytesWritten(written); stream.endRequest(); } else { stream.writeHead(method, rawMethod, uri, headers, hostHeader(), chunked, pending, false); } } else { if (completed) { // we also need to write the head so optimize this and write all out in once stream.writeHead(method, rawMethod, uri, headers, hostHeader(), chunked, null, true); stream.reportBytesWritten(written); stream.endRequest(); } else { stream.writeHead(method, rawMethod, uri, headers, hostHeader(), chunked, null, false); } } this.connecting = false; this.stream = stream; } if (headersHandler != null) { headersHandler.handle(stream.version()); } } private boolean contentLengthSet() { return headers != null && headers().contains(CONTENT_LENGTH); } @Override public void end(String chunk) { end(Buffer.buffer(chunk)); } @Override public void end(String chunk, String enc) { Objects.requireNonNull(enc, "no null encoding accepted"); end(Buffer.buffer(chunk, enc)); } @Override public void end(Buffer chunk) { write(chunk.getByteBuf(), true); } @Override public void end() { write(null, true); } @Override public HttpClientRequestImpl write(Buffer chunk) { ByteBuf buf = chunk.getByteBuf(); write(buf, false); return this; } @Override public HttpClientRequestImpl write(String chunk) { return write(Buffer.buffer(chunk)); } @Override public HttpClientRequestImpl write(String chunk, String enc) { Objects.requireNonNull(enc, "no null encoding accepted"); return write(Buffer.buffer(chunk, enc)); } private void write(ByteBuf buff, boolean end) { HttpClientStream s; synchronized (this) { checkComplete(); checkResponseHandler(); if (end) { if (buff != null && !chunked && !contentLengthSet()) { headers().set(CONTENT_LENGTH, String.valueOf(buff.readableBytes())); } } else { if (!chunked && !contentLengthSet()) { throw new IllegalStateException("You must set the Content-Length header to be the total size of the message " + "body BEFORE sending any data if you are not using HTTP chunked encoding."); } } if (buff == null && !end) { // nothing to write to the connection just return return; } if (buff != null) { written += buff.readableBytes(); } if ((s = stream) == null) { if (buff != null) { if (pendingChunks == null) { pendingChunks = buff; } else { CompositeByteBuf pending; if (pendingChunks instanceof CompositeByteBuf) { pending = (CompositeByteBuf) pendingChunks; } else { pending = Unpooled.compositeBuffer(); pending.addComponent(true, pendingChunks); pendingChunks = pending; } pending.addComponent(true, buff); } } if (end) { tryComplete(); if (completionHandler != null) { completionHandler.handle(null); } } connect(null); return; } } s.writeBuffer(buff, end); if (end) { s.reportBytesWritten(written); // MUST BE READ UNDER SYNCHRONIZATION } if (end) { Handler<Void> handler; synchronized (this) { tryComplete(); s.endRequest(); if ((handler = completionHandler) == null) { return; } } handler.handle(null); } } protected void checkComplete() { if (completed) { throw new IllegalStateException("Request already complete"); } } private void checkResponseHandler() { if (respHandler == null) { throw new IllegalStateException("You must set an handler for the HttpClientResponse before connecting"); } } synchronized Handler<HttpClientRequest> pushHandler() { return pushHandler; } }
./CrossVul/dataset_final_sorted/CWE-20/java/bad_195_3
crossvul-java_data_bad_4128_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-20/java/bad_4128_1
crossvul-java_data_bad_418_3
package eu.siacs.conversations.ui; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.PendingIntent; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.ClipboardManager; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.content.res.TypedArray; import android.databinding.DataBindingUtil; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.support.annotation.BoolRes; import android.support.annotation.StringRes; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog.Builder; import android.support.v7.app.AppCompatDelegate; import android.text.InputType; import android.util.DisplayMetrics; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import eu.siacs.conversations.Config; import eu.siacs.conversations.R; import eu.siacs.conversations.crypto.PgpEngine; import eu.siacs.conversations.databinding.DialogQuickeditBinding; import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Contact; import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Presences; import eu.siacs.conversations.services.AvatarService; import eu.siacs.conversations.services.BarcodeProvider; import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService.XmppConnectionBinder; import eu.siacs.conversations.ui.util.MenuDoubleTabUtil; import eu.siacs.conversations.ui.util.PresenceSelector; import eu.siacs.conversations.ui.util.SoftKeyboardUtils; import eu.siacs.conversations.utils.ExceptionHelper; import eu.siacs.conversations.utils.ThemeHelper; import eu.siacs.conversations.xmpp.OnKeyStatusUpdated; import eu.siacs.conversations.xmpp.OnUpdateBlocklist; import rocks.xmpp.addr.Jid; public abstract class XmppActivity extends ActionBarActivity { public static final String EXTRA_ACCOUNT = "account"; protected static final int REQUEST_ANNOUNCE_PGP = 0x0101; protected static final int REQUEST_INVITE_TO_CONVERSATION = 0x0102; protected static final int REQUEST_CHOOSE_PGP_ID = 0x0103; protected static final int REQUEST_BATTERY_OP = 0x49ff; public XmppConnectionService xmppConnectionService; public boolean xmppConnectionServiceBound = false; protected int mColorRed; protected static final String FRAGMENT_TAG_DIALOG = "dialog"; private boolean isCameraFeatureAvailable = false; protected int mTheme; protected boolean mUsingEnterKey = false; protected Toast mToast; public Runnable onOpenPGPKeyPublished = () -> Toast.makeText(XmppActivity.this, R.string.openpgp_has_been_published, Toast.LENGTH_SHORT).show(); protected ConferenceInvite mPendingConferenceInvite = null; protected ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { XmppConnectionBinder binder = (XmppConnectionBinder) service; xmppConnectionService = binder.getService(); xmppConnectionServiceBound = true; registerListeners(); onBackendConnected(); } @Override public void onServiceDisconnected(ComponentName arg0) { xmppConnectionServiceBound = false; } }; private DisplayMetrics metrics; private long mLastUiRefresh = 0; private Handler mRefreshUiHandler = new Handler(); private Runnable mRefreshUiRunnable = () -> { mLastUiRefresh = SystemClock.elapsedRealtime(); refreshUiReal(); }; private UiCallback<Conversation> adhocCallback = new UiCallback<Conversation>() { @Override public void success(final Conversation conversation) { runOnUiThread(() -> { switchToConversation(conversation); hideToast(); }); } @Override public void error(final int errorCode, Conversation object) { runOnUiThread(() -> replaceToast(getString(errorCode))); } @Override public void userInputRequried(PendingIntent pi, Conversation object) { } }; public boolean mSkipBackgroundBinding = false; public static boolean cancelPotentialWork(Message message, ImageView imageView) { final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); if (bitmapWorkerTask != null) { final Message oldMessage = bitmapWorkerTask.message; if (oldMessage == null || message != oldMessage) { bitmapWorkerTask.cancel(true); } else { return false; } } return true; } private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) { if (imageView != null) { final Drawable drawable = imageView.getDrawable(); if (drawable instanceof AsyncDrawable) { final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable; return asyncDrawable.getBitmapWorkerTask(); } } return null; } protected void hideToast() { if (mToast != null) { mToast.cancel(); } } protected void replaceToast(String msg) { replaceToast(msg, true); } protected void replaceToast(String msg, boolean showlong) { hideToast(); mToast = Toast.makeText(this, msg, showlong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT); mToast.show(); } protected final void refreshUi() { final long diff = SystemClock.elapsedRealtime() - mLastUiRefresh; if (diff > Config.REFRESH_UI_INTERVAL) { mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable); runOnUiThread(mRefreshUiRunnable); } else { final long next = Config.REFRESH_UI_INTERVAL - diff; mRefreshUiHandler.removeCallbacks(mRefreshUiRunnable); mRefreshUiHandler.postDelayed(mRefreshUiRunnable, next); } } abstract protected void refreshUiReal(); @Override protected void onStart() { super.onStart(); if (!xmppConnectionServiceBound) { if (this.mSkipBackgroundBinding) { Log.d(Config.LOGTAG,"skipping background binding"); } else { connectToBackend(); } } else { this.registerListeners(); this.onBackendConnected(); } } public void connectToBackend() { Intent intent = new Intent(this, XmppConnectionService.class); intent.setAction("ui"); startService(intent); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); if (xmppConnectionServiceBound) { this.unregisterListeners(); unbindService(mConnection); xmppConnectionServiceBound = false; } } public boolean hasPgp() { return xmppConnectionService.getPgpEngine() != null; } public void showInstallPgpDialog() { Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.openkeychain_required)); builder.setIconAttribute(android.R.attr.alertDialogIcon); builder.setMessage(getText(R.string.openkeychain_required_long)); builder.setNegativeButton(getString(R.string.cancel), null); builder.setNeutralButton(getString(R.string.restart), (dialog, which) -> { if (xmppConnectionServiceBound) { unbindService(mConnection); xmppConnectionServiceBound = false; } stopService(new Intent(XmppActivity.this, XmppConnectionService.class)); finish(); }); builder.setPositiveButton(getString(R.string.install), (dialog, which) -> { Uri uri = Uri .parse("market://details?id=org.sufficientlysecure.keychain"); Intent marketIntent = new Intent(Intent.ACTION_VIEW, uri); PackageManager manager = getApplicationContext() .getPackageManager(); List<ResolveInfo> infos = manager .queryIntentActivities(marketIntent, 0); if (infos.size() > 0) { startActivity(marketIntent); } else { uri = Uri.parse("http://www.openkeychain.org/"); Intent browserIntent = new Intent( Intent.ACTION_VIEW, uri); startActivity(browserIntent); } finish(); }); builder.create().show(); } abstract void onBackendConnected(); protected void registerListeners() { if (this instanceof XmppConnectionService.OnConversationUpdate) { this.xmppConnectionService.setOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this); } if (this instanceof XmppConnectionService.OnAccountUpdate) { this.xmppConnectionService.setOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this); } if (this instanceof XmppConnectionService.OnCaptchaRequested) { this.xmppConnectionService.setOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this); } if (this instanceof XmppConnectionService.OnRosterUpdate) { this.xmppConnectionService.setOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this); } if (this instanceof XmppConnectionService.OnMucRosterUpdate) { this.xmppConnectionService.setOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this); } if (this instanceof OnUpdateBlocklist) { this.xmppConnectionService.setOnUpdateBlocklistListener((OnUpdateBlocklist) this); } if (this instanceof XmppConnectionService.OnShowErrorToast) { this.xmppConnectionService.setOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this); } if (this instanceof OnKeyStatusUpdated) { this.xmppConnectionService.setOnKeyStatusUpdatedListener((OnKeyStatusUpdated) this); } } protected void unregisterListeners() { if (this instanceof XmppConnectionService.OnConversationUpdate) { this.xmppConnectionService.removeOnConversationListChangedListener((XmppConnectionService.OnConversationUpdate) this); } if (this instanceof XmppConnectionService.OnAccountUpdate) { this.xmppConnectionService.removeOnAccountListChangedListener((XmppConnectionService.OnAccountUpdate) this); } if (this instanceof XmppConnectionService.OnCaptchaRequested) { this.xmppConnectionService.removeOnCaptchaRequestedListener((XmppConnectionService.OnCaptchaRequested) this); } if (this instanceof XmppConnectionService.OnRosterUpdate) { this.xmppConnectionService.removeOnRosterUpdateListener((XmppConnectionService.OnRosterUpdate) this); } if (this instanceof XmppConnectionService.OnMucRosterUpdate) { this.xmppConnectionService.removeOnMucRosterUpdateListener((XmppConnectionService.OnMucRosterUpdate) this); } if (this instanceof OnUpdateBlocklist) { this.xmppConnectionService.removeOnUpdateBlocklistListener((OnUpdateBlocklist) this); } if (this instanceof XmppConnectionService.OnShowErrorToast) { this.xmppConnectionService.removeOnShowErrorToastListener((XmppConnectionService.OnShowErrorToast) this); } if (this instanceof OnKeyStatusUpdated) { this.xmppConnectionService.removeOnNewKeysAvailableListener((OnKeyStatusUpdated) this); } } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: startActivity(new Intent(this, SettingsActivity.class)); break; case R.id.action_accounts: startActivity(new Intent(this, ManageAccountActivity.class)); break; case android.R.id.home: finish(); break; case R.id.action_show_qr_code: showQrCode(); break; } return super.onOptionsItemSelected(item); } public void selectPresence(final Conversation conversation, final PresenceSelector.OnPresenceSelected listener) { final Contact contact = conversation.getContact(); if (!contact.showInRoster()) { showAddToRosterDialog(conversation.getContact()); } else { final Presences presences = contact.getPresences(); if (presences.size() == 0) { if (!contact.getOption(Contact.Options.TO) && !contact.getOption(Contact.Options.ASKING) && contact.getAccount().getStatus() == Account.State.ONLINE) { showAskForPresenceDialog(contact); } else if (!contact.getOption(Contact.Options.TO) || !contact.getOption(Contact.Options.FROM)) { PresenceSelector.warnMutualPresenceSubscription(this, conversation, listener); } else { conversation.setNextCounterpart(null); listener.onPresenceSelected(); } } else if (presences.size() == 1) { String presence = presences.toResourceArray()[0]; try { conversation.setNextCounterpart(Jid.of(contact.getJid().getLocal(), contact.getJid().getDomain(), presence)); } catch (IllegalArgumentException e) { conversation.setNextCounterpart(null); } listener.onPresenceSelected(); } else { PresenceSelector.showPresenceSelectionDialog(this, conversation, listener); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); metrics = getResources().getDisplayMetrics(); ExceptionHelper.init(getApplicationContext()); this.isCameraFeatureAvailable = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA); mColorRed = ContextCompat.getColor(this, R.color.red800); this.mTheme = findTheme(); setTheme(this.mTheme); this.mUsingEnterKey = usingEnterKey(); } protected boolean isCameraFeatureAvailable() { return this.isCameraFeatureAvailable; } public boolean isDarkTheme() { return ThemeHelper.isDark(mTheme); } public int getThemeResource(int r_attr_name, int r_drawable_def) { int[] attrs = {r_attr_name}; TypedArray ta = this.getTheme().obtainStyledAttributes(attrs); int res = ta.getResourceId(0, r_drawable_def); ta.recycle(); return res; } protected boolean isOptimizingBattery() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE); return pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName()); } else { return false; } } protected boolean isAffectedByDataSaver() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return cm != null && cm.isActiveNetworkMetered() && cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED; } else { return false; } } protected boolean usingEnterKey() { return getBooleanPreference("display_enter_key", R.bool.display_enter_key); } protected SharedPreferences getPreferences() { return PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); } protected boolean getBooleanPreference(String name, @BoolRes int res) { return getPreferences().getBoolean(name, getResources().getBoolean(res)); } public void switchToConversation(Conversation conversation) { switchToConversation(conversation, null); } public void switchToConversationAndQuote(Conversation conversation, String text) { switchToConversation(conversation, text, true, null, false); } public void switchToConversation(Conversation conversation, String text) { switchToConversation(conversation, text, false, null, false); } public void highlightInMuc(Conversation conversation, String nick) { switchToConversation(conversation, null, false, nick, false); } public void privateMsgInMuc(Conversation conversation, String nick) { switchToConversation(conversation, null, false, nick, true); } private void switchToConversation(Conversation conversation, String text, boolean asQuote, String nick, boolean pm) { Intent intent = new Intent(this, ConversationsActivity.class); intent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION); intent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid()); if (text != null) { intent.putExtra(Intent.EXTRA_TEXT, text); if (asQuote) { intent.putExtra(ConversationsActivity.EXTRA_AS_QUOTE, true); } } if (nick != null) { intent.putExtra(ConversationsActivity.EXTRA_NICK, nick); intent.putExtra(ConversationsActivity.EXTRA_IS_PRIVATE_MESSAGE, pm); } intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } public void switchToContactDetails(Contact contact) { switchToContactDetails(contact, null); } public void switchToContactDetails(Contact contact, String messageFingerprint) { Intent intent = new Intent(this, ContactDetailsActivity.class); intent.setAction(ContactDetailsActivity.ACTION_VIEW_CONTACT); intent.putExtra(EXTRA_ACCOUNT, contact.getAccount().getJid().asBareJid().toString()); intent.putExtra("contact", contact.getJid().toString()); intent.putExtra("fingerprint", messageFingerprint); startActivity(intent); } public void switchToAccount(Account account, String fingerprint) { switchToAccount(account, false, fingerprint); } public void switchToAccount(Account account) { switchToAccount(account, false, null); } public void switchToAccount(Account account, boolean init, String fingerprint) { Intent intent = new Intent(this, EditAccountActivity.class); intent.putExtra("jid", account.getJid().asBareJid().toString()); intent.putExtra("init", init); if (init) { intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION); } if (fingerprint != null) { intent.putExtra("fingerprint", fingerprint); } startActivity(intent); if (init) { overridePendingTransition(0, 0); } } protected void delegateUriPermissionsToService(Uri uri) { Intent intent = new Intent(this, XmppConnectionService.class); intent.setAction(Intent.ACTION_SEND); intent.setData(uri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); try { startService(intent); } catch (Exception e) { Log.e(Config.LOGTAG,"unable to delegate uri permission",e); } } protected void inviteToConversation(Conversation conversation) { startActivityForResult(ChooseContactActivity.create(this,conversation), REQUEST_INVITE_TO_CONVERSATION); } protected void announcePgp(final Account account, final Conversation conversation, Intent intent, final Runnable onSuccess) { if (account.getPgpId() == 0) { choosePgpSignId(account); } else { String status = null; if (manuallyChangePresence()) { status = account.getPresenceStatusMessage(); } if (status == null) { status = ""; } xmppConnectionService.getPgpEngine().generateSignature(intent, account, status, new UiCallback<String>() { @Override public void userInputRequried(PendingIntent pi, String signature) { try { startIntentSenderForResult(pi.getIntentSender(), REQUEST_ANNOUNCE_PGP, null, 0, 0, 0); } catch (final SendIntentException ignored) { } } @Override public void success(String signature) { account.setPgpSignature(signature); xmppConnectionService.databaseBackend.updateAccount(account); xmppConnectionService.sendPresence(account); if (conversation != null) { conversation.setNextEncryption(Message.ENCRYPTION_PGP); xmppConnectionService.updateConversation(conversation); refreshUi(); } if (onSuccess != null) { runOnUiThread(onSuccess); } } @Override public void error(int error, String signature) { if (error == 0) { account.setPgpSignId(0); account.unsetPgpSignature(); xmppConnectionService.databaseBackend.updateAccount(account); choosePgpSignId(account); } else { displayErrorDialog(error); } } }); } } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.JELLY_BEAN) protected void setListItemBackgroundOnView(View view) { int sdk = android.os.Build.VERSION.SDK_INT; if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { view.setBackgroundDrawable(getResources().getDrawable(R.drawable.greybackground)); } else { view.setBackground(getResources().getDrawable(R.drawable.greybackground)); } } protected void choosePgpSignId(Account account) { xmppConnectionService.getPgpEngine().chooseKey(account, new UiCallback<Account>() { @Override public void success(Account account1) { } @Override public void error(int errorCode, Account object) { } @Override public void userInputRequried(PendingIntent pi, Account object) { try { startIntentSenderForResult(pi.getIntentSender(), REQUEST_CHOOSE_PGP_ID, null, 0, 0, 0); } catch (final SendIntentException ignored) { } } }); } protected void displayErrorDialog(final int errorCode) { runOnUiThread(() -> { Builder builder = new Builder(XmppActivity.this); builder.setIconAttribute(android.R.attr.alertDialogIcon); builder.setTitle(getString(R.string.error)); builder.setMessage(errorCode); builder.setNeutralButton(R.string.accept, null); builder.create().show(); }); } protected void showAddToRosterDialog(final Contact contact) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(contact.getJid().toString()); builder.setMessage(getString(R.string.not_in_roster)); builder.setNegativeButton(getString(R.string.cancel), null); builder.setPositiveButton(getString(R.string.add_contact), (dialog, which) -> xmppConnectionService.createContact(contact,true)); builder.create().show(); } private void showAskForPresenceDialog(final Contact contact) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(contact.getJid().toString()); builder.setMessage(R.string.request_presence_updates); builder.setNegativeButton(R.string.cancel, null); builder.setPositiveButton(R.string.request_now, (dialog, which) -> { if (xmppConnectionServiceBound) { xmppConnectionService.sendPresencePacket(contact .getAccount(), xmppConnectionService .getPresenceGenerator() .requestPresenceUpdatesFrom(contact)); } }); builder.create().show(); } protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback) { quickEdit(previousValue, callback, hint, false, false); } protected void quickEdit(String previousValue, @StringRes int hint, OnValueEdited callback, boolean permitEmpty) { quickEdit(previousValue, callback, hint, false, permitEmpty); } protected void quickPasswordEdit(String previousValue, OnValueEdited callback) { quickEdit(previousValue, callback, R.string.password, true, false); } @SuppressLint("InflateParams") private void quickEdit(final String previousValue, final OnValueEdited callback, final @StringRes int hint, boolean password, boolean permitEmpty) { AlertDialog.Builder builder = new AlertDialog.Builder(this); DialogQuickeditBinding binding = DataBindingUtil.inflate(getLayoutInflater(),R.layout.dialog_quickedit, null, false); if (password) { binding.inputEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } builder.setPositiveButton(R.string.accept, null); if (hint != 0) { binding.inputLayout.setHint(getString(hint)); } binding.inputEditText.requestFocus(); if (previousValue != null) { binding.inputEditText.getText().append(previousValue); } builder.setView(binding.getRoot()); builder.setNegativeButton(R.string.cancel, null); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(d -> SoftKeyboardUtils.showKeyboard(binding.inputEditText)); dialog.show(); View.OnClickListener clickListener = v -> { String value = binding.inputEditText.getText().toString(); if (!value.equals(previousValue) && (!value.trim().isEmpty() || permitEmpty)) { String error = callback.onValueEdited(value); if (error != null) { binding.inputLayout.setError(error); return; } } SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText); dialog.dismiss(); }; dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(clickListener); dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener((v -> { SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText); dialog.dismiss(); })); dialog.setOnDismissListener(dialog1 -> { SoftKeyboardUtils.hideSoftKeyboard(binding.inputEditText); }); } protected boolean hasStoragePermission(int requestCode) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode); return false; } else { return true; } } else { return true; } } protected void onActivityResult(int requestCode, int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_INVITE_TO_CONVERSATION && resultCode == RESULT_OK) { mPendingConferenceInvite = ConferenceInvite.parse(data); if (xmppConnectionServiceBound && mPendingConferenceInvite != null) { if (mPendingConferenceInvite.execute(this)) { mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG); mToast.show(); } mPendingConferenceInvite = null; } } } public int getWarningTextColor() { return this.mColorRed; } public int getPixel(int dp) { DisplayMetrics metrics = getResources().getDisplayMetrics(); return ((int) (dp * metrics.density)); } public boolean copyTextToClipboard(String text, int labelResId) { ClipboardManager mClipBoardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); String label = getResources().getString(labelResId); if (mClipBoardManager != null) { ClipData mClipData = ClipData.newPlainText(label, text); mClipBoardManager.setPrimaryClip(mClipData); return true; } return false; } protected boolean neverCompressPictures() { return getPreferences().getString("picture_compression", getResources().getString(R.string.picture_compression)).equals("never"); } protected boolean manuallyChangePresence() { return getBooleanPreference(SettingsActivity.MANUALLY_CHANGE_PRESENCE, R.bool.manually_change_presence); } protected String getShareableUri() { return getShareableUri(false); } protected String getShareableUri(boolean http) { return null; } protected void shareLink(boolean http) { String uri = getShareableUri(http); if (uri == null || uri.isEmpty()) { return; } Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, getShareableUri(http)); try { startActivity(Intent.createChooser(intent, getText(R.string.share_uri_with))); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.no_application_to_share_uri, Toast.LENGTH_SHORT).show(); } } protected void launchOpenKeyChain(long keyId) { PgpEngine pgp = XmppActivity.this.xmppConnectionService.getPgpEngine(); try { startIntentSenderForResult( pgp.getIntentForKey(keyId).getIntentSender(), 0, null, 0, 0, 0); } catch (Throwable e) { Toast.makeText(XmppActivity.this, R.string.openpgp_error, Toast.LENGTH_SHORT).show(); } } @Override public void onResume() { super.onResume(); } protected int findTheme() { return ThemeHelper.find(this); } @Override public void onPause() { super.onPause(); } @Override public boolean onMenuOpened(int id, Menu menu) { if(id == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null) { MenuDoubleTabUtil.recordMenuOpen(); } return super.onMenuOpened(id, menu); } protected void showQrCode() { showQrCode(getShareableUri()); } protected void showQrCode(final String uri) { if (uri == null || uri.isEmpty()) { return; } Point size = new Point(); getWindowManager().getDefaultDisplay().getSize(size); final int width = (size.x < size.y ? size.x : size.y); Bitmap bitmap = BarcodeProvider.create2dBarcodeBitmap(uri, width); ImageView view = new ImageView(this); view.setBackgroundColor(Color.WHITE); view.setImageBitmap(bitmap); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(view); builder.create().show(); } protected Account extractAccount(Intent intent) { String jid = intent != null ? intent.getStringExtra(EXTRA_ACCOUNT) : null; try { return jid != null ? xmppConnectionService.findAccountByJid(Jid.of(jid)) : null; } catch (IllegalArgumentException e) { return null; } } public AvatarService avatarService() { return xmppConnectionService.getAvatarService(); } public void loadBitmap(Message message, ImageView imageView) { Bitmap bm; try { bm = xmppConnectionService.getFileBackend().getThumbnail(message, (int) (metrics.density * 288), true); } catch (IOException e) { bm = null; } if (bm != null) { cancelPotentialWork(message, imageView); imageView.setImageBitmap(bm); imageView.setBackgroundColor(0x00000000); } else { if (cancelPotentialWork(message, imageView)) { imageView.setBackgroundColor(0xff333333); imageView.setImageDrawable(null); final BitmapWorkerTask task = new BitmapWorkerTask(this, imageView); final AsyncDrawable asyncDrawable = new AsyncDrawable( getResources(), null, task); imageView.setImageDrawable(asyncDrawable); try { task.execute(message); } catch (final RejectedExecutionException ignored) { ignored.printStackTrace(); } } } } protected interface OnValueEdited { String onValueEdited(String value); } public static class ConferenceInvite { private String uuid; private List<Jid> jids = new ArrayList<>(); public static ConferenceInvite parse(Intent data) { ConferenceInvite invite = new ConferenceInvite(); invite.uuid = data.getStringExtra(ChooseContactActivity.EXTRA_CONVERSATION); if (invite.uuid == null) { return null; } invite.jids.addAll(ChooseContactActivity.extractJabberIds(data)); return invite; } public boolean execute(XmppActivity activity) { XmppConnectionService service = activity.xmppConnectionService; Conversation conversation = service.findConversationByUuid(this.uuid); if (conversation == null) { return false; } if (conversation.getMode() == Conversation.MODE_MULTI) { for (Jid jid : jids) { service.invite(conversation, jid); } return false; } else { jids.add(conversation.getJid().asBareJid()); return service.createAdhocConference(conversation.getAccount(), null, jids, activity.adhocCallback); } } } static class BitmapWorkerTask extends AsyncTask<Message, Void, Bitmap> { private final WeakReference<ImageView> imageViewReference; private final WeakReference<XmppActivity> activity; private Message message = null; private BitmapWorkerTask(XmppActivity activity, ImageView imageView) { this.activity = new WeakReference<>(activity); this.imageViewReference = new WeakReference<>(imageView); } @Override protected Bitmap doInBackground(Message... params) { if (isCancelled()) { return null; } message = params[0]; try { XmppActivity activity = this.activity.get(); if (activity != null && activity.xmppConnectionService != null) { return activity.xmppConnectionService.getFileBackend().getThumbnail(message, (int) (activity.metrics.density * 288), false); } else { return null; } } catch (IOException e) { return null; } } @Override protected void onPostExecute(Bitmap bitmap) { if (bitmap != null && !isCancelled()) { final ImageView imageView = imageViewReference.get(); if (imageView != null) { imageView.setImageBitmap(bitmap); imageView.setBackgroundColor(0x00000000); } } } } private static class AsyncDrawable extends BitmapDrawable { private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference; private AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) { super(res, bitmap); bitmapWorkerTaskReference = new WeakReference<>(bitmapWorkerTask); } private BitmapWorkerTask getBitmapWorkerTask() { return bitmapWorkerTaskReference.get(); } } }
./CrossVul/dataset_final_sorted/CWE-20/java/bad_418_3
crossvul-java_data_bad_1177_0
/* * Copyright 2013 the original author or authors. * * 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 ratpack.server.internal; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.handler.codec.http.*; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandshakeCompletionEvent; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.AttributeKey; import io.netty.util.CharsetUtil; import io.netty.util.ReferenceCountUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ratpack.exec.ExecController; import ratpack.func.Action; import ratpack.handling.Handler; import ratpack.handling.Handlers; import ratpack.handling.internal.ChainHandler; import ratpack.handling.internal.DefaultContext; import ratpack.handling.internal.DescribingHandler; import ratpack.handling.internal.DescribingHandlers; import ratpack.http.Headers; import ratpack.http.MutableHeaders; import ratpack.http.Response; import ratpack.http.internal.*; import ratpack.registry.Registry; import ratpack.render.internal.DefaultRenderController; import ratpack.server.ServerConfig; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLPeerUnverifiedException; import javax.security.cert.X509Certificate; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.CharBuffer; import java.nio.channels.ClosedChannelException; import java.time.Clock; import java.util.concurrent.atomic.AtomicBoolean; @ChannelHandler.Sharable public class NettyHandlerAdapter extends ChannelInboundHandlerAdapter { private static final AttributeKey<Action<Object>> CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY = AttributeKey.valueOf(NettyHandlerAdapter.class, "subscriber"); private static final AttributeKey<RequestBodyAccumulator> BODY_ACCUMULATOR_KEY = AttributeKey.valueOf(NettyHandlerAdapter.class, "requestBody"); private static final AttributeKey<X509Certificate> CLIENT_CERT_KEY = AttributeKey.valueOf(NettyHandlerAdapter.class, "principal"); private final static Logger LOGGER = LoggerFactory.getLogger(NettyHandlerAdapter.class); private final Handler[] handlers; private final DefaultContext.ApplicationConstants applicationConstants; private final Registry serverRegistry; private final boolean development; private final Clock clock; public NettyHandlerAdapter(Registry serverRegistry, Handler handler) throws Exception { this.handlers = ChainHandler.unpack(handler); this.serverRegistry = serverRegistry; this.applicationConstants = new DefaultContext.ApplicationConstants(this.serverRegistry, new DefaultRenderController(), serverRegistry.get(ExecController.class), Handlers.notFound()); this.development = serverRegistry.get(ServerConfig.class).isDevelopment(); this.clock = serverRegistry.get(Clock.class); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.read(); super.channelActive(ctx); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { newRequest(ctx, (HttpRequest) msg); } else if (msg instanceof HttpContent) { ((HttpContent) msg).touch(); RequestBodyAccumulator bodyAccumulator = ctx.channel().attr(BODY_ACCUMULATOR_KEY).get(); if (bodyAccumulator == null) { ((HttpContent) msg).release(); } else { bodyAccumulator.add((HttpContent) msg); } // Read for the next request proactively so that we // detect if the client closes the connection. if (msg instanceof LastHttpContent) { ctx.channel().read(); } } else { Action<Object> subscriber = ctx.channel().attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).get(); if (subscriber == null) { super.channelRead(ctx, ReferenceCountUtil.touch(msg)); } else { subscriber.execute(ReferenceCountUtil.touch(msg)); } } } private void newRequest(ChannelHandlerContext ctx, HttpRequest nettyRequest) throws Exception { if (!nettyRequest.decoderResult().isSuccess()) { LOGGER.debug("Failed to decode HTTP request.", nettyRequest.decoderResult().cause()); sendError(ctx, HttpResponseStatus.BAD_REQUEST); return; } Headers requestHeaders = new NettyHeadersBackedHeaders(nettyRequest.headers()); //Find the content length we will use this as an indicator of a body Long contentLength = HttpUtil.getContentLength(nettyRequest, -1L); String transferEncoding = requestHeaders.get(HttpHeaderNames.TRANSFER_ENCODING); //If there is a content length or transfer encoding that indicates there is a body boolean hasBody = (contentLength > 0) || (transferEncoding != null); RequestBody requestBody = hasBody ? new RequestBody(contentLength, nettyRequest, ctx) : null; Channel channel = ctx.channel(); if (requestBody != null) { channel.attr(BODY_ACCUMULATOR_KEY).set(requestBody); } InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress(); InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress(); ConnectionIdleTimeout connectionIdleTimeout = ConnectionIdleTimeout.of(channel); DefaultRequest request = new DefaultRequest( clock.instant(), requestHeaders, nettyRequest.method(), nettyRequest.protocolVersion(), nettyRequest.uri(), remoteAddress, socketAddress, serverRegistry.get(ServerConfig.class), requestBody, connectionIdleTimeout, channel.attr(CLIENT_CERT_KEY).get() ); HttpHeaders nettyHeaders = new DefaultHttpHeaders(false); MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders); AtomicBoolean transmitted = new AtomicBoolean(false); DefaultResponseTransmitter responseTransmitter = new DefaultResponseTransmitter(transmitted, channel, clock, nettyRequest, request, nettyHeaders, requestBody); ctx.channel().attr(DefaultResponseTransmitter.ATTRIBUTE_KEY).set(responseTransmitter); Action<Action<Object>> subscribeHandler = thing -> { transmitted.set(true); ctx.channel().attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).set(thing); }; DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants( applicationConstants, request, channel, responseTransmitter, subscribeHandler ); Response response = new DefaultResponse(responseHeaders, ctx.alloc(), responseTransmitter); requestConstants.response = response; DefaultContext.start(channel.eventLoop(), requestConstants, serverRegistry, handlers, execution -> { if (!transmitted.get()) { Handler lastHandler = requestConstants.handler; StringBuilder description = new StringBuilder(); description .append("No response sent for ") .append(request.getMethod().getName()) .append(" request to ") .append(request.getUri()); if (lastHandler != null) { description.append(" (last handler: "); if (lastHandler instanceof DescribingHandler) { ((DescribingHandler) lastHandler).describeTo(description); } else { DescribingHandlers.describeTo(lastHandler, description); } description.append(")"); } String message = description.toString(); LOGGER.warn(message); response.getHeaders().clear(); ByteBuf body; if (development) { CharBuffer charBuffer = CharBuffer.wrap(message); body = ByteBufUtil.encodeString(ctx.alloc(), charBuffer, CharsetUtil.UTF_8); response.contentType(HttpHeaderConstants.PLAIN_TEXT_UTF8); } else { body = Unpooled.EMPTY_BUFFER; } response.getHeaders().set(HttpHeaderConstants.CONTENT_LENGTH, body.readableBytes()); responseTransmitter.transmit(HttpResponseStatus.INTERNAL_SERVER_ERROR, body); } }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (!isIgnorableException(cause)) { LOGGER.error("", cause); if (ctx.channel().isActive()) { sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); } } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { ConnectionClosureReason.setIdle(ctx.channel()); ctx.close(); } if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).isSuccess()) { SSLEngine engine = ctx.pipeline().get(SslHandler.class).engine(); if (engine.getWantClientAuth() || engine.getNeedClientAuth()) { try { X509Certificate clientCert = engine.getSession().getPeerCertificateChain()[0]; ctx.channel().attr(CLIENT_CERT_KEY).set(clientCert); } catch (SSLPeerUnverifiedException ignore) { // ignore - there is no way to avoid this exception that I can determine } } } super.userEventTriggered(ctx, evt); } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { DefaultResponseTransmitter responseTransmitter = ctx.channel().attr(DefaultResponseTransmitter.ATTRIBUTE_KEY).get(); if (responseTransmitter != null) { responseTransmitter.writabilityChanged(); } } private static boolean isIgnorableException(Throwable throwable) { if (throwable instanceof ClosedChannelException) { return true; } else if (throwable instanceof IOException) { // There really does not seem to be a better way of detecting this kind of exception String message = throwable.getMessage(); return message != null && message.endsWith("Connection reset by peer"); } else { return false; } } private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8)); response.headers().set(HttpHeaderConstants.CONTENT_TYPE, HttpHeaderConstants.PLAIN_TEXT_UTF8); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } }
./CrossVul/dataset_final_sorted/CWE-20/java/bad_1177_0
crossvul-java_data_bad_657_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 org.apache.cxf.fediz.systests.idp; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.Base64; import javax.servlet.ServletException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import com.gargoylesoftware.htmlunit.CookieManager; import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.DomNodeList; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; import com.gargoylesoftware.htmlunit.xml.XmlPage; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.connector.Connector; import org.apache.catalina.startup.Tomcat; import org.apache.commons.io.IOUtils; import org.apache.cxf.fediz.core.FederationConstants; import org.apache.cxf.fediz.core.util.DOMUtils; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.wss4j.dom.engine.WSSConfig; import org.apache.xml.security.keys.KeyInfo; import org.apache.xml.security.signature.XMLSignature; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * Some tests invoking directly on the IdP */ public class IdpTest { static String idpHttpsPort; static String rpHttpsPort; private static Tomcat idpServer; @BeforeClass public static void init() throws Exception { idpHttpsPort = System.getProperty("idp.https.port"); Assert.assertNotNull("Property 'idp.https.port' null", idpHttpsPort); rpHttpsPort = System.getProperty("rp.https.port"); Assert.assertNotNull("Property 'rp.https.port' null", rpHttpsPort); idpServer = startServer(true, idpHttpsPort); WSSConfig.init(); } private static Tomcat startServer(boolean idp, String port) throws ServletException, LifecycleException, IOException { Tomcat server = new Tomcat(); server.setPort(0); String currentDir = new File(".").getCanonicalPath(); String baseDir = currentDir + File.separator + "target"; server.setBaseDir(baseDir); server.getHost().setAppBase("tomcat/idp/webapps"); server.getHost().setAutoDeploy(true); server.getHost().setDeployOnStartup(true); Connector httpsConnector = new Connector(); httpsConnector.setPort(Integer.parseInt(port)); httpsConnector.setSecure(true); httpsConnector.setScheme("https"); httpsConnector.setAttribute("keyAlias", "mytomidpkey"); httpsConnector.setAttribute("keystorePass", "tompass"); httpsConnector.setAttribute("keystoreFile", "test-classes/server.jks"); httpsConnector.setAttribute("truststorePass", "tompass"); httpsConnector.setAttribute("truststoreFile", "test-classes/server.jks"); httpsConnector.setAttribute("clientAuth", "want"); // httpsConnector.setAttribute("clientAuth", "false"); httpsConnector.setAttribute("sslProtocol", "TLS"); httpsConnector.setAttribute("SSLEnabled", true); server.getService().addConnector(httpsConnector); File stsWebapp = new File(baseDir + File.separator + server.getHost().getAppBase(), "fediz-idp-sts"); server.addWebapp("/fediz-idp-sts", stsWebapp.getAbsolutePath()); File idpWebapp = new File(baseDir + File.separator + server.getHost().getAppBase(), "fediz-idp"); server.addWebapp("/fediz-idp", idpWebapp.getAbsolutePath()); server.start(); return server; } @AfterClass public static void cleanup() { shutdownServer(idpServer); } private static void shutdownServer(Tomcat server) { try { if (server != null && server.getServer() != null && server.getServer().getState() != LifecycleState.DESTROYED) { if (server.getServer().getState() != LifecycleState.STOPPED) { server.stop(); } server.destroy(); } } catch (Exception e) { e.printStackTrace(); } } public String getIdpHttpsPort() { return idpHttpsPort; } public String getRpHttpsPort() { return rpHttpsPort; } public String getServletContextName() { return "fedizhelloworld"; } @org.junit.Test public void testSuccessfulInvokeOnIdP() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); final HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); // Parse the form to get the token (wresult) DomNodeList<DomElement> results = idpPage.getElementsByTagName("input"); String wresult = null; for (DomElement result : results) { if ("wresult".equals(result.getAttributeNS(null, "name"))) { wresult = result.getAttributeNS(null, "value"); break; } } Assert.assertNotNull(wresult); webClient.close(); } @org.junit.Test public void testSuccessfulSSOInvokeOnIdP() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.addRequestHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString((user + ":" + password).getBytes())); // // First invocation // webClient.getOptions().setJavaScriptEnabled(false); HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); // Parse the form to get the token (wresult) DomNodeList<DomElement> results = idpPage.getElementsByTagName("input"); String wresult = null; for (DomElement result : results) { if ("wresult".equals(result.getAttributeNS(null, "name"))) { wresult = result.getAttributeNS(null, "value"); break; } } Assert.assertNotNull(wresult); // // Second invocation - change the credentials to make sure the session is set up correctly // webClient.removeRequestHeader("Authorization"); webClient.addRequestHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString(("mallory" + ":" + password).getBytes())); webClient.getOptions().setJavaScriptEnabled(false); idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); // Parse the form to get the token (wresult) results = idpPage.getElementsByTagName("input"); wresult = null; for (DomElement result : results) { if ("wresult".equals(result.getAttributeNS(null, "name"))) { wresult = result.getAttributeNS(null, "value"); break; } } Assert.assertNotNull(wresult); webClient.close(); } @Test public void testIdPMetadata() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/FederationMetadata/2007-06/FederationMetadata.xml"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getOptions().setSSLClientCertificate( this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks"); final XmlPage rpPage = webClient.getPage(url); final String xmlContent = rpPage.asXml(); Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor")); // Now validate the Signature Document doc = rpPage.getXmlDocument(); doc.getDocumentElement().setIdAttributeNS(null, "ID", true); Node signatureNode = DOMUtils.getChild(doc.getDocumentElement(), "Signature"); Assert.assertNotNull(signatureNode); XMLSignature signature = new XMLSignature((Element)signatureNode, ""); KeyInfo ki = signature.getKeyInfo(); Assert.assertNotNull(ki); Assert.assertNotNull(ki.getX509Certificate()); Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate())); webClient.close(); } @Test public void testIdPMetadataDefault() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/metadata"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getOptions().setSSLClientCertificate( this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks"); final XmlPage rpPage = webClient.getPage(url); final String xmlContent = rpPage.asXml(); Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor")); // Now validate the Signature Document doc = rpPage.getXmlDocument(); doc.getDocumentElement().setIdAttributeNS(null, "ID", true); Node signatureNode = DOMUtils.getChild(doc.getDocumentElement(), "Signature"); Assert.assertNotNull(signatureNode); XMLSignature signature = new XMLSignature((Element)signatureNode, ""); KeyInfo ki = signature.getKeyInfo(); Assert.assertNotNull(ki); Assert.assertNotNull(ki.getX509Certificate()); Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate())); webClient.close(); } @Test public void testIdPServiceMetadata() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/metadata/urn:org:apache:cxf:fediz:idp:realm-B"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getOptions().setSSLClientCertificate( this.getClass().getClassLoader().getResource("client.jks"), "storepass", "jks"); final XmlPage rpPage = webClient.getPage(url); final String xmlContent = rpPage.asXml(); Assert.assertTrue(xmlContent.startsWith("<md:EntityDescriptor")); // Now validate the Signature Document doc = rpPage.getXmlDocument(); doc.getDocumentElement().setIdAttributeNS(null, "ID", true); Node signatureNode = DOMUtils.getChild(doc.getDocumentElement(), "Signature"); Assert.assertNotNull(signatureNode); XMLSignature signature = new XMLSignature((Element)signatureNode, ""); KeyInfo ki = signature.getKeyInfo(); Assert.assertNotNull(ki); Assert.assertNotNull(ki.getX509Certificate()); Assert.assertTrue(signature.checkSignatureValue(ki.getX509Certificate())); webClient.close(); } // Send an unknown wreq value @org.junit.Test public void testBadWReq() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String testWReq = "<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">" + "<TokenType>http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV3.0</TokenType>" + "</RequestSecurityToken>"; url += "&wreq=" + URLEncoder.encode(testWReq, "UTF-8"); String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wreq value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } // Send an entity expansion attack for the wreq value @org.junit.Test public void testEntityExpansionWReq() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; InputStream is = this.getClass().getClassLoader().getResource("entity_wreq.xml").openStream(); String entity = IOUtils.toString(is, "UTF-8"); is.close(); String validWreq = "<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">" + "<TokenType>&m;http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</TokenType>" + "</RequestSecurityToken>"; url += "&wreq=" + URLEncoder.encode(entity + validWreq, "UTF-8"); String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wreq value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } // Send an malformed wreq value @org.junit.Test public void testMalformedWReq() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String testWReq = "<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">" + "<TokenTypehttp://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</TokenType>" + "</RequestSecurityToken>"; url += "&wreq=" + URLEncoder.encode(testWReq, "UTF-8"); String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wreq value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } // Send an unknown wa value @org.junit.Test public void testBadWa() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin2.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wa value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } // Send an unknown whr value @org.junit.Test public void testBadWHR() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A-xyz"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad whr value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 500); } webClient.close(); } // Send an unknown wtrealm value @org.junit.Test public void testBadWtRealm() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld-xyz"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wtrealm value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } // Send an malformed wreply value @org.junit.Test public void testMalformedWReply() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "/localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wreply value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } // Send a bad wreply value @org.junit.Test public void testBadWReply() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://www.apache.org:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wreply value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } @org.junit.Test public void testValidWReplyWrongApplication() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld2"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wreply value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } @org.junit.Test public void testWReplyExactMatchingSuccess() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); webClient.getPage(url); webClient.close(); } @org.junit.Test public void testWReplyExactMatchingFailure() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet/blah"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wreply value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } @org.junit.Test public void testNoEndpointAddressOrConstraint() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld4"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); // This is an error in the IdP try { webClient.getPage(url); Assert.fail("Failure expected on a bad wreply value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } // Send a bad wreply value. This will pass the reg ex validation but fail the commons-validator // validation @org.junit.Test public void testWReplyWithDoubleSlashes() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure//fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wreply value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } // Send a query parameter that's too big @org.junit.Test public void testLargeQueryParameterRejected() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; StringBuilder sb = new StringBuilder("https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"); for (int i = 0; i < 100; i++) { sb.append("aaaaaaaaaa"); } url += "&wreply=" + sb.toString(); String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); try { webClient.getPage(url); Assert.fail("Failure expected on a bad wreply value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } // Send a query parameter that's bigger than the accepted default, but is allowed by configuration @org.junit.Test public void testLargeQueryParameterAccepted() throws Exception { String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; StringBuilder sb = new StringBuilder("https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"); for (int i = 0; i < 50; i++) { sb.append("aaaaaaaaaa"); } url += "&wreply=" + sb.toString(); String user = "alice"; String password = "ecila"; final WebClient webClient = new WebClient(); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); webClient.getPage(url); webClient.close(); } @Test public void testIdPLogout() throws Exception { // 1. First let's login to the IdP String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; CookieManager cookieManager = new CookieManager(); WebClient webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); webClient.close(); // 2. now we logout from IdP String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa=" + FederationConstants.ACTION_SIGNOUT; webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); idpPage = webClient.getPage(idpLogoutUrl); Assert.assertEquals("IDP SignOut Confirmation Response Page", idpPage.getTitleText()); HtmlForm form = idpPage.getFormByName("signoutconfirmationresponseform"); HtmlSubmitInput button = form.getInputByName("_eventId_submit"); button.click(); webClient.close(); // 3. now we try to access the idp without authentication but with the existing cookies // to see if we are really logged out webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); idpPage = webClient.getPage(url); Assert.assertEquals(401, idpPage.getWebResponse().getStatusCode()); webClient.close(); } @Test public void testIdPLogoutCleanup() throws Exception { // 1. First let's login to the IdP String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; CookieManager cookieManager = new CookieManager(); WebClient webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); webClient.close(); // 2. now we logout from IdP String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa=" + FederationConstants.ACTION_SIGNOUT_CLEANUP; webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); idpPage = webClient.getPage(idpLogoutUrl); Assert.assertEquals("IDP SignOut Response Page", idpPage.getTitleText()); webClient.close(); // 3. now we try to access the idp without authentication but with the existing cookies // to see if we are really logged out webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); idpPage = webClient.getPage(url); Assert.assertEquals(401, idpPage.getWebResponse().getStatusCode()); webClient.close(); } @Test public void testIdPLogoutCleanupWithBadWReply() throws Exception { // 1. First let's login to the IdP String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; CookieManager cookieManager = new CookieManager(); WebClient webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); webClient.close(); // 2. now we logout from IdP using a bad wreply String badWReply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure//fedservlet"; String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa=" + FederationConstants.ACTION_SIGNOUT_CLEANUP; idpLogoutUrl += "&wreply=" + badWReply; webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); try { webClient.getPage(idpLogoutUrl); Assert.fail("Failure expected on a bad wreply value"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); // 3. now we try to access the idp without authentication but with the existing cookies // to see if we are really logged out. Even though an error was thrown on a bad wreply, we should still // be logged out webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); idpPage = webClient.getPage(url); Assert.assertEquals(401, idpPage.getWebResponse().getStatusCode()); webClient.close(); } @Test public void testIdPLogoutWithWreplyConstraint() throws Exception { // 1. First let's login to the IdP String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; CookieManager cookieManager = new CookieManager(); WebClient webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); webClient.close(); // 2. now we logout from IdP String logoutWReply = "https://localhost:12345"; String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa=" + FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply + "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); idpPage = webClient.getPage(idpLogoutUrl); Assert.assertEquals("IDP SignOut Confirmation Response Page", idpPage.getTitleText()); HtmlForm form = idpPage.getFormByName("signoutconfirmationresponseform"); HtmlSubmitInput button = form.getInputByName("_eventId_submit"); button.click(); webClient.close(); // 3. now we try to access the idp without authentication but with the existing cookies // to see if we are really logged out webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); idpPage = webClient.getPage(url); Assert.assertEquals(401, idpPage.getWebResponse().getStatusCode()); webClient.close(); } @Test public void testIdPLogoutWithWreplyBadAddress() throws Exception { // 1. First let's login to the IdP String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; CookieManager cookieManager = new CookieManager(); WebClient webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); webClient.close(); // 2. now we logout from IdP String logoutWReply = "https://localhost:12345/badlogout"; String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa=" + FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply + "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); try { webClient.getPage(idpLogoutUrl); Assert.fail("Failure expected on a non-matching wreply address"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } @Test public void testIdPLogoutWithNoRealm() throws Exception { // 1. First let's login to the IdP String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; CookieManager cookieManager = new CookieManager(); WebClient webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); webClient.close(); // 2. now we logout from IdP String logoutWReply = "https://localhost:12345"; String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa=" + FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply; webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); try { webClient.getPage(idpLogoutUrl); Assert.fail("Failure expected on a non-matching wreply address"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } @Test public void testIdPLogoutWithWreplyAddress() throws Exception { // 1. First let's login to the IdP String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; CookieManager cookieManager = new CookieManager(); WebClient webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); webClient.close(); // 2. now we logout from IdP String logoutWReply = "https://localhost:12345"; String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa=" + FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply + "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3"; webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); idpPage = webClient.getPage(idpLogoutUrl); Assert.assertEquals("IDP SignOut Confirmation Response Page", idpPage.getTitleText()); HtmlForm form = idpPage.getFormByName("signoutconfirmationresponseform"); HtmlSubmitInput button = form.getInputByName("_eventId_submit"); button.click(); webClient.close(); // 3. now we try to access the idp without authentication but with the existing cookies // to see if we are really logged out webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); idpPage = webClient.getPage(url); Assert.assertEquals(401, idpPage.getWebResponse().getStatusCode()); webClient.close(); } @Test public void testIdPLogoutWithBadAddress() throws Exception { // 1. First let's login to the IdP String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; CookieManager cookieManager = new CookieManager(); WebClient webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); webClient.close(); // 2. now we logout from IdP String logoutWReply = "https://localhost:12345/badlogout"; String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa=" + FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply + "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld3"; webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); try { webClient.getPage(idpLogoutUrl); Assert.fail("Failure expected on a non-matching wreply address"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } @Test public void testIdPLogoutWithNoConfiguredConstraint() throws Exception { // 1. First let's login to the IdP String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?"; url += "wa=wsignin1.0"; url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A"; url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld2"; String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure2/fedservlet"; url += "&wreply=" + wreply; String user = "alice"; String password = "ecila"; CookieManager cookieManager = new CookieManager(); WebClient webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); webClient.getCredentialsProvider().setCredentials( new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())), new UsernamePasswordCredentials(user, password)); webClient.getOptions().setJavaScriptEnabled(false); HtmlPage idpPage = webClient.getPage(url); webClient.getOptions().setJavaScriptEnabled(true); Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText()); webClient.close(); // 2. now we logout from IdP String logoutWReply = "https://localhost:12345"; String idpLogoutUrl = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?wa=" + FederationConstants.ACTION_SIGNOUT + "&wreply=" + logoutWReply + "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld2"; webClient = new WebClient(); webClient.setCookieManager(cookieManager); webClient.getOptions().setUseInsecureSSL(true); try { webClient.getPage(idpLogoutUrl); Assert.fail("Failure expected on a non-matching wreply address"); } catch (FailingHttpStatusCodeException ex) { Assert.assertEquals(ex.getStatusCode(), 400); } webClient.close(); } }
./CrossVul/dataset_final_sorted/CWE-20/java/bad_657_1
crossvul-java_data_bad_4128_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-20/java/bad_4128_0
crossvul-java_data_good_1381_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. */ package com.facebook.thrift.protocol; import java.util.Collections; import com.facebook.thrift.TException; /** * Utility class with static methods for interacting with protocol data * streams. * */ public class TProtocolUtil { /** * The maximum recursive depth the skip() function will traverse before * throwing a TException. */ private static int maxSkipDepth = Integer.MAX_VALUE; /** * Specifies the maximum recursive depth that the skip function will * traverse before throwing a TException. This is a global setting, so * any call to skip in this JVM will enforce this value. * * @param depth the maximum recursive depth. A value of 2 would allow * the skip function to skip a structure or collection with basic children, * but it would not permit skipping a struct that had a field containing * a child struct. A value of 1 would only allow skipping of simple * types and empty structs/collections. */ public static void setMaxSkipDepth(int depth) { maxSkipDepth = depth; } /** * Skips over the next data element from the provided input TProtocol object. * * @param prot the protocol object to read from * @param type the next value will be intepreted as this TType value. */ public static void skip(TProtocol prot, byte type) throws TException { skip(prot, type, maxSkipDepth); } /** * Skips over the next data element from the provided input TProtocol object. * * @param prot the protocol object to read from * @param type the next value will be intepreted as this TType value. * @param maxDepth this function will only skip complex objects to this * recursive depth, to prevent Java stack overflow. */ public static void skip(TProtocol prot, byte type, int maxDepth) throws TException { if (maxDepth <= 0) { throw new TException("Maximum skip depth exceeded"); } switch (type) { case TType.BOOL: { prot.readBool(); break; } case TType.BYTE: { prot.readByte(); break; } case TType.I16: { prot.readI16(); break; } case TType.I32: { prot.readI32(); break; } case TType.I64: { prot.readI64(); break; } case TType.DOUBLE: { prot.readDouble(); break; } case TType.FLOAT: { prot.readFloat(); break; } case TType.STRING: { prot.readBinary(); break; } case TType.STRUCT: { prot.readStructBegin( Collections.<Integer, com.facebook.thrift.meta_data.FieldMetaData>emptyMap()); while (true) { TField field = prot.readFieldBegin(); if (field.type == TType.STOP) { break; } skip(prot, field.type, maxDepth - 1); prot.readFieldEnd(); } prot.readStructEnd(); break; } case TType.MAP: { TMap map = prot.readMapBegin(); for (int i = 0; (map.size < 0) ? prot.peekMap() : (i < map.size); i++) { skip(prot, map.keyType, maxDepth - 1); skip(prot, map.valueType, maxDepth - 1); } prot.readMapEnd(); break; } case TType.SET: { TSet set = prot.readSetBegin(); for (int i = 0; (set.size < 0) ? prot.peekSet() : (i < set.size); i++) { skip(prot, set.elemType, maxDepth - 1); } prot.readSetEnd(); break; } case TType.LIST: { TList list = prot.readListBegin(); for (int i = 0; (list.size < 0) ? prot.peekList() : (i < list.size); i++) { skip(prot, list.elemType, maxDepth - 1); } prot.readListEnd(); break; } default: { throw new TProtocolException( TProtocolException.INVALID_DATA, "Invalid type encountered during skipping: " + type); } } } /** * Attempt to determine the protocol used to serialize some data. * * The guess is based on known specificities of supported protocols. * In some cases, no guess can be done, in that case we return the * fallback TProtocolFactory. * To be certain to correctly detect the protocol, the first encoded * field should have a field id < 256 * * @param data The serialized data to guess the protocol for. * @param fallback The TProtocol to return if no guess can be made. * @return a Class implementing TProtocolFactory which can be used to create a deserializer. */ public static TProtocolFactory guessProtocolFactory(byte[] data, TProtocolFactory fallback) { // // If the first and last bytes are opening/closing curly braces we guess the protocol as // being TJSONProtocol. // It could not be a TCompactBinary encoding for a field of type 0xb (Map) // with delta id 7 as the last byte for TCompactBinary is always 0. // if ('{' == data[0] && '}' == data[data.length - 1]) { return new TJSONProtocol.Factory(); } // // If the last byte is not 0, then it cannot be TCompactProtocol, it must be // TBinaryProtocol. // if (data[data.length - 1] != 0) { return new TBinaryProtocol.Factory(); } // // A first byte of value > 16 indicates TCompactProtocol was used, and the first byte // encodes a delta field id (id <= 15) and a field type. // if (data[0] > 0x10) { return new TCompactProtocol.Factory(); } // // If the second byte is 0 then it is a field id < 256 encoded by TBinaryProtocol. // It cannot possibly be TCompactProtocol since a value of 0 would imply a field id // of 0 as the zig zag varint encoding would end. // if (data.length > 1 && 0 == data[1]) { return new TBinaryProtocol.Factory(); } // // If bit 7 of the first byte of the field id is set then we have two choices: // 1. A field id > 63 was encoded with TCompactProtocol. // 2. A field id > 0x7fff (32767) was encoded with TBinaryProtocol and the last byte of the // serialized data is 0. // Option 2 is impossible since field ids are short and thus limited to 32767. // if (data.length > 1 && (data[1] & 0x80) != 0) { return new TCompactProtocol.Factory(); } // // The remaining case is either a field id <= 63 encoded as TCompactProtocol, // one >= 256 encoded with TBinaryProtocol with a last byte at 0, or an empty structure. // As we cannot really decide, we return the fallback protocol. // return fallback; } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_1381_0
crossvul-java_data_good_195_7
/* * Copyright (c) 2011-2017 Contributors to the Eclipse Foundation * * 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, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.test.core; import io.vertx.core.MultiMap; import io.vertx.core.http.impl.headers.VertxHttpHeaders; import org.junit.Test; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public class VertxHttpHeadersTest extends CaseInsensitiveHeadersTest { @Override protected MultiMap newMultiMap() { return new VertxHttpHeaders(); } @Override public void testHashMININT() { // Does not apply } }
./CrossVul/dataset_final_sorted/CWE-20/java/good_195_7
crossvul-java_data_bad_761_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-20/java/bad_761_1
crossvul-java_data_bad_4128_3
404: Not Found
./CrossVul/dataset_final_sorted/CWE-20/java/bad_4128_3