max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
2,086
/* * Licensed to 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. Apache Software Foundation (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.dolphinscheduler.alert.api; public class AlertResult { private String status; private String message; public AlertResult(String status, String message) { this.status = status; this.message = message; } public AlertResult() { } public static AlertResultBuilder builder() { return new AlertResultBuilder(); } public String getStatus() { return this.status; } public AlertResult setStatus(String status) { this.status = status; return this; } public String getMessage() { return this.message; } public AlertResult setMessage(String message) { this.message = message; return this; } public boolean equals(final Object o) { if (o == this) { return true; } if (!(o instanceof AlertResult)) { return false; } final AlertResult other = (AlertResult) o; if (!other.canEqual((Object) this)) { return false; } final Object this$status = this.getStatus(); final Object other$status = other.getStatus(); if (this$status == null ? other$status != null : !this$status.equals(other$status)) { return false; } final Object this$message = this.getMessage(); final Object other$message = other.getMessage(); if (this$message == null ? other$message != null : !this$message.equals(other$message)) { return false; } return true; } protected boolean canEqual(final Object other) { return other instanceof AlertResult; } public int hashCode() { final int PRIME = 59; int result = 1; final Object $status = this.getStatus(); result = result * PRIME + ($status == null ? 43 : $status.hashCode()); final Object $message = this.getMessage(); result = result * PRIME + ($message == null ? 43 : $message.hashCode()); return result; } public String toString() { return "AlertResult(status=" + this.getStatus() + ", message=" + this.getMessage() + ")"; } public static class AlertResultBuilder { private String status; private String message; AlertResultBuilder() { } public AlertResultBuilder status(String status) { this.status = status; return this; } public AlertResultBuilder message(String message) { this.message = message; return this; } public AlertResult build() { return new AlertResult(status, message); } public String toString() { return "AlertResult.AlertResultBuilder(status=" + this.status + ", message=" + this.message + ")"; } } }
1,363
360
<gh_stars>100-1000 /* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * --------------------------------------------------------------------------------------- * * vecplainagg.h * plain agg class and class member declare. * * IDENTIFICATION * src/include/vecexecutor/vecplainagg.h * * --------------------------------------------------------------------------------------- */ #ifndef VECPLAINAGG_H #define VECPLAINAGG_H #include "vecexecutor/vecagg.h" class PlainAggRunner : public BaseAggRunner { public: VectorBatch* Run(); PlainAggRunner(VecAggState* runtime); ~PlainAggRunner(){}; void Build() {} VectorBatch* Probe() { return NULL; } bool ResetNecessary(VecAggState* node); void endPlainAgg(); private: /* Plain aggregation without group by.*/ template <bool hasDistinct> VectorBatch* RunPlain(); void BindingFp(); VectorBatch* (PlainAggRunner::*plainAggregation)(); template <bool hasDistinct> void buildPlaintAgg(VectorBatch* outerBatch, bool first_batch); }; #endif /* VECPLAINAGG_H */
545
5,169
{ "name": "UIBuilder", "version": "0.2.5", "summary": "An iOS swift library intended to assist with programatically building complicated UI elements.", "description": "Provides low level constraint based building blocks to ease development of programatically generated\nviews. Also includes stacking views that aid in more complex view creation.", "homepage": "https://github.com/e2technologies/UIBuilder-swift", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "source": { "git": "https://github.com/e2technologies/UIBuilder-swift.git", "tag": "0.2.5" }, "swift_version": "4.0", "platforms": { "ios": "8.0" }, "source_files": "UIBuilder/Classes/**/*" }
269
504
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ An spline interpolation method for data fitting. This allows for fitting bopes sampler results or potential energy surfaces. """ from typing import Tuple, List, Optional, Callable, Any import scipy.interpolate as interp from scipy.optimize import minimize_scalar from qiskit.chemistry.algorithms.pes_samplers.potentials.potential_base import EnergySurfaceBase class EnergySurface1DSpline(EnergySurfaceBase): """A simple cubic spline interpolation for the potential energy surface.""" def __init__(self) -> None: """A spline interpolation method for data fitting. This allows for fitting BOPES sampler results or potential energy surfaces. """ self._eval = None # type: Optional[Callable[[Any], Any]] self.eval_d = None # type: Optional[Callable[[Any], Any]] self.min_x = None self.min_val = None self.x_left = None # type: Optional[float] self.x_right = None # type: Optional[float] def eval(self, x: float) -> float: """After fitting the data to the fit function, predict the energy at a point x. Args: x: Value to be evaluated Returns: Value of surface fit in point x. """ assert self._eval is not None result = self._eval(x) return result def fit(self, xdata: List[float], ydata: List[float], initial_vals: Optional[List[float]] = None, bounds_list: Optional[Tuple[List[float], List[float]]] = None ) -> None: r"""Fits surface to data. Args: xdata: x data to be fitted ydata: y data to be fitted initial_vals: Initial values for fit parameters. None for default. Order of parameters is d_e, alpha, r_0 and m_shift (see fit_function implementation) bounds_list: Bounds for the fit parameters. None for default. Order of parameters is d_e, alpha, r_0 and m_shift (see fit_function implementation) """ newx = xdata newy = ydata tck = interp.splrep(newx, newy, k=3) self._eval = lambda x: interp.splev(x, tck) self.eval_d = lambda x: interp.splev(x, tck, der=1) result = minimize_scalar(self._eval) assert result.success self.min_x = result.x self.min_val = result.fun self.x_left = min(xdata) self.x_right = max(xdata) def get_equilibrium_geometry(self, scaling: float = 1.0) -> float: """ Returns the geometry for the minimal energy (scaled by 'scaling') Default units (scaling=1.0) are Angstroms. Scale by 1E-10 to get meters. Args: scaling: scaling factor Returns: equilibrium geometry """ assert self.min_x is not None return self.min_x * scaling def get_minimal_energy(self, scaling: float = 1.0) -> float: """ Returns the value of the minimal energy (scaled by 'scaling') Default units (scaling=1.0) are J/mol. Scale appropriately for Hartrees. Args: scaling: scaling factor Returns: minimum energy """ assert self.min_val is not None return self.min_val * scaling def get_trust_region(self) -> Tuple[float, float]: """Get the trust region. Returns the bounds of the region (in space) where the energy surface implementation can be trusted. When doing spline interpolation, for example, that would be the region where data is interpolated (vs. extrapolated) from the arguments of fit(). Returns: The trust region between bounds. """ return (self.x_left, self.x_right)
1,731
964
[ { "queryName": "Unrestricted Security Group Ingress", "severity": "HIGH", "line": 6, "filename": "positive1.tf" }, { "queryName": "Unrestricted Security Group Ingress", "severity": "HIGH", "line": 6, "filename": "positive2.tf" }, { "queryName": "Unrestricted Security Group Ingress", "severity": "HIGH", "line": 13, "filename": "positive3.tf" }, { "queryName": "Unrestricted Security Group Ingress", "severity": "HIGH", "line": 9, "filename": "positive4.tf" }, { "queryName": "Unrestricted Security Group Ingress", "severity": "HIGH", "line": 9, "filename": "positive5.tf" } ]
284
32,544
<reponame>DBatOWL/tutorials package com.baeldung.charstack; import static org.junit.Assert.assertEquals; import org.junit.jupiter.api.Test; public class CharStackWithArrayUnitTest { @Test public void whenCharStackIsCreated_thenItHasSize0() { CharStackWithArray charStack = new CharStackWithArray(); assertEquals(0, charStack.size()); } @Test public void givenEmptyCharStack_whenElementIsPushed_thenStackSizeisIncreased() { CharStackWithArray charStack = new CharStackWithArray(); charStack.push('A'); assertEquals(1, charStack.size()); } @Test public void givenEmptyCharStack_when5ElementIsPushed_thenStackSizeis() { CharStackWithArray charStack = new CharStackWithArray(); charStack.push('A'); charStack.push('B'); charStack.push('C'); charStack.push('D'); charStack.push('E'); assertEquals(5, charStack.size()); } @Test public void givenCharStack_whenElementIsPoppedFromStack_thenElementIsRemovedAndSizeChanges() { CharStackWithArray charStack = new CharStackWithArray(); charStack.push('A'); char element = charStack.pop(); assertEquals('A', element); assertEquals(0, charStack.size()); } @Test public void givenCharStack_whenElementIsPeeked_thenElementIsNotRemovedAndSizeDoesNotChange() { CharStackWithArray charStack = new CharStackWithArray(); charStack.push('A'); char element = charStack.peek(); assertEquals('A', element); assertEquals(1, charStack.size()); } }
634
765
<reponame>hyu-iot/gem5<gh_stars>100-1000 /***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera 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. *****************************************************************************/ /***************************************************************************** arith10.cpp -- Original Author: <NAME>, Synopsys, Inc., 2002-02-15 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ #include <stdlib.h> #include "systemc.h" #include "isaac.h" QTIsaac<8> rng; // Platform independent random number generator. int sc_main( int argc, char* argv[] ) { signed int vali[5] = { 0, 1, -1, 7, -8 }; signed int valj[5] = { 0, 1, -1, 7, -8 }; for (int i = 3; i < 32; ++i) { for (int j = 3; j < 32; ++j) { cout << "i = " << i << ", j = " << j << endl; sc_signed x(i); sc_signed y(j); sc_signed z(65), q(65); vali[3] = (1 << (i - 1)) - 1; vali[4] = - (1 << (i - 1)); valj[3] = (1 << (j - 1)) - 1; valj[4] = - (1 << (j - 1)); for (int ii = 0; ii < 100; ++ii) { for (int jj = 0; jj < 100; ++jj) { signed int qi = (ii < 5) ? vali[ii] : (rng.rand() & ((1 << i) - 1)); signed int qj = (jj < 5) ? valj[jj] : (rng.rand() & ((1 << j) - 1)); if (qi & (1 << (i - 1))) { qi = (qi << (32 - i)) >> (32 - i); } if (qj & (1 << (j - 1))) { qj = (qj << (32 - j)) >> (32 - j); } x = qi; y = qj; z = x * y; sc_assert( static_cast<sc_bigint<32> >( z.range(31,0) ) == (qi * qj) ); bool s; s = ((x < 0) != (y < 0)); sc_signed x2(i+1); x2 = x; if (x < 0) { x2 = - x; } sc_signed y2(j+1); y2 = y; if (y < 0) { y2 = - y; } sc_unsigned xhi(16), xlo(16); sc_unsigned yhi(16), ylo(16); sc_unsigned zero(16); zero = 0; xlo = i > 14 ? x2.range(15,0) : x2.range(i,0); xhi = i > 15 ? x2.range(i,16) : zero; ylo = j > 14 ? y2.range(15,0) : y2.range(j,0); yhi = j > 15 ? y2.range(j,16) : zero; q = (xlo * ylo) + (xhi * ylo + xlo * yhi) * 65536 + ((xhi * yhi) * 65536) * 65536; if (s) q = - q; if (z.range(63,0) != q.range(63,0)) { cout << "xlo = " << xlo << endl; cout << "xhi = " << xhi << endl; cout << "ylo = " << ylo << endl; cout << "yhi = " << yhi << endl; sc_assert(false); } } } } } return 0; }
2,235
315
#include "Tools/Algo/Matrix/Sparse_matrix/Sparse_matrix.hpp" namespace aff3ct { namespace tools { const std::vector<uint32_t>& Sparse_matrix ::get_cols_from_row(const size_t row_index) const { return this->row_to_cols[row_index]; } const std::vector<uint32_t>& Sparse_matrix ::get_rows_from_col(const size_t col_index) const { return this->col_to_rows[col_index]; } const std::vector<uint32_t>& Sparse_matrix ::operator[](const size_t col_index) const { return this->get_rows_from_col(col_index); } const std::vector<std::vector<uint32_t>>& Sparse_matrix ::get_row_to_cols() const { return this->row_to_cols; } const std::vector<std::vector<uint32_t>>& Sparse_matrix ::get_col_to_rows() const { return this->col_to_rows; } } }
309
1,350
<reponame>Shashi-rk/azure-sdk-for-java // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.policyinsights.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.policyinsights.models.ComponentStateDetails; import com.azure.resourcemanager.policyinsights.models.PolicyEvaluationDetails; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; /** Policy state record. */ @Fluent public final class PolicyStateInner { @JsonIgnore private final ClientLogger logger = new ClientLogger(PolicyStateInner.class); /* * OData entity ID; always set to null since policy state records do not * have an entity ID. */ @JsonProperty(value = "@odata.id") private String odataId; /* * OData context string; used by OData clients to resolve type information * based on metadata. */ @JsonProperty(value = "@odata.context") private String odataContext; /* * Timestamp for the policy state record. */ @JsonProperty(value = "timestamp") private OffsetDateTime timestamp; /* * Resource ID. */ @JsonProperty(value = "resourceId") private String resourceId; /* * Policy assignment ID. */ @JsonProperty(value = "policyAssignmentId") private String policyAssignmentId; /* * Policy definition ID. */ @JsonProperty(value = "policyDefinitionId") private String policyDefinitionId; /* * Effective parameters for the policy assignment. */ @JsonProperty(value = "effectiveParameters") private String effectiveParameters; /* * Flag which states whether the resource is compliant against the policy * assignment it was evaluated against. This property is deprecated; please * use ComplianceState instead. */ @JsonProperty(value = "isCompliant") private Boolean isCompliant; /* * Subscription ID. */ @JsonProperty(value = "subscriptionId") private String subscriptionId; /* * Resource type. */ @JsonProperty(value = "resourceType") private String resourceType; /* * Resource location. */ @JsonProperty(value = "resourceLocation") private String resourceLocation; /* * Resource group name. */ @JsonProperty(value = "resourceGroup") private String resourceGroup; /* * List of resource tags. */ @JsonProperty(value = "resourceTags") private String resourceTags; /* * Policy assignment name. */ @JsonProperty(value = "policyAssignmentName") private String policyAssignmentName; /* * Policy assignment owner. */ @JsonProperty(value = "policyAssignmentOwner") private String policyAssignmentOwner; /* * Policy assignment parameters. */ @JsonProperty(value = "policyAssignmentParameters") private String policyAssignmentParameters; /* * Policy assignment scope. */ @JsonProperty(value = "policyAssignmentScope") private String policyAssignmentScope; /* * Policy definition name. */ @JsonProperty(value = "policyDefinitionName") private String policyDefinitionName; /* * Policy definition action, i.e. effect. */ @JsonProperty(value = "policyDefinitionAction") private String policyDefinitionAction; /* * Policy definition category. */ @JsonProperty(value = "policyDefinitionCategory") private String policyDefinitionCategory; /* * Policy set definition ID, if the policy assignment is for a policy set. */ @JsonProperty(value = "policySetDefinitionId") private String policySetDefinitionId; /* * Policy set definition name, if the policy assignment is for a policy * set. */ @JsonProperty(value = "policySetDefinitionName") private String policySetDefinitionName; /* * Policy set definition owner, if the policy assignment is for a policy * set. */ @JsonProperty(value = "policySetDefinitionOwner") private String policySetDefinitionOwner; /* * Policy set definition category, if the policy assignment is for a policy * set. */ @JsonProperty(value = "policySetDefinitionCategory") private String policySetDefinitionCategory; /* * Policy set definition parameters, if the policy assignment is for a * policy set. */ @JsonProperty(value = "policySetDefinitionParameters") private String policySetDefinitionParameters; /* * Comma separated list of management group IDs, which represent the * hierarchy of the management groups the resource is under. */ @JsonProperty(value = "managementGroupIds") private String managementGroupIds; /* * Reference ID for the policy definition inside the policy set, if the * policy assignment is for a policy set. */ @JsonProperty(value = "policyDefinitionReferenceId") private String policyDefinitionReferenceId; /* * Compliance state of the resource. */ @JsonProperty(value = "complianceState") private String complianceState; /* * Policy evaluation details. */ @JsonProperty(value = "policyEvaluationDetails") private PolicyEvaluationDetails policyEvaluationDetails; /* * Policy definition group names. */ @JsonProperty(value = "policyDefinitionGroupNames") private List<String> policyDefinitionGroupNames; /* * Components state compliance records populated only when URL contains * $expand=components clause. */ @JsonProperty(value = "components") private List<ComponentStateDetails> components; /* * Evaluated policy definition version. */ @JsonProperty(value = "policyDefinitionVersion", access = JsonProperty.Access.WRITE_ONLY) private String policyDefinitionVersion; /* * Evaluated policy set definition version. */ @JsonProperty(value = "policySetDefinitionVersion", access = JsonProperty.Access.WRITE_ONLY) private String policySetDefinitionVersion; /* * Evaluated policy assignment version. */ @JsonProperty(value = "policyAssignmentVersion", access = JsonProperty.Access.WRITE_ONLY) private String policyAssignmentVersion; /* * Policy state record. */ @JsonIgnore private Map<String, Object> additionalProperties; /** * Get the odataId property: OData entity ID; always set to null since policy state records do not have an entity * ID. * * @return the odataId value. */ public String odataId() { return this.odataId; } /** * Set the odataId property: OData entity ID; always set to null since policy state records do not have an entity * ID. * * @param odataId the odataId value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withOdataId(String odataId) { this.odataId = odataId; return this; } /** * Get the odataContext property: OData context string; used by OData clients to resolve type information based on * metadata. * * @return the odataContext value. */ public String odataContext() { return this.odataContext; } /** * Set the odataContext property: OData context string; used by OData clients to resolve type information based on * metadata. * * @param odataContext the odataContext value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withOdataContext(String odataContext) { this.odataContext = odataContext; return this; } /** * Get the timestamp property: Timestamp for the policy state record. * * @return the timestamp value. */ public OffsetDateTime timestamp() { return this.timestamp; } /** * Set the timestamp property: Timestamp for the policy state record. * * @param timestamp the timestamp value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Get the resourceId property: Resource ID. * * @return the resourceId value. */ public String resourceId() { return this.resourceId; } /** * Set the resourceId property: Resource ID. * * @param resourceId the resourceId value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withResourceId(String resourceId) { this.resourceId = resourceId; return this; } /** * Get the policyAssignmentId property: Policy assignment ID. * * @return the policyAssignmentId value. */ public String policyAssignmentId() { return this.policyAssignmentId; } /** * Set the policyAssignmentId property: Policy assignment ID. * * @param policyAssignmentId the policyAssignmentId value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyAssignmentId(String policyAssignmentId) { this.policyAssignmentId = policyAssignmentId; return this; } /** * Get the policyDefinitionId property: Policy definition ID. * * @return the policyDefinitionId value. */ public String policyDefinitionId() { return this.policyDefinitionId; } /** * Set the policyDefinitionId property: Policy definition ID. * * @param policyDefinitionId the policyDefinitionId value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyDefinitionId(String policyDefinitionId) { this.policyDefinitionId = policyDefinitionId; return this; } /** * Get the effectiveParameters property: Effective parameters for the policy assignment. * * @return the effectiveParameters value. */ public String effectiveParameters() { return this.effectiveParameters; } /** * Set the effectiveParameters property: Effective parameters for the policy assignment. * * @param effectiveParameters the effectiveParameters value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withEffectiveParameters(String effectiveParameters) { this.effectiveParameters = effectiveParameters; return this; } /** * Get the isCompliant property: Flag which states whether the resource is compliant against the policy assignment * it was evaluated against. This property is deprecated; please use ComplianceState instead. * * @return the isCompliant value. */ public Boolean isCompliant() { return this.isCompliant; } /** * Set the isCompliant property: Flag which states whether the resource is compliant against the policy assignment * it was evaluated against. This property is deprecated; please use ComplianceState instead. * * @param isCompliant the isCompliant value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withIsCompliant(Boolean isCompliant) { this.isCompliant = isCompliant; return this; } /** * Get the subscriptionId property: Subscription ID. * * @return the subscriptionId value. */ public String subscriptionId() { return this.subscriptionId; } /** * Set the subscriptionId property: Subscription ID. * * @param subscriptionId the subscriptionId value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /** * Get the resourceType property: Resource type. * * @return the resourceType value. */ public String resourceType() { return this.resourceType; } /** * Set the resourceType property: Resource type. * * @param resourceType the resourceType value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withResourceType(String resourceType) { this.resourceType = resourceType; return this; } /** * Get the resourceLocation property: Resource location. * * @return the resourceLocation value. */ public String resourceLocation() { return this.resourceLocation; } /** * Set the resourceLocation property: Resource location. * * @param resourceLocation the resourceLocation value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; return this; } /** * Get the resourceGroup property: Resource group name. * * @return the resourceGroup value. */ public String resourceGroup() { return this.resourceGroup; } /** * Set the resourceGroup property: Resource group name. * * @param resourceGroup the resourceGroup value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withResourceGroup(String resourceGroup) { this.resourceGroup = resourceGroup; return this; } /** * Get the resourceTags property: List of resource tags. * * @return the resourceTags value. */ public String resourceTags() { return this.resourceTags; } /** * Set the resourceTags property: List of resource tags. * * @param resourceTags the resourceTags value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withResourceTags(String resourceTags) { this.resourceTags = resourceTags; return this; } /** * Get the policyAssignmentName property: Policy assignment name. * * @return the policyAssignmentName value. */ public String policyAssignmentName() { return this.policyAssignmentName; } /** * Set the policyAssignmentName property: Policy assignment name. * * @param policyAssignmentName the policyAssignmentName value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyAssignmentName(String policyAssignmentName) { this.policyAssignmentName = policyAssignmentName; return this; } /** * Get the policyAssignmentOwner property: Policy assignment owner. * * @return the policyAssignmentOwner value. */ public String policyAssignmentOwner() { return this.policyAssignmentOwner; } /** * Set the policyAssignmentOwner property: Policy assignment owner. * * @param policyAssignmentOwner the policyAssignmentOwner value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyAssignmentOwner(String policyAssignmentOwner) { this.policyAssignmentOwner = policyAssignmentOwner; return this; } /** * Get the policyAssignmentParameters property: Policy assignment parameters. * * @return the policyAssignmentParameters value. */ public String policyAssignmentParameters() { return this.policyAssignmentParameters; } /** * Set the policyAssignmentParameters property: Policy assignment parameters. * * @param policyAssignmentParameters the policyAssignmentParameters value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyAssignmentParameters(String policyAssignmentParameters) { this.policyAssignmentParameters = policyAssignmentParameters; return this; } /** * Get the policyAssignmentScope property: Policy assignment scope. * * @return the policyAssignmentScope value. */ public String policyAssignmentScope() { return this.policyAssignmentScope; } /** * Set the policyAssignmentScope property: Policy assignment scope. * * @param policyAssignmentScope the policyAssignmentScope value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyAssignmentScope(String policyAssignmentScope) { this.policyAssignmentScope = policyAssignmentScope; return this; } /** * Get the policyDefinitionName property: Policy definition name. * * @return the policyDefinitionName value. */ public String policyDefinitionName() { return this.policyDefinitionName; } /** * Set the policyDefinitionName property: Policy definition name. * * @param policyDefinitionName the policyDefinitionName value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyDefinitionName(String policyDefinitionName) { this.policyDefinitionName = policyDefinitionName; return this; } /** * Get the policyDefinitionAction property: Policy definition action, i.e. effect. * * @return the policyDefinitionAction value. */ public String policyDefinitionAction() { return this.policyDefinitionAction; } /** * Set the policyDefinitionAction property: Policy definition action, i.e. effect. * * @param policyDefinitionAction the policyDefinitionAction value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyDefinitionAction(String policyDefinitionAction) { this.policyDefinitionAction = policyDefinitionAction; return this; } /** * Get the policyDefinitionCategory property: Policy definition category. * * @return the policyDefinitionCategory value. */ public String policyDefinitionCategory() { return this.policyDefinitionCategory; } /** * Set the policyDefinitionCategory property: Policy definition category. * * @param policyDefinitionCategory the policyDefinitionCategory value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyDefinitionCategory(String policyDefinitionCategory) { this.policyDefinitionCategory = policyDefinitionCategory; return this; } /** * Get the policySetDefinitionId property: Policy set definition ID, if the policy assignment is for a policy set. * * @return the policySetDefinitionId value. */ public String policySetDefinitionId() { return this.policySetDefinitionId; } /** * Set the policySetDefinitionId property: Policy set definition ID, if the policy assignment is for a policy set. * * @param policySetDefinitionId the policySetDefinitionId value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicySetDefinitionId(String policySetDefinitionId) { this.policySetDefinitionId = policySetDefinitionId; return this; } /** * Get the policySetDefinitionName property: Policy set definition name, if the policy assignment is for a policy * set. * * @return the policySetDefinitionName value. */ public String policySetDefinitionName() { return this.policySetDefinitionName; } /** * Set the policySetDefinitionName property: Policy set definition name, if the policy assignment is for a policy * set. * * @param policySetDefinitionName the policySetDefinitionName value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicySetDefinitionName(String policySetDefinitionName) { this.policySetDefinitionName = policySetDefinitionName; return this; } /** * Get the policySetDefinitionOwner property: Policy set definition owner, if the policy assignment is for a policy * set. * * @return the policySetDefinitionOwner value. */ public String policySetDefinitionOwner() { return this.policySetDefinitionOwner; } /** * Set the policySetDefinitionOwner property: Policy set definition owner, if the policy assignment is for a policy * set. * * @param policySetDefinitionOwner the policySetDefinitionOwner value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicySetDefinitionOwner(String policySetDefinitionOwner) { this.policySetDefinitionOwner = policySetDefinitionOwner; return this; } /** * Get the policySetDefinitionCategory property: Policy set definition category, if the policy assignment is for a * policy set. * * @return the policySetDefinitionCategory value. */ public String policySetDefinitionCategory() { return this.policySetDefinitionCategory; } /** * Set the policySetDefinitionCategory property: Policy set definition category, if the policy assignment is for a * policy set. * * @param policySetDefinitionCategory the policySetDefinitionCategory value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicySetDefinitionCategory(String policySetDefinitionCategory) { this.policySetDefinitionCategory = policySetDefinitionCategory; return this; } /** * Get the policySetDefinitionParameters property: Policy set definition parameters, if the policy assignment is for * a policy set. * * @return the policySetDefinitionParameters value. */ public String policySetDefinitionParameters() { return this.policySetDefinitionParameters; } /** * Set the policySetDefinitionParameters property: Policy set definition parameters, if the policy assignment is for * a policy set. * * @param policySetDefinitionParameters the policySetDefinitionParameters value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicySetDefinitionParameters(String policySetDefinitionParameters) { this.policySetDefinitionParameters = policySetDefinitionParameters; return this; } /** * Get the managementGroupIds property: Comma separated list of management group IDs, which represent the hierarchy * of the management groups the resource is under. * * @return the managementGroupIds value. */ public String managementGroupIds() { return this.managementGroupIds; } /** * Set the managementGroupIds property: Comma separated list of management group IDs, which represent the hierarchy * of the management groups the resource is under. * * @param managementGroupIds the managementGroupIds value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withManagementGroupIds(String managementGroupIds) { this.managementGroupIds = managementGroupIds; return this; } /** * Get the policyDefinitionReferenceId property: Reference ID for the policy definition inside the policy set, if * the policy assignment is for a policy set. * * @return the policyDefinitionReferenceId value. */ public String policyDefinitionReferenceId() { return this.policyDefinitionReferenceId; } /** * Set the policyDefinitionReferenceId property: Reference ID for the policy definition inside the policy set, if * the policy assignment is for a policy set. * * @param policyDefinitionReferenceId the policyDefinitionReferenceId value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyDefinitionReferenceId(String policyDefinitionReferenceId) { this.policyDefinitionReferenceId = policyDefinitionReferenceId; return this; } /** * Get the complianceState property: Compliance state of the resource. * * @return the complianceState value. */ public String complianceState() { return this.complianceState; } /** * Set the complianceState property: Compliance state of the resource. * * @param complianceState the complianceState value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withComplianceState(String complianceState) { this.complianceState = complianceState; return this; } /** * Get the policyEvaluationDetails property: Policy evaluation details. * * @return the policyEvaluationDetails value. */ public PolicyEvaluationDetails policyEvaluationDetails() { return this.policyEvaluationDetails; } /** * Set the policyEvaluationDetails property: Policy evaluation details. * * @param policyEvaluationDetails the policyEvaluationDetails value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyEvaluationDetails(PolicyEvaluationDetails policyEvaluationDetails) { this.policyEvaluationDetails = policyEvaluationDetails; return this; } /** * Get the policyDefinitionGroupNames property: Policy definition group names. * * @return the policyDefinitionGroupNames value. */ public List<String> policyDefinitionGroupNames() { return this.policyDefinitionGroupNames; } /** * Set the policyDefinitionGroupNames property: Policy definition group names. * * @param policyDefinitionGroupNames the policyDefinitionGroupNames value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withPolicyDefinitionGroupNames(List<String> policyDefinitionGroupNames) { this.policyDefinitionGroupNames = policyDefinitionGroupNames; return this; } /** * Get the components property: Components state compliance records populated only when URL contains * $expand=components clause. * * @return the components value. */ public List<ComponentStateDetails> components() { return this.components; } /** * Set the components property: Components state compliance records populated only when URL contains * $expand=components clause. * * @param components the components value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withComponents(List<ComponentStateDetails> components) { this.components = components; return this; } /** * Get the policyDefinitionVersion property: Evaluated policy definition version. * * @return the policyDefinitionVersion value. */ public String policyDefinitionVersion() { return this.policyDefinitionVersion; } /** * Get the policySetDefinitionVersion property: Evaluated policy set definition version. * * @return the policySetDefinitionVersion value. */ public String policySetDefinitionVersion() { return this.policySetDefinitionVersion; } /** * Get the policyAssignmentVersion property: Evaluated policy assignment version. * * @return the policyAssignmentVersion value. */ public String policyAssignmentVersion() { return this.policyAssignmentVersion; } /** * Get the additionalProperties property: Policy state record. * * @return the additionalProperties value. */ @JsonAnyGetter public Map<String, Object> additionalProperties() { return this.additionalProperties; } /** * Set the additionalProperties property: Policy state record. * * @param additionalProperties the additionalProperties value to set. * @return the PolicyStateInner object itself. */ public PolicyStateInner withAdditionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; return this; } @JsonAnySetter void withAdditionalProperties(String key, Object value) { if (additionalProperties == null) { additionalProperties = new HashMap<>(); } additionalProperties.put(key, value); } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (policyEvaluationDetails() != null) { policyEvaluationDetails().validate(); } if (components() != null) { components().forEach(e -> e.validate()); } } }
9,805
390
<filename>blueflood-core/src/main/java/com/rackspacecloud/blueflood/cache/AbstractJmxCache.java /* * Copyright 2013 Rackspace * * 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.rackspacecloud.blueflood.cache; import com.codahale.metrics.Gauge; import com.codahale.metrics.JmxAttributeGauge; import com.codahale.metrics.MetricRegistry; import com.google.common.cache.CacheStats; import com.rackspacecloud.blueflood.utils.Metrics; import javax.management.ObjectName; public abstract class AbstractJmxCache implements CacheStatsMBean { private Gauge hitCount; private Gauge hitRate; private Gauge loadCount; private Gauge missRate; private Gauge requestCount; private Gauge totalLoadTime; public abstract CacheStats getStats(); public long getHitCount() { return getStats().hitCount(); } public double getHitRate() { return getStats().hitRate(); } public long getMissCount() { return getStats().missCount(); } public double getMissRate() { return getStats().missRate(); } public long getLoadCount() { return getStats().loadCount(); } public long getRequestCount() { return getStats().requestCount(); } public long getTotalLoadTime() { return getStats().totalLoadTime(); } public void instantiateYammerMetrics(Class klass, String scope, ObjectName nameObj) { String name = MetricRegistry.name(klass); if (scope != null) { name = MetricRegistry.name(name, scope); } MetricRegistry reg = Metrics.getRegistry(); hitCount = reg.register(MetricRegistry.name(name, "Hit Count"), new JmxAttributeGauge(nameObj, "HitCount")); hitRate = reg.register(MetricRegistry.name(name, "Hit Rate"), new JmxAttributeGauge(nameObj, "HitRate")); loadCount = reg.register(MetricRegistry.name(name, "Load Count"), new JmxAttributeGauge(nameObj, "LoadCount")); missRate = reg.register(MetricRegistry.name(name, "Miss Rate"), new JmxAttributeGauge(nameObj, "MissRate")); requestCount = reg.register(MetricRegistry.name(name, "Request Count"), new JmxAttributeGauge(nameObj, "RequestCount")); totalLoadTime = reg.register(MetricRegistry.name(name, "Total Load Time"), new JmxAttributeGauge(nameObj, "TotalLoadTime")); } }
1,121
4,013
from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck from checkov.common.models.enums import CheckCategories, CheckResult class GoogleCloudDNSSECEnabled(BaseResourceValueCheck): """ Looks for DNSSEC state at dns_managed_zone: https://www.terraform.io/docs/providers/google/r/dns_managed_zone.html#state """ def __init__(self): name = "Ensure that DNSSEC is enabled for Cloud DNS" id = "CKV_GCP_16" supported_resources = ["google_dns_managed_zone"] categories = [CheckCategories.ENCRYPTION] super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources) def scan_resource_conf(self, conf): if 'visibility' in conf: if conf['visibility'][0] == 'private': return CheckResult.UNKNOWN # check is irrelevant (cannot set DNSSEC to anything else) # default visibility is public; just use base class implementation return super().scan_resource_conf(conf) def get_inspected_key(self): return "dnssec_config/[0]/state" def get_expected_value(self): return "on" def get_expected_values(self): return [self.get_expected_value(), "transfer"] check = GoogleCloudDNSSECEnabled()
489
408
/* * Copyright (C) 2012 The Guava 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 com.google.common.reflect; import static com.google.common.base.Preconditions.checkNotNull; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import javax.annotation.Nullable; /** * Represents either a {@link Field}, a {@link Method} or a {@link Constructor}. Provides * convenience methods such as {@link #isPublic} and {@link #isPackagePrivate}. * * @author <NAME> */ class Element extends AccessibleObject implements Member { private final AccessibleObject accessibleObject; private final Member member; <M extends AccessibleObject & Member> Element(M member) { checkNotNull(member); this.accessibleObject = member; this.member = member; } public TypeToken<?> getOwnerType() { return TypeToken.of(getDeclaringClass()); } @Override public final boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { return accessibleObject.isAnnotationPresent(annotationClass); } @Override public final <A extends Annotation> A getAnnotation(Class<A> annotationClass) { return accessibleObject.getAnnotation(annotationClass); } @Override public final Annotation[] getAnnotations() { return accessibleObject.getAnnotations(); } @Override public final Annotation[] getDeclaredAnnotations() { return accessibleObject.getDeclaredAnnotations(); } @Override public final void setAccessible(boolean flag) throws SecurityException { accessibleObject.setAccessible(flag); } @Override public final boolean isAccessible() { return accessibleObject.isAccessible(); } @Override public Class<?> getDeclaringClass() { return member.getDeclaringClass(); } @Override public final String getName() { return member.getName(); } @Override public final int getModifiers() { return member.getModifiers(); } @Override public final boolean isSynthetic() { return member.isSynthetic(); } /** Returns true if the element is public. */ public final boolean isPublic() { return Modifier.isPublic(getModifiers()); } /** Returns true if the element is protected. */ public final boolean isProtected() { return Modifier.isProtected(getModifiers()); } /** Returns true if the element is package-private. */ public final boolean isPackagePrivate() { return !isPrivate() && !isPublic() && !isProtected(); } /** Returns true if the element is private. */ public final boolean isPrivate() { return Modifier.isPrivate(getModifiers()); } /** Returns true if the element is static. */ public final boolean isStatic() { return Modifier.isStatic(getModifiers()); } /** * Returns {@code true} if this method is final, per {@code Modifier.isFinal(getModifiers())}. * * <p>Note that a method may still be effectively "final", or non-overridable when it has no * {@code final} keyword. For example, it could be private, or it could be declared by a final * class. To tell whether a method is overridable, use {@link Invokable#isOverridable}. */ public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } /** Returns true if the method is abstract. */ public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } /** Returns true if the element is native. */ public final boolean isNative() { return Modifier.isNative(getModifiers()); } /** Returns true if the method is synchronized. */ public final boolean isSynchronized() { return Modifier.isSynchronized(getModifiers()); } /** Returns true if the field is volatile. */ final boolean isVolatile() { return Modifier.isVolatile(getModifiers()); } /** Returns true if the field is transient. */ final boolean isTransient() { return Modifier.isTransient(getModifiers()); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof Element) { Element that = (Element) obj; return getOwnerType().equals(that.getOwnerType()) && member.equals(that.member); } return false; } @Override public int hashCode() { return member.hashCode(); } @Override public String toString() { return member.toString(); } }
1,490
939
<reponame>srihari-humbarwadi/neural-structured-learning # Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Default configuration parameters.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function CONFIG = { 'string': { 'dataset': ('Dataset', 'WN18RR'), 'model': ('Model', 'RotE'), 'data_dir': ('Path to data directory', 'data/'), 'save_dir': ('Path to logs directory', 'logs/'), 'loss_fn': ('Loss function to use', 'SigmoidCrossEntropy'), 'initializer': ('Which initializer to use', 'GlorotNormal'), 'regularizer': ('Regularizer', 'N3'), 'optimizer': ('Optimizer', 'Adam'), 'bias': ('Bias term', 'learn'), 'dtype': ('Precision to use', 'float32'), }, 'float': { 'lr': ('Learning rate', 1e-3), 'lr_decay': ('Learning rate decay', 0.96), 'min_lr': ('Minimum learning rate decay', 1e-5), 'gamma': ('Margin for distance-based losses', 0), 'entity_reg': ('Regularization weight for entity embeddings', 0), 'rel_reg': ('Regularization weight for relation embeddings', 0), }, 'integer': { 'patience': ('Number of validation steps before early stopping', 20), 'valid': ('Number of epochs before computing validation metrics', 5), 'checkpoint': ('Number of epochs before checkpointing the model', 5), 'max_epochs': ('Maximum number of epochs to train for', 400), 'rank': ('Embeddings dimension', 500), 'batch_size': ('Batch size', 500), 'neg_sample_size': ('Negative sample size, -1 to use loss without negative sampling', 50), }, 'boolean': { 'train_c': ('Whether to train the hyperbolic curvature or not', True), 'debug': ('If debug is true, only use 1000 examples for' ' debugging purposes', False), 'save_logs': ('Whether to save the training logs or print to stdout', True), 'save_model': ('Whether to save the model weights', False) } }
961
1,723
// // MessageViewController.h // MessageViewController // // Created by <NAME> on 12/22/17. // Copyright © 2017 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for MessageViewController. FOUNDATION_EXPORT double MessageViewControllerVersionNumber; //! Project version string for MessageViewController. FOUNDATION_EXPORT const unsigned char MessageViewControllerVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <MessageViewController/PublicHeader.h>
149
1,001
<reponame>yndu13/aliyun-openapi-python-sdk<gh_stars>1000+ # 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. from aliyunsdkcore.request import RpcRequest from aliyunsdkoutboundbot.endpoint import endpoint_data class QueryJobsWithResultRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'OutboundBot', '2019-12-26', 'QueryJobsWithResult','outboundbot') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_HasReachedEndOfFlowFilter(self): return self.get_query_params().get('HasReachedEndOfFlowFilter') def set_HasReachedEndOfFlowFilter(self,HasReachedEndOfFlowFilter): self.add_query_param('HasReachedEndOfFlowFilter',HasReachedEndOfFlowFilter) def get_HasAnsweredFilter(self): return self.get_query_params().get('HasAnsweredFilter') def set_HasAnsweredFilter(self,HasAnsweredFilter): self.add_query_param('HasAnsweredFilter',HasAnsweredFilter) def get_PageNumber(self): return self.get_query_params().get('PageNumber') def set_PageNumber(self,PageNumber): self.add_query_param('PageNumber',PageNumber) def get_QueryText(self): return self.get_query_params().get('QueryText') def set_QueryText(self,QueryText): self.add_query_param('QueryText',QueryText) def get_HasHangUpByRejectionFilter(self): return self.get_query_params().get('HasHangUpByRejectionFilter') def set_HasHangUpByRejectionFilter(self,HasHangUpByRejectionFilter): self.add_query_param('HasHangUpByRejectionFilter',HasHangUpByRejectionFilter) def get_InstanceId(self): return self.get_query_params().get('InstanceId') def set_InstanceId(self,InstanceId): self.add_query_param('InstanceId',InstanceId) def get_JobStatusFilter(self): return self.get_query_params().get('JobStatusFilter') def set_JobStatusFilter(self,JobStatusFilter): self.add_query_param('JobStatusFilter',JobStatusFilter) def get_PageSize(self): return self.get_query_params().get('PageSize') def set_PageSize(self,PageSize): self.add_query_param('PageSize',PageSize) def get_JobGroupId(self): return self.get_query_params().get('JobGroupId') def set_JobGroupId(self,JobGroupId): self.add_query_param('JobGroupId',JobGroupId)
1,092
5,428
<reponame>haoflynet/haipproxy<gh_stars>1000+ """ web api for haipproxy """ import os from flask import ( Flask, jsonify as flask_jsonify) from ..client.py_cli import ProxyFetcher from ..config.rules import VALIDATOR_TASKS def jsonify(*args, **kwargs): response = flask_jsonify(*args, **kwargs) if not response.data.endswith(b"\n"): response.data += b"\n" return response # web api uses robin strategy for proxy schedule, crawler client may implete # its own schedule strategy usage_registry = {task['name']: ProxyFetcher('task') for task in VALIDATOR_TASKS} app = Flask(__name__) app.debug = bool(os.environ.get("DEBUG")) app.config["JSONIFY_PRETTYPRINT_REGULAR"] = True @app.errorhandler(404) def not_found(e): return jsonify({ 'reason': 'resource not found', 'status_code': 404 }) @app.errorhandler(500) def not_found(e): return jsonify({ 'reason': 'internal server error', 'status_code': 500 }) @app.route("/proxy/get/<usage>") def get_proxy(usage): # default usage is 'https' if usage not in usage_registry: usage = 'https' proxy_fetcher = usage_registry.get(usage) ip = proxy_fetcher.get_proxy() return jsonify({ 'proxy': ip, 'resource': usage, 'status_code': 200 }) @app.route("/proxy/delete/<usage>/<proxy>") def delete_proxy(usage, proxy): if usage not in usage_registry: usage = 'https' proxy_fetcher = usage_registry.get(usage) proxy_fetcher.delete_proxy(proxy) return jsonify({ 'result': 'ok', 'status_code': 200 }) @app.route("/pool/get/<usage>") def get_proxies(usage): if usage not in usage_registry: usage = 'https' proxy_fetcher = usage_registry.get(usage) return jsonify({ 'pool': proxy_fetcher.pool, 'resource': usage, 'status_code': 200 })
782
1,707
package org.apache.spark.sql.cassandra;
14
382
package com.fangxu.dota2helper.presenter; /** * Created by Administrator on 2016/7/19. */ public class VideoCachePresenter { }
46
473
<reponame>pingjuiliao/cb-multios #pragma once #include "cgc_types.h" void cgc_protocol_send_str(char* str); void cgc_protocol_with_recv_string(void (^block)(uint16 len, char* str)); void cgc_protocol_consume_str();
91
1,220
/* * The MIT License * * Copyright (c) 2013-2016 reark project contributors * * https://github.com/reark/reark/graphs/contributors * * 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 io.reark.reark.pojo; import android.support.annotation.NonNull; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import io.reark.reark.utils.Log; import static io.reark.reark.utils.Preconditions.checkNotNull; /** * Pojo base class that supports overwriting the fields with fields from * another instance of the same class. */ public abstract class OverwritablePojo<T extends OverwritablePojo<T>> { private static final String TAG = OverwritablePojo.class.getSimpleName(); @NonNull protected abstract Class<T> getTypeParameterClass(); @NonNull @SuppressWarnings("unchecked") public T overwrite(@NonNull final T other) { checkNotNull(other, "Can't overwrite with null value"); if (equals(other)) { return (T) this; } for (Field field : getTypeParameterClass().getDeclaredFields()) { final int modifiers = field.getModifiers(); if (hasIllegalAccessModifiers(modifiers)) { continue; } if (!Modifier.isPublic(modifiers) || Modifier.isFinal(modifiers)) { // We want to overwrite also private and final fields. This allows field access // for this instance of the field. The actual field of the class isn't modified. field.setAccessible(true); } try { if (!isEmpty(field, other)) { field.set(this, field.get(other)); } } catch (IllegalAccessException e) { Log.e(TAG, "Failed set at " + field.getName(), e); } } return (T) this; } protected boolean hasIllegalAccessModifiers(int modifiers) { return Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers); } protected boolean isEmpty(@NonNull final Field field, @NonNull final OverwritablePojo<T> pojo) { try { Object value = field.get(pojo); if (value == null) { return true; } else if (value instanceof String) { return isEmpty((String) value); } else if (value instanceof Boolean) { return false; } else if (value instanceof Long) { return isEmpty((Long) value); } else if (value instanceof Integer) { return isEmpty((Integer) value); } else if (value instanceof Double) { return isEmpty((Double) value); } else if (value instanceof Float) { return isEmpty((Float) value); } else if (value instanceof Short) { return isEmpty((Short) value); } else if (value instanceof Byte) { return isEmpty((Byte) value); } else if (value instanceof Character) { return isEmpty((Character) value); } } catch (IllegalAccessException e) { Log.e(TAG, "Failed get at " + field.getName(), e); } // Derived objects with more types should first check the new types, and then the base // types with this method. Thus, we can assume reaching here is always an error. Log.e(TAG, "Unknown field type: " + field.getName()); return true; } protected boolean isEmpty(String value) { return false; } protected boolean isEmpty(long value) { return false; } protected boolean isEmpty(int value) { return false; } protected boolean isEmpty(double value) { return false; } protected boolean isEmpty(float value) { return false; } protected boolean isEmpty(short value) { return false; } protected boolean isEmpty(byte value) { return false; } protected boolean isEmpty(char value) { return false; } @Override public boolean equals(Object o) { return getTypeParameterClass().isInstance(o); } }
2,031
347
<filename>frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/macpool/MacRangeModel.java package org.ovirt.engine.ui.uicommonweb.models.macpool; import org.ovirt.engine.core.common.businessentities.MacRange; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.Model; import org.ovirt.engine.ui.uicommonweb.validation.IValidation; import org.ovirt.engine.ui.uicommonweb.validation.MacAddressValidation; import org.ovirt.engine.ui.uicommonweb.validation.MacRangeValidation; public class MacRangeModel extends Model { private final MacRange macRange; private final EntityModel<String> leftBound = new EntityModel<>(); private final EntityModel<String> rightBound = new EntityModel<>(); private final EntityModel<Integer> macsCount = new EntityModel<>(); public EntityModel<String> getLeftBound() { return leftBound; } public EntityModel<String> getRightBound() { return rightBound; } public EntityModel<Integer> getMacsCount() { return macsCount; } public MacRangeModel() { this(new MacRange()); } public MacRangeModel(MacRange macRange) { this.macRange = macRange; init(); } private void init() { leftBound.setEntity(macRange.getMacFrom() == null ? "" : macRange.getMacFrom()); //$NON-NLS-1$ rightBound.setEntity(macRange.getMacTo() == null ? "" : macRange.getMacTo()); //$NON-NLS-1$ recalculateMacsCount(); } public MacRange flush() { macRange.setMacFrom(leftBound.getEntity()); macRange.setMacTo(rightBound.getEntity()); return macRange; } public boolean validate() { leftBound.validateEntity(new IValidation[] { new MacAddressValidation() }); rightBound.validateEntity(new IValidation[] { new MacAddressValidation() }); if (leftBound.getIsValid() && rightBound.getIsValid()) { rightBound.validateEntity(new IValidation[] { new MacRangeValidation(leftBound.getEntity())}); } setIsValid(leftBound.getIsValid() && rightBound.getIsValid()); return getIsValid(); } public void recalculateMacsCount() { if (!validate()) { getMacsCount().setEntity(null); return; } String from = getLeftBound().getEntity(); String to = getRightBound().getEntity(); Long count = MacRangeValidation.macToLong(to) - MacRangeValidation.macToLong(from) + 1; getMacsCount().setEntity(count.intValue()); } }
1,005
348
<gh_stars>100-1000 import torch import torch.nn as nn from torchvision.models import vgg16 from torch.autograd import Variable from collections import OrderedDict import torch.nn.functional as F import sys sys.path.append('../') from libs.pytorch_spn.modules.gaterecurrent2dnoind import GateRecurrent2dnoind class spn_block(nn.Module): def __init__(self, horizontal, reverse): super(spn_block, self).__init__() self.propagator = GateRecurrent2dnoind(horizontal,reverse) def forward(self,x,G1,G2,G3): sum_abs = G1.abs() + G2.abs() + G3.abs() sum_abs.data[sum_abs.data == 0] = 1e-6 mask_need_norm = sum_abs.ge(1) mask_need_norm = mask_need_norm.float() G1_norm = torch.div(G1, sum_abs) G2_norm = torch.div(G2, sum_abs) G3_norm = torch.div(G3, sum_abs) G1 = torch.add(-mask_need_norm, 1) * G1 + mask_need_norm * G1_norm G2 = torch.add(-mask_need_norm, 1) * G2 + mask_need_norm * G2_norm G3 = torch.add(-mask_need_norm, 1) * G3 + mask_need_norm * G3_norm return self.propagator(x,G1,G2,G3) class VGG(nn.Module): def __init__(self,nf): super(VGG,self).__init__() self.conv1 = nn.Conv2d(3,nf,3,padding = 1) # 256 x 256 self.pool1 = nn.MaxPool2d(kernel_size = 3, stride = 2,padding=1) self.conv2 = nn.Conv2d(nf,nf*2,3,padding = 1) # 128 x 128 self.pool2 = nn.MaxPool2d(kernel_size = 3, stride = 2,padding=1) self.conv3 = nn.Conv2d(nf*2,nf*4,3,padding = 1) # 64 x 64 self.pool3 = nn.MaxPool2d(kernel_size = 3, stride = 2,padding=1) # 32 x 32 self.conv4 = nn.Conv2d(nf*4,nf*8,3,padding = 1) def forward(self,x): output = {} output['conv1'] = self.conv1(x) x = F.relu(output['conv1']) x = self.pool1(x) output['conv2'] = self.conv2(x) # 128 x 128 x = F.relu(output['conv2']) x = self.pool2(x) output['conv3'] = self.conv3(x) # 64 x 64 x = F.relu(output['conv3']) output['pool3'] = self.pool3(x) # 32 x 32 output['conv4'] = self.conv4(output['pool3']) return output class Decoder(nn.Module): def __init__(self,nf=32,spn=1): super(Decoder,self).__init__() # 32 x 32 self.layer0 = nn.Conv2d(nf*8,nf*4,1,1,0) # edge_conv5 self.layer1 = nn.Upsample(scale_factor=2,mode='bilinear') self.layer2 = nn.Sequential(nn.Conv2d(nf*4,nf*4,3,1,1), # edge_conv8 nn.ELU(inplace=True)) # 64 x 64 self.layer3 = nn.Upsample(scale_factor=2,mode='bilinear') self.layer4 = nn.Sequential(nn.Conv2d(nf*4,nf*2,3,1,1), # edge_conv8 nn.ELU(inplace=True)) # 128 x 128 self.layer5 = nn.Upsample(scale_factor=2,mode='bilinear') self.layer6 = nn.Sequential(nn.Conv2d(nf*2,nf,3,1,1), # edge_conv8 nn.ELU(inplace=True)) if(spn == 1): self.layer7 = nn.Conv2d(nf,nf*12,3,1,1) else: self.layer7 = nn.Conv2d(nf,nf*24,3,1,1) self.spn = spn # 256 x 256 def forward(self,encode_feature): output = {} output['0'] = self.layer0(encode_feature['conv4']) output['1'] = self.layer1(output['0']) output['2'] = self.layer2(output['1']) output['2res'] = output['2'] + encode_feature['conv3'] # 64 x 64 output['3'] = self.layer3(output['2res']) output['4'] = self.layer4(output['3']) output['4res'] = output['4'] + encode_feature['conv2'] # 128 x 128 output['5'] = self.layer5(output['4res']) output['6'] = self.layer6(output['5']) output['6res'] = output['6'] + encode_feature['conv1'] output['7'] = self.layer7(output['6res']) return output['7'] class SPN(nn.Module): def __init__(self,nf=32,spn=1): super(SPN,self).__init__() # conv for mask self.mask_conv = nn.Conv2d(3,nf,3,1,1) # guidance network self.encoder = VGG(nf) self.decoder = Decoder(nf,spn) # spn blocks self.left_right = spn_block(True,False) self.right_left = spn_block(True,True) self.top_down = spn_block(False, False) self.down_top = spn_block(False,True) # post upsample self.post = nn.Conv2d(nf,3,3,1,1) self.nf = nf def forward(self,x,rgb): # feature for mask X = self.mask_conv(x) # guidance features = self.encoder(rgb) guide = self.decoder(features) G = torch.split(guide,self.nf,1) out1 = self.left_right(X,G[0],G[1],G[2]) out2 = self.right_left(X,G[3],G[4],G[5]) out3 = self.top_down(X,G[6],G[7],G[8]) out4 = self.down_top(X,G[9],G[10],G[11]) out = torch.max(out1,out2) out = torch.max(out,out3) out = torch.max(out,out4) return self.post(out) if __name__ == '__main__': spn = SPN() spn = spn.cuda() for i in range(100): x = Variable(torch.Tensor(1,3,256,256)).cuda() rgb = Variable(torch.Tensor(1,3,256,256)).cuda() output = spn(x,rgb) print(output.size())
2,829
2,978
<gh_stars>1000+ /* * Copyright Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.operator.cluster.operator.assembly; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodBuilder; import io.fabric8.kubernetes.api.model.apps.StatefulSet; import io.strimzi.api.kafka.model.Kafka; import io.strimzi.api.kafka.model.KafkaBuilder; import io.strimzi.api.kafka.model.listener.arraylistener.GenericKafkaListenerBuilder; import io.strimzi.api.kafka.model.listener.arraylistener.KafkaListenerType; import io.strimzi.certs.CertManager; import io.strimzi.operator.KubernetesVersion; import io.strimzi.operator.PlatformFeaturesAvailability; import io.strimzi.operator.cluster.ClusterOperatorConfig; import io.strimzi.operator.cluster.KafkaVersionTestUtils; import io.strimzi.operator.cluster.ResourceUtils; import io.strimzi.operator.cluster.model.KafkaCluster; import io.strimzi.operator.cluster.model.KafkaVersion; import io.strimzi.operator.cluster.model.ZookeeperCluster; import io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier; import io.strimzi.operator.cluster.operator.resource.StatefulSetOperator; import io.strimzi.operator.common.Annotations; import io.strimzi.operator.common.PasswordGenerator; import io.strimzi.operator.common.Reconciliation; import io.strimzi.operator.common.model.Labels; import io.strimzi.operator.common.operator.MockCertManager; import io.strimzi.operator.common.operator.resource.CrdOperator; import io.strimzi.operator.common.operator.resource.PodOperator; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.junit5.Checkpoint; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; @ExtendWith(VertxExtension.class) public class KafkaAssemblyOperatorManualRollingUpdatesTest { private final KubernetesVersion kubernetesVersion = KubernetesVersion.V1_18; private final MockCertManager certManager = new MockCertManager(); private final PasswordGenerator passwordGenerator = new PasswordGenerator(10, "a", "a"); private final ClusterOperatorConfig config = ResourceUtils.dummyClusterOperatorConfig(VERSIONS); private static final KafkaVersion.Lookup VERSIONS = KafkaVersionTestUtils.getKafkaVersionLookup(); private final String namespace = "testns"; private final String clusterName = "testkafka"; protected static Vertx vertx; @BeforeAll public static void before() { vertx = Vertx.vertx(); } @AfterAll public static void after() { vertx.close(); } @Test public void testNoManualRollingUpdate(VertxTestContext context) throws ParseException { Kafka kafka = new KafkaBuilder() .withNewMetadata() .withName(clusterName) .withNamespace(namespace) .withGeneration(2L) .endMetadata() .withNewSpec() .withNewKafka() .withReplicas(3) .withListeners(new GenericKafkaListenerBuilder() .withName("plain") .withPort(9092) .withType(KafkaListenerType.INTERNAL) .withTls(false) .build()) .withNewEphemeralStorage() .endEphemeralStorage() .endKafka() .withNewZookeeper() .withReplicas(3) .withNewEphemeralStorage() .endEphemeralStorage() .endZookeeper() .endSpec() .build(); KafkaCluster kafkaCluster = KafkaCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafka, VERSIONS); ZookeeperCluster zkCluster = ZookeeperCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafka, VERSIONS); ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false); StatefulSetOperator mockKafkaSetOps = supplier.kafkaSetOperations; when(mockKafkaSetOps.getAsync(any(), any())).thenReturn(Future.succeededFuture(kafkaCluster.generateStatefulSet(false, null, null))); StatefulSetOperator mockZkSetOps = supplier.zkSetOperations; when(mockZkSetOps.getAsync(any(), any())).thenReturn(Future.succeededFuture(zkCluster.generateStatefulSet(false, null, null))); PodOperator mockPodOps = supplier.podOperations; when(mockPodOps.listAsync(any(), eq(zkCluster.getSelectorLabels()))).thenReturn(Future.succeededFuture(Collections.emptyList())); when(mockPodOps.listAsync(any(), eq(kafkaCluster.getSelectorLabels()))).thenReturn(Future.succeededFuture(Collections.emptyList())); when(mockPodOps.listAsync(any(), any(Labels.class))).thenReturn(Future.succeededFuture(Collections.emptyList())); CrdOperator mockKafkaOps = supplier.kafkaOperator; when(mockKafkaOps.getAsync(eq(namespace), eq(clusterName))).thenReturn(Future.succeededFuture(kafka)); when(mockKafkaOps.get(eq(namespace), eq(clusterName))).thenReturn(kafka); when(mockKafkaOps.updateStatusAsync(any(), any())).thenReturn(Future.succeededFuture()); when(mockKafkaOps.updateStatusAsync(any(), any())).thenReturn(Future.succeededFuture()); MockKafkaAssemblyOperator kao = new MockKafkaAssemblyOperator( vertx, new PlatformFeaturesAvailability(false, kubernetesVersion), certManager, passwordGenerator, supplier, config); Checkpoint async = context.checkpoint(); kao.reconcile(new Reconciliation("test-trigger", Kafka.RESOURCE_KIND, namespace, clusterName)) .onComplete(context.succeeding(v -> context.verify(() -> { Mockito.verify(mockKafkaSetOps, never()).maybeRollingUpdate(any(), any(), any()); Mockito.verify(mockZkSetOps, never()).maybeRollingUpdate(any(), any(), any()); async.flag(); }))); } @Test public void testStatefulSetManualRollingUpdate(VertxTestContext context) throws ParseException { Kafka kafka = new KafkaBuilder() .withNewMetadata() .withName(clusterName) .withNamespace(namespace) .withGeneration(2L) .endMetadata() .withNewSpec() .withNewKafka() .withReplicas(3) .withListeners(new GenericKafkaListenerBuilder() .withName("plain") .withPort(9092) .withType(KafkaListenerType.INTERNAL) .withTls(false) .build()) .withNewEphemeralStorage() .endEphemeralStorage() .endKafka() .withNewZookeeper() .withReplicas(3) .withNewEphemeralStorage() .endEphemeralStorage() .endZookeeper() .endSpec() .build(); KafkaCluster kafkaCluster = KafkaCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafka, VERSIONS); ZookeeperCluster zkCluster = ZookeeperCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafka, VERSIONS); ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false); StatefulSetOperator mockKafkaSetOps = supplier.kafkaSetOperations; when(mockKafkaSetOps.getAsync(any(), any())).thenAnswer(i -> { StatefulSet sts = kafkaCluster.generateStatefulSet(false, null, null); sts.getMetadata().getAnnotations().put(Annotations.ANNO_STRIMZI_IO_MANUAL_ROLLING_UPDATE, "true"); return Future.succeededFuture(sts); }); StatefulSetOperator mockZkSetOps = supplier.zkSetOperations; when(mockZkSetOps.getAsync(any(), any())).thenAnswer(i -> { StatefulSet sts = zkCluster.generateStatefulSet(false, null, null); sts.getMetadata().getAnnotations().put(Annotations.ANNO_STRIMZI_IO_MANUAL_ROLLING_UPDATE, "true"); return Future.succeededFuture(sts); }); ArgumentCaptor<Function<Pod, List<String>>> zkNeedsRestartCaptor = ArgumentCaptor.forClass(Function.class); when(mockZkSetOps.maybeRollingUpdate(any(), any(), zkNeedsRestartCaptor.capture())).thenReturn(Future.succeededFuture()); PodOperator mockPodOps = supplier.podOperations; when(mockPodOps.listAsync(any(), eq(zkCluster.getSelectorLabels()))).thenReturn(Future.succeededFuture(Collections.emptyList())); when(mockPodOps.listAsync(any(), eq(kafkaCluster.getSelectorLabels()))).thenReturn(Future.succeededFuture(Collections.emptyList())); CrdOperator mockKafkaOps = supplier.kafkaOperator; when(mockKafkaOps.getAsync(eq(namespace), eq(clusterName))).thenReturn(Future.succeededFuture(kafka)); when(mockKafkaOps.get(eq(namespace), eq(clusterName))).thenReturn(kafka); when(mockKafkaOps.updateStatusAsync(any(), any())).thenReturn(Future.succeededFuture()); MockKafkaAssemblyOperator kao = new MockKafkaAssemblyOperator( vertx, new PlatformFeaturesAvailability(false, kubernetesVersion), certManager, passwordGenerator, supplier, config); Checkpoint async = context.checkpoint(); kao.reconcile(new Reconciliation("test-trigger", Kafka.RESOURCE_KIND, namespace, clusterName)) .onComplete(context.succeeding(v -> context.verify(() -> { // Verify Zookeeper rolling updates Mockito.verify(mockZkSetOps, times(1)).maybeRollingUpdate(any(), any(), any()); Function<Pod, List<String>> zkPodNeedsRestart = zkNeedsRestartCaptor.getValue(); assertThat(zkPodNeedsRestart.apply(podWithName("my-cluster-zookeeper-0")), is(Collections.singletonList("manual rolling update"))); assertThat(zkPodNeedsRestart.apply(podWithName("my-cluster-zookeeper-1")), is(Collections.singletonList("manual rolling update"))); assertThat(zkPodNeedsRestart.apply(podWithName("my-cluster-zookeeper-2")), is(Collections.singletonList("manual rolling update"))); // Verify Kafka rolling updates assertThat(kao.maybeRollKafkaInvocations, is(1)); assertThat(kao.kafkaPodNeedsRestart.apply(podWithName("my-cluster-kafka-0")), is(Collections.singletonList("manual rolling update"))); assertThat(kao.kafkaPodNeedsRestart.apply(podWithName("my-cluster-kafka-1")), is(Collections.singletonList("manual rolling update"))); assertThat(kao.kafkaPodNeedsRestart.apply(podWithName("my-cluster-kafka-2")), is(Collections.singletonList("manual rolling update"))); async.flag(); }))); } @Test public void testPodManualRollingUpdate(VertxTestContext context) throws ParseException { Kafka kafka = new KafkaBuilder() .withNewMetadata() .withName(clusterName) .withNamespace(namespace) .withGeneration(2L) .endMetadata() .withNewSpec() .withNewKafka() .withReplicas(3) .withListeners(new GenericKafkaListenerBuilder() .withName("plain") .withPort(9092) .withType(KafkaListenerType.INTERNAL) .withTls(false) .build()) .withNewEphemeralStorage() .endEphemeralStorage() .endKafka() .withNewZookeeper() .withReplicas(3) .withNewEphemeralStorage() .endEphemeralStorage() .endZookeeper() .endSpec() .build(); KafkaCluster kafkaCluster = KafkaCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafka, VERSIONS); ZookeeperCluster zkCluster = ZookeeperCluster.fromCrd(Reconciliation.DUMMY_RECONCILIATION, kafka, VERSIONS); ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(false); StatefulSetOperator mockKafkaSetOps = supplier.kafkaSetOperations; when(mockKafkaSetOps.getAsync(any(), any())).thenReturn(Future.succeededFuture(kafkaCluster.generateStatefulSet(false, null, null))); StatefulSetOperator mockZkSetOps = supplier.zkSetOperations; when(mockZkSetOps.getAsync(any(), any())).thenReturn(Future.succeededFuture(zkCluster.generateStatefulSet(false, null, null))); ArgumentCaptor<Function<Pod, List<String>>> zkNeedsRestartCaptor = ArgumentCaptor.forClass(Function.class); when(mockZkSetOps.maybeRollingUpdate(any(), any(), zkNeedsRestartCaptor.capture())).thenReturn(Future.succeededFuture()); PodOperator mockPodOps = supplier.podOperations; when(mockPodOps.listAsync(any(), eq(zkCluster.getSelectorLabels()))).thenAnswer(i -> { List<Pod> pods = new ArrayList<>(); pods.add(podWithName("my-cluster-zookeeper-0")); pods.add(podWithNameAndAnnotations("my-cluster-zookeeper-1", Collections.singletonMap(Annotations.ANNO_STRIMZI_IO_MANUAL_ROLLING_UPDATE, "true"))); pods.add(podWithNameAndAnnotations("my-cluster-zookeeper-2", Collections.singletonMap(Annotations.ANNO_STRIMZI_IO_MANUAL_ROLLING_UPDATE, "true"))); return Future.succeededFuture(pods); }); when(mockPodOps.listAsync(any(), eq(kafkaCluster.getSelectorLabels()))).thenAnswer(i -> { List<Pod> pods = new ArrayList<>(); pods.add(podWithNameAndAnnotations("my-cluster-kafka-0", Collections.singletonMap(Annotations.ANNO_STRIMZI_IO_MANUAL_ROLLING_UPDATE, "true"))); pods.add(podWithNameAndAnnotations("my-cluster-kafka-1", Collections.singletonMap(Annotations.ANNO_STRIMZI_IO_MANUAL_ROLLING_UPDATE, "true"))); pods.add(podWithName("my-cluster-kafka-2")); return Future.succeededFuture(pods); }); CrdOperator mockKafkaOps = supplier.kafkaOperator; when(mockKafkaOps.getAsync(eq(namespace), eq(clusterName))).thenReturn(Future.succeededFuture(kafka)); when(mockKafkaOps.get(eq(namespace), eq(clusterName))).thenReturn(kafka); when(mockKafkaOps.updateStatusAsync(any(), any())).thenReturn(Future.succeededFuture()); MockKafkaAssemblyOperator kao = new MockKafkaAssemblyOperator( vertx, new PlatformFeaturesAvailability(false, kubernetesVersion), certManager, passwordGenerator, supplier, config); Checkpoint async = context.checkpoint(); kao.reconcile(new Reconciliation("test-trigger", Kafka.RESOURCE_KIND, namespace, clusterName)) .onComplete(context.succeeding(v -> context.verify(() -> { // Verify Zookeeper rolling updates Mockito.verify(mockZkSetOps, times(1)).maybeRollingUpdate(any(), any(), any()); Function<Pod, List<String>> zkPodNeedsRestart = zkNeedsRestartCaptor.getValue(); assertThat(zkPodNeedsRestart.apply(podWithName("my-cluster-zookeeper-0")), is(nullValue())); assertThat(zkPodNeedsRestart.apply(podWithName("my-cluster-zookeeper-1")), is(Collections.singletonList("manual rolling update annotation on a pod"))); assertThat(zkPodNeedsRestart.apply(podWithName("my-cluster-zookeeper-2")), is(Collections.singletonList("manual rolling update annotation on a pod"))); // Verify Kafka rolling updates assertThat(kao.maybeRollKafkaInvocations, is(1)); assertThat(kao.kafkaPodNeedsRestart.apply(podWithName("my-cluster-kafka-0")), is(Collections.singletonList("manual rolling update annotation on a pod"))); assertThat(kao.kafkaPodNeedsRestart.apply(podWithName("my-cluster-kafka-1")), is(Collections.singletonList("manual rolling update annotation on a pod"))); assertThat(kao.kafkaPodNeedsRestart.apply(podWithName("my-cluster-kafka-2")), is(Collections.emptyList())); async.flag(); }))); } // Internal utility methods private Pod podWithName(String name) { return podWithNameAndAnnotations(name, Collections.emptyMap()); } private Pod podWithNameAndAnnotations(String name, Map<String, String> annotations) { return new PodBuilder() .withNewMetadata() .withName(name) .withAnnotations(annotations) .endMetadata() .build(); } class MockKafkaAssemblyOperator extends KafkaAssemblyOperator { int maybeRollKafkaInvocations = 0; Function<Pod, List<String>> kafkaPodNeedsRestart = null; public MockKafkaAssemblyOperator(Vertx vertx, PlatformFeaturesAvailability pfa, CertManager certManager, PasswordGenerator passwordGenerator, ResourceOperatorSupplier supplier, ClusterOperatorConfig config) { super(vertx, pfa, certManager, passwordGenerator, supplier, config); } ReconciliationState createReconciliationState(Reconciliation reconciliation, Kafka kafkaAssembly) { return new MockReconciliationState(reconciliation, kafkaAssembly); } @Override Future<Void> reconcile(ReconciliationState reconcileState) { return Future.succeededFuture(reconcileState) .compose(state -> state.getKafkaClusterDescription()) .compose(state -> state.getZookeeperDescription()) .compose(state -> state.zkManualRollingUpdate()) .compose(state -> state.kafkaManualRollingUpdate()) .mapEmpty(); } class MockReconciliationState extends KafkaAssemblyOperator.ReconciliationState { MockReconciliationState(Reconciliation reconciliation, Kafka kafkaAssembly) { super(reconciliation, kafkaAssembly); } Future<Void> maybeRollKafka(StatefulSet sts, Function<Pod, List<String>> podNeedsRestart) { maybeRollKafkaInvocations++; kafkaPodNeedsRestart = podNeedsRestart; return Future.succeededFuture(); } } } }
9,055
403
<filename>bots/misc/joinServer2.0.py # # joinServer2.0.py # @author Merubokkusu # @created Thu Feb 07 2019 15:20:35 GMT-0500 (Eastern Standard Time) # @copyright 2018 - 2019 # @license CC BY-NC-ND 3.0 US | https://creativecommons.org/licenses/by-nc-nd/3.0/us/ # @website https://github.com/Merubokkusu/discord-spam-bots/ # @email <EMAIL> # @last-modified Tue Mar 05 2019 02:14:17 GMT-0500 (Eastern Standard Time) # import requests import json import sys import os TOKEN = sys.argv[1] INVITE_LINK = sys.argv[2] PROXY = { 'http' : sys.argv[3] } url = 'https://discordapp.com/api/v6/invite/'+INVITE_LINK+'?with_counts=true' print(url) headers = {"content-type": "application/json", "Authorization": TOKEN } r = requests.post(url,headers=headers, proxies=PROXY) if r.status_code == 200: print("Token:"+"'"+TOKEN[-25]+"'"+" Joined the server") else: print('error, something went wrong.') print('Make sure your token is correct | https://discordhelp.net/discord-token') print(r.json())
416
854
__________________________________________________________________________________________________ class Logger { public: Logger() {} bool shouldPrintMessage(int timestamp, string message) { if (!m.count(message)) { m[message] = timestamp; return true; } if (timestamp - m[message] >= 10) { m[message] = timestamp; return true; } return false; } private: unordered_map<string, int> m; }; __________________________________________________________________________________________________ class Logger { public: Logger() {} bool shouldPrintMessage(int timestamp, string message) { if (timestamp < m[message]) return false; m[message] = timestamp + 10; return true; } private: unordered_map<string, int> m; }; __________________________________________________________________________________________________
322
1,444
package org.mage.test.cards.abilities.keywords; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; /** * @author LevelX2 */ public class DomainTest extends CardTestPlayerBase { /** * Collapsing Borders correctly does the 3 damage to each player at the * beginning of their upkeeps. However, it does NOT add any life for each * type of basic land the player has on the field. */ @Test public void testCollapsingBorders() { // Domain - At the beginning of each player's upkeep, that player gains 1 life for each basic land type among lands they control. // Then Collapsing Borders deals 3 damage to that player. addCard(Zone.HAND, playerA, "Collapsing Borders", 1); // {3}{R} addCard(Zone.BATTLEFIELD, playerA, "Mountain", 1); addCard(Zone.BATTLEFIELD, playerA, "Forest", 1); addCard(Zone.BATTLEFIELD, playerA, "Swamp", 1); addCard(Zone.BATTLEFIELD, playerA, "Island", 3); addCard(Zone.BATTLEFIELD, playerB, "Mountain", 3); castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Collapsing Borders"); setStopAt(3, PhaseStep.PRECOMBAT_MAIN); execute(); assertPermanentCount(playerA, "Collapsing Borders", 1); assertLife(playerA, 21); assertLife(playerB, 18); } }
524
790
""" Functions for working with "safe strings": strings that can be displayed safely without further escaping in HTML. Marking something as a "safe string" means that the producer of the string has already turned characters that should not be interpreted by the HTML engine (e.g. '<') into the appropriate entities. """ from django.utils.functional import curry, Promise class EscapeData(object): pass class EscapeString(str, EscapeData): """ A string that should be HTML-escaped when output. """ pass class EscapeUnicode(unicode, EscapeData): """ A unicode object that should be HTML-escaped when output. """ pass class SafeData(object): pass class SafeString(str, SafeData): """ A string subclass that has been specifically marked as "safe" (requires no further escaping) for HTML output purposes. """ def __add__(self, rhs): """ Concatenating a safe string with another safe string or safe unicode object is safe. Otherwise, the result is no longer safe. """ t = super(SafeString, self).__add__(rhs) if isinstance(rhs, SafeUnicode): return SafeUnicode(t) elif isinstance(rhs, SafeString): return SafeString(t) return t def _proxy_method(self, *args, **kwargs): """ Wrap a call to a normal unicode method up so that we return safe results. The method that is being wrapped is passed in the 'method' argument. """ method = kwargs.pop('method') data = method(self, *args, **kwargs) if isinstance(data, str): return SafeString(data) else: return SafeUnicode(data) decode = curry(_proxy_method, method = str.decode) class SafeUnicode(unicode, SafeData): """ A unicode subclass that has been specifically marked as "safe" for HTML output purposes. """ def __add__(self, rhs): """ Concatenating a safe unicode object with another safe string or safe unicode object is safe. Otherwise, the result is no longer safe. """ t = super(SafeUnicode, self).__add__(rhs) if isinstance(rhs, SafeData): return SafeUnicode(t) return t def _proxy_method(self, *args, **kwargs): """ Wrap a call to a normal unicode method up so that we return safe results. The method that is being wrapped is passed in the 'method' argument. """ method = kwargs.pop('method') data = method(self, *args, **kwargs) if isinstance(data, str): return SafeString(data) else: return SafeUnicode(data) encode = curry(_proxy_method, method = unicode.encode) def mark_safe(s): """ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string or unicode object is appropriate. Can be called multiple times on a single string. """ if isinstance(s, SafeData): return s if isinstance(s, str) or (isinstance(s, Promise) and s._delegate_str): return SafeString(s) if isinstance(s, (unicode, Promise)): return SafeUnicode(s) return SafeString(str(s)) def mark_for_escaping(s): """ Explicitly mark a string as requiring HTML escaping upon output. Has no effect on SafeData subclasses. Can be called multiple times on a single string (the resulting escaping is only applied once). """ if isinstance(s, (SafeData, EscapeData)): return s if isinstance(s, str) or (isinstance(s, Promise) and s._delegate_str): return EscapeString(s) if isinstance(s, (unicode, Promise)): return EscapeUnicode(s) return EscapeString(str(s)) # Forwards compatibility with Django 1.5 EscapeBytes = EscapeString EscapeText = EscapeUnicode SafeBytes = SafeString SafeText = SafeUnicode
1,501
3,175
<reponame>johnamcleod/agents<filename>tf_agents/bandits/environments/classification_environment.py # coding=utf-8 # Copyright 2020 The TF-Agents 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """An environment based on an arbitrary classification problem.""" from __future__ import absolute_import from __future__ import division # Using Type Annotations. from __future__ import print_function from typing import Optional, Text import gin import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import import tensorflow_probability as tfp from tf_agents.bandits.environments import bandit_tf_environment as bte from tf_agents.specs import tensor_spec from tf_agents.trajectories import time_step from tf_agents.typing import types from tf_agents.utils import eager_utils tfd = tfp.distributions def _batched_table_lookup(tbl, row, col): """Mapped 2D table lookup. Args: tbl: a `Tensor` of shape `[r, s, t]`. row: a `Tensor` of dtype `int32` with shape `[r]` and values in the range `[0, s - 1]`. col: a `Tensor` of dtype `int32` with shape `[r]` and values in the range `[0, t - 1]`. Returns: A `Tensor` `x` with shape `[r]` where `x[i] = tbl[i, row[i], col[i]`. """ assert_correct_shapes = tf.group( tf.assert_equal(tf.shape(row), tf.shape(col)), tf.assert_equal(tf.shape(row)[0], tf.shape(tbl)[0])) rng = tf.range(tf.shape(row)[0]) idx = tf.stack([rng, row, col], axis=-1) with tf.control_dependencies([assert_correct_shapes]): values = tf.gather_nd(tbl, idx) return values @gin.configurable class ClassificationBanditEnvironment(bte.BanditTFEnvironment): """An environment based on an arbitrary classification problem.""" def __init__(self, dataset: tf.data.Dataset, reward_distribution: types.Distribution, batch_size: types.Int, label_dtype_cast: Optional[tf.DType] = None, shuffle_buffer_size: Optional[types.Int] = None, repeat_dataset: Optional[bool] = True, prefetch_size: Optional[types.Int] = None, seed: Optional[types.Int] = None, name: Optional[Text] = 'classification'): """Initialize `ClassificationBanditEnvironment`. Args: dataset: a `tf.data.Dataset` consisting of two `Tensor`s, [inputs, labels] where inputs can be of any shape, while labels are integer class labels. The label tensor can be of any rank as long as it has 1 element. reward_distribution: a `tfd.Distribution` with event_shape `[num_classes, num_actions]`. Entry `[i, j]` is the reward for taking action `j` for an instance of class `i`. batch_size: if `dataset` is batched, this is the size of the batches. label_dtype_cast: if not None, casts dataset labels to this dtype. shuffle_buffer_size: If None, do not shuffle. Otherwise, a shuffle buffer of the specified size is used in the environment's `dataset`. repeat_dataset: Makes the environment iterate on the `dataset` once avoiding `OutOfRangeError: End of sequence` errors when the environment is stepped past the end of the `dataset`. prefetch_size: If None, do not prefetch. Otherwise, a prefetch buffer of the specified size is used in the environment's `dataset`. seed: Used to make results deterministic. name: The name of this environment instance. Raises: ValueError: if `reward_distribution` does not have an event shape with rank 2. """ # Computing `action_spec`. event_shape = reward_distribution.event_shape if len(event_shape) != 2: raise ValueError( 'reward_distribution must have event shape of rank 2; ' 'got event shape {}'.format(event_shape)) _, num_actions = event_shape action_spec = tensor_spec.BoundedTensorSpec(shape=(), dtype=tf.int32, minimum=0, maximum=num_actions - 1, name='action') output_shapes = tf.compat.v1.data.get_output_shapes(dataset) # Computing `time_step_spec`. if len(output_shapes) != 2: raise ValueError('Dataset must have exactly two outputs; got {}'.format( len(output_shapes))) context_shape = output_shapes[0] context_dtype, lbl_dtype = tf.compat.v1.data.get_output_types(dataset) if label_dtype_cast: lbl_dtype = label_dtype_cast observation_spec = tensor_spec.TensorSpec( shape=context_shape, dtype=context_dtype) time_step_spec = time_step.time_step_spec(observation_spec) super(ClassificationBanditEnvironment, self).__init__( action_spec=action_spec, time_step_spec=time_step_spec, batch_size=batch_size, name=name) if shuffle_buffer_size: dataset = dataset.shuffle(buffer_size=shuffle_buffer_size, seed=seed, reshuffle_each_iteration=True) if repeat_dataset: dataset = dataset.repeat() dataset = dataset.batch(batch_size, drop_remainder=True) if prefetch_size: dataset = dataset.prefetch(prefetch_size) self._data_iterator = eager_utils.dataset_iterator(dataset) self._current_label = tf.compat.v2.Variable( tf.zeros(batch_size, dtype=lbl_dtype)) self._previous_label = tf.compat.v2.Variable( tf.zeros(batch_size, dtype=lbl_dtype)) self._reward_distribution = reward_distribution self._label_dtype = lbl_dtype reward_means = self._reward_distribution.mean() self._optimal_action_table = tf.argmax( reward_means, axis=1, output_type=self._action_spec.dtype) self._optimal_reward_table = tf.reduce_max(reward_means, axis=1) def _observe(self) -> types.NestedTensor: context, lbl = eager_utils.get_next(self._data_iterator) self._previous_label.assign(self._current_label) self._current_label.assign(tf.reshape( tf.cast(lbl, dtype=self._label_dtype), shape=[self._batch_size])) return tf.reshape( context, shape=[self._batch_size] + self._time_step_spec.observation.shape) def _apply_action(self, action: types.NestedTensor) -> types.NestedTensor: action = tf.reshape( action, shape=[self._batch_size] + self._action_spec.shape) reward_samples = self._reward_distribution.sample(tf.shape(action)) return _batched_table_lookup(reward_samples, self._current_label, action) def compute_optimal_action(self) -> types.NestedTensor: return tf.gather( params=self._optimal_action_table, indices=self._previous_label) def compute_optimal_reward(self) -> types.NestedTensor: return tf.gather( params=self._optimal_reward_table, indices=self._previous_label)
2,977
2,780
/** * Copyright (c) 2018-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "DataBlockPosition.h" #include <sstream> #include <folly/compression/Compression.h> #include <folly/io/IOBuf.h> #include <folly/synchronization/CallOnce.h> #include "BucketStorage.h" #include "GorillaStatsManager.h" namespace facebook { namespace gorilla { namespace { constexpr union { uint32_t i; char c[4]; } dataBlockMagic = {.c = {'D', 'A', 'T', 'A'}}; // see // https://stackoverflow.com/questions/9050260/what-does-a-zlib-header-look-like constexpr size_t CMF = 0; constexpr size_t FLG = 1; static_assert( (static_cast<uint8_t>(dataBlockMagic.c[CMF]) * 256 + static_cast<uint8_t>(dataBlockMagic.c[FLG])) % 31 != 0, "new file format must not be misinterpreted as old zlib compressed data"); struct DataBlockHeader { explicit DataBlockHeader(DataBlockVersion versionArg) : magic_(dataBlockMagic.i), version_(static_cast<int32_t>(versionArg)) {} DataBlockHeader(const char* data, size_t len); bool valid() const; // @pre this->valid() const void* data() const; // @pre this->valid() size_t length() const; // @return whether the entire payload should be compressed // @pre this->valid() bool compress() const; private: uint32_t magic_; // Defer conversion until retrieval to preserve unknown values int32_t version_; }; const size_t kLargeFileBuffer = 1024 * 1024; // Byte size difference in compressed files const std::string kBucketCompressedDelta = "bucket_compressed_delta"; // Percent of original size const std::string kBucketCompressedPercent = "bucket_compressed_percent"; template <typename T> T fromUnaligned(const void* ptr) { T ret; memcpy(&ret, ptr, sizeof(ret)); return ret; } DataBlockHeader::DataBlockHeader(const char* data, size_t length) : magic_(), version_(static_cast<int32_t>(DataBlockVersion::V_UNKNOWN)) { if (length >= sizeof(*this)) { magic_ = fromUnaligned<uint32_t>(data); version_ = fromUnaligned<uint32_t>(data + sizeof(uint32_t)); } } bool DataBlockHeader::valid() const { return ( magic_ == dataBlockMagic.i && static_cast<int32_t>(DataBlockVersion::V_0) <= version_ && version_ < static_cast<int32_t>(DataBlockVersion::V_MAX)); } const void* DataBlockHeader::data() const { return this; } size_t DataBlockHeader::length() const { CHECK_GE(version_, static_cast<int32_t>(DataBlockVersion::V_0)); CHECK_LT(version_, static_cast<int32_t>(DataBlockVersion::V_MAX)); return ( version_ == static_cast<int32_t>(DataBlockVersion::V_0) ? 0 : sizeof(*this)); } bool DataBlockHeader::compress() const { CHECK_GE(version_, static_cast<int32_t>(DataBlockVersion::V_0)); CHECK_LT(version_, static_cast<int32_t>(DataBlockVersion::V_MAX)); return version_ == static_cast<int32_t>(DataBlockVersion::V_0); } } // namespace DataBlockPosition::DataBlockPosition( int64_t shardId, uint32_t position, DataBlockVersion writeVersion) : shardId_(shardId), position_(position), writeVersion_(writeVersion) { static folly::once_flag flag; folly::call_once(flag, [&]() { GorillaStatsManager::addStatExportType(kBucketCompressedDelta, SUM); GorillaStatsManager::addStatExportType(kBucketCompressedDelta, AVG); GorillaStatsManager::addStatExportType(kBucketCompressedPercent, AVG); }); } std::vector<std::unique_ptr<DataBlock>> DataBlockPosition::readBlocks( FileUtils& dataFiles, std::vector<uint32_t>& timeSeriesIds, std::vector<uint64_t>& storageIds) { std::vector<std::unique_ptr<DataBlock>> pointers; auto f = dataFiles.open(position_, "rb", 0); if (!f.file) { LOG(ERROR) << "Could not open block file for reading : " << position_; return pointers; } fseek(f.file, 0, SEEK_END); size_t len = ftell(f.file); if (len == 0) { LOG(WARNING) << "Empty data file " << f.name; fclose(f.file); return pointers; } fseek(f.file, 0, SEEK_SET); std::unique_ptr<char[]> buffer(new char[len]); int bytesRead = fread(buffer.get(), sizeof(char), len, f.file); if (bytesRead != len) { PLOG(ERROR) << "Could not read metadata from " << f.name; fclose(f.file); return pointers; } fclose(f.file); const DataBlockHeader header(buffer.get(), len); std::unique_ptr<folly::IOBuf> uncompressed; if (header.valid()) { uncompressed = folly::IOBuf::wrapBuffer(buffer.get(), len); } else { try { auto codec = folly::io::getCodec(folly::io::CodecType::ZLIB); auto ioBuffer = folly::IOBuf::wrapBuffer(buffer.get(), len); uncompressed = codec->uncompress(ioBuffer.get()); uncompressed->coalesce(); } catch (std::exception& e) { LOG(ERROR) << e.what(); return pointers; } } if (uncompressed->length() < sizeof(uint32_t) + sizeof(uint32_t)) { LOG(ERROR) << "Not enough data"; return pointers; } const char* const start = (const char*)uncompressed->data(); const char* ptr = start; uint32_t count; uint32_t activePages; uint32_t headerLength = header.valid() ? header.length() : 0; ptr += headerLength; memcpy(&count, ptr, sizeof(uint32_t)); ptr += sizeof(uint32_t); memcpy(&activePages, ptr, sizeof(uint32_t)); ptr += sizeof(uint32_t); size_t expectedLength = headerLength + sizeof(uint32_t) + sizeof(uint32_t) + count * sizeof(uint32_t) + count * sizeof(uint64_t) + activePages * BucketStorage::kPageSize; if (uncompressed->length() != expectedLength) { LOG(ERROR) << "Corrupt data file: expected " << expectedLength << " bytes, got " << uncompressed->length() << " bytes."; return pointers; } timeSeriesIds.resize(count); storageIds.resize(count); memcpy(timeSeriesIds.data(), ptr, count * sizeof(uint32_t)); ptr += count * sizeof(uint32_t); memcpy(storageIds.data(), ptr, count * sizeof(uint64_t)); ptr += count * sizeof(uint64_t); // Reorganize into individually allocated blocks because // BucketStorage doesn't know how to deal with a single pointer. for (int i = 0; i < activePages; i++) { pointers.emplace_back(new DataBlock); memcpy(pointers.back()->data, ptr, BucketStorage::kPageSize); ptr += BucketStorage::kPageSize; } return pointers; } void DataBlockPosition::write( FileUtils& dataFiles, FileUtils& completeFiles, const std::vector<std::shared_ptr<DataBlock>>& pages, uint32_t activePages, const std::vector<uint32_t>& timeSeriesIds, const std::vector<uint64_t>& storageIds) { CHECK_EQ(timeSeriesIds.size(), storageIds.size()); CHECK_GE( static_cast<int32_t>(writeVersion_), static_cast<int32_t>(DataBlockVersion::V_0)); CHECK_LT( static_cast<int32_t>(writeVersion_), static_cast<int32_t>(DataBlockVersion::V_MAX)); auto dataFile = dataFiles.open(position_, "wb", kLargeFileBuffer); if (!dataFile.file) { LOG(ERROR) << "Opening data block file:" << dataFile.name << " failed"; return; } const DataBlockHeader header(writeVersion_); uint32_t count = timeSeriesIds.size(); size_t dataLen = header.length() + sizeof(uint32_t) + // count sizeof(uint32_t) + // active pages count * sizeof(uint32_t) + // time series ids count * sizeof(uint64_t) + // storage ids activePages * kDataBlockSize; // blocks std::unique_ptr<char[]> buffer(new char[dataLen]); char* const start = buffer.get(); char* ptr = start; memcpy(ptr, header.data(), header.length()); ptr += header.length(); memcpy(ptr, &count, sizeof(uint32_t)); ptr += sizeof(uint32_t); memcpy(ptr, &activePages, sizeof(uint32_t)); ptr += sizeof(uint32_t); memcpy(ptr, timeSeriesIds.data(), sizeof(uint32_t) * count); ptr += sizeof(uint32_t) * count; memcpy(ptr, storageIds.data(), sizeof(uint64_t) * count); ptr += sizeof(uint64_t) * count; for (int i = 0; i < activePages; i++) { memcpy(ptr, pages[i]->data, kDataBlockSize); ptr += kDataBlockSize; } CHECK_EQ(ptr - buffer.get(), dataLen); try { auto ioBuffer = folly::IOBuf::wrapBuffer(buffer.get(), dataLen); if (header.compress()) { auto codec = folly::io::getCodec( folly::io::CodecType::ZLIB, folly::io::COMPRESSION_LEVEL_BEST); auto compressed = codec->compress(ioBuffer.get()); compressed->coalesce(); GorillaStatsManager::addStatValue( kBucketCompressedDelta, ioBuffer->length() - compressed->length()); GorillaStatsManager::addStatValue( kBucketCompressedDelta, compressed->length() * 100 / ioBuffer->length()); ioBuffer = std::move(compressed); } if (fwrite( ioBuffer->data(), sizeof(char), ioBuffer->length(), dataFile.file) != ioBuffer->length()) { PLOG(ERROR) << "Writing data block file " << dataFile.name << " failed"; FileUtils::closeFile(dataFile, false); return; } LOG(INFO) << "Wrote data block file " << dataFile.name << " dataLen:" << dataLen << " compressed:" << ioBuffer->length(); } catch (std::exception& e) { LOG(ERROR) << e.what(); FileUtils::closeFile(dataFile, false); return; } FileUtils::closeFile(dataFile, false); auto completeFile = completeFiles.open(position_, "wb", 0); if (!completeFile.file) { LOG(ERROR) << "Opening marker file " << completeFile.name << " failed"; return; } FileUtils::closeFile(completeFile, false); } } // namespace gorilla } // namespace facebook
3,664
446
<filename>body-tracking-samples/offline_processor/main.cpp // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include <iostream> #include <fstream> #include <string> #include <iomanip> #include <k4a/k4a.h> #include <k4arecord/playback.h> #include <k4abt.h> #include <nlohmann/json.hpp> #include <BodyTrackingHelpers.h> #include <Utilities.h> using namespace std; using namespace nlohmann; bool predict_joints(json &frames_json, int frame_count, k4abt_tracker_t tracker, k4a_capture_t capture_handle) { k4a_wait_result_t queue_capture_result = k4abt_tracker_enqueue_capture(tracker, capture_handle, K4A_WAIT_INFINITE); if (queue_capture_result != K4A_WAIT_RESULT_SUCCEEDED) { cerr << "Error! Adding capture to tracker process queue failed!" << endl; return false; } k4abt_frame_t body_frame = nullptr; k4a_wait_result_t pop_frame_result = k4abt_tracker_pop_result(tracker, &body_frame, K4A_WAIT_INFINITE); if (pop_frame_result != K4A_WAIT_RESULT_SUCCEEDED) { cerr << "Error! Popping body tracking result failed!" << endl; return false; } uint32_t num_bodies = k4abt_frame_get_num_bodies(body_frame); uint64_t timestamp = k4abt_frame_get_device_timestamp_usec(body_frame); json frame_result_json; frame_result_json["timestamp_usec"] = timestamp; frame_result_json["frame_id"] = frame_count; frame_result_json["num_bodies"] = num_bodies; frame_result_json["bodies"] = json::array(); for (uint32_t i = 0; i < num_bodies; i++) { k4abt_skeleton_t skeleton; VERIFY(k4abt_frame_get_body_skeleton(body_frame, i, &skeleton), "Get body from body frame failed!"); json body_result_json; int body_id = k4abt_frame_get_body_id(body_frame, i); body_result_json["body_id"] = body_id; for (int j = 0; j < (int)K4ABT_JOINT_COUNT; j++) { body_result_json["joint_positions"].push_back( { skeleton.joints[j].position.xyz.x, skeleton.joints[j].position.xyz.y, skeleton.joints[j].position.xyz.z }); body_result_json["joint_orientations"].push_back({ skeleton.joints[j].orientation.wxyz.w, skeleton.joints[j].orientation.wxyz.x, skeleton.joints[j].orientation.wxyz.y, skeleton.joints[j].orientation.wxyz.z }); } frame_result_json["bodies"].push_back(body_result_json); } frames_json.push_back(frame_result_json); k4abt_frame_release(body_frame); return true; } bool check_depth_image_exists(k4a_capture_t capture) { k4a_image_t depth = k4a_capture_get_depth_image(capture); if (depth != nullptr) { k4a_image_release(depth); return true; } else { return false; } } bool process_mkv_offline(const char* input_path, const char* output_path) { k4a_playback_t playback_handle = nullptr; k4a_result_t result = k4a_playback_open(input_path, &playback_handle); if (result != K4A_RESULT_SUCCEEDED) { cerr << "Cannot open recording at " << input_path << endl; return false; } k4a_calibration_t calibration; result = k4a_playback_get_calibration(playback_handle, &calibration); if (result != K4A_RESULT_SUCCEEDED) { cerr << "Failed to get calibration" << endl; return false; } k4abt_tracker_t tracker = NULL; k4abt_tracker_configuration_t tracker_config = K4ABT_TRACKER_CONFIG_DEFAULT; if (K4A_RESULT_SUCCEEDED != k4abt_tracker_create(&calibration, tracker_config, &tracker)) { cerr << "Body tracker initialization failed!" << endl; return false; } json json_output; json_output["k4abt_sdk_version"] = K4ABT_VERSION_STR; json_output["source_file"] = input_path; // Store all joint names to the json json_output["joint_names"] = json::array(); for (int i = 0; i < (int)K4ABT_JOINT_COUNT; i++) { json_output["joint_names"].push_back(g_jointNames.find((k4abt_joint_id_t)i)->second); } // Store all bone linkings to the json json_output["bone_list"] = json::array(); for (int i = 0; i < (int)g_boneList.size(); i++) { json_output["bone_list"].push_back({ g_jointNames.find(g_boneList[i].first)->second, g_jointNames.find(g_boneList[i].second)->second }); } cout << "Tracking " << input_path << endl; int frame_count = 0; json frames_json = json::array(); bool success = true; while (true) { k4a_capture_t capture_handle = nullptr; k4a_stream_result_t stream_result = k4a_playback_get_next_capture(playback_handle, &capture_handle); if (stream_result == K4A_STREAM_RESULT_EOF) { break; } cout << "frame " << frame_count << '\r'; if (stream_result == K4A_STREAM_RESULT_SUCCEEDED) { // Only try to predict joints when capture contains depth image if (check_depth_image_exists(capture_handle)) { success = predict_joints(frames_json, frame_count, tracker, capture_handle); k4a_capture_release(capture_handle); if (!success) { cerr << "Predict joints failed for clip at frame " << frame_count << endl; break; } } } else { success = false; cerr << "Stream error for clip at frame " << frame_count << endl; break; } frame_count++; } if (success) { json_output["frames"] = frames_json; cout << endl << "DONE " << endl; cout << "Total read " << frame_count << " frames" << endl; std::ofstream output_file(output_path); output_file << std::setw(4) << json_output << std::endl; cout << "Results saved in " << output_path; } k4a_playback_close(playback_handle); return success; } int main(int argc, char **argv) { if (argc != 3) { cout << "Usage: k4abt_offline_processor.exe <input_mkv_file> <output_json_file>" << endl; return -1; } return process_mkv_offline(argv[1], argv[2]) ? 0 : -1; }
3,199
528
""" Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. """ # Definition for a undirected graph node # class UndirectedGraphNode(object): # def __init__(self, x): # self.label = x # self.neighbors = [] class Solution(object): def cloneGraph(self, node): """ :type node: UndirectedGraphNode :rtype: UndirectedGraphNode BFS """ if node is None: return None queue = [] start_cloned_node = UndirectedGraphNode(node.label) visited = set() # A dictionary that maps labels to cloned nodes d = {node: start_cloned_node} queue.append(node) while queue: node = queue.pop(0) visited.add(node) cloned_node = d[node] cloned_neighbors = [] for neighbor in node.neighbors: if neighbor not in visited: queue.append(neighbor) if neighbor not in d: cloned_neighbor = UndirectedGraphNode(neighbor.label) d[neighbor] = cloned_neighbor else: cloned_neighbor = d[neighbor] cloned_neighbors.append(cloned_neighbor) cloned_node.neighbors = cloned_neighbors return start_cloned_node
686
309
// Copyright 2020 the deepx authors. // Author: <NAME> (<EMAIL>) // Author: <NAME> (<EMAIL>) // #pragma once #include <deepx_core/common/stream.h> #include <deepx_core/tensor/data_type.h> #include <string> #include <unordered_map> #include <unordered_set> namespace deepx_core { /************************************************************************/ /* PullRequest */ /************************************************************************/ struct PullRequest : DataType { public: // 1, train // 0, predict int is_train = 0; std::unordered_set<std::string> tsr_set; std::unordered_map<std::string, id_set_t> srm_map; id_freq_map_t id_freq_map; public: void clear() noexcept { is_train = 0; tsr_set.clear(); srm_map.clear(); id_freq_map.clear(); } bool empty() const noexcept { return tsr_set.empty() && srm_map.empty() && id_freq_map.empty(); } }; OutputStream& operator<<(OutputStream& os, const PullRequest& pull_request); InputStream& operator>>(InputStream& is, PullRequest& pull_request); } // namespace deepx_core
368
965
<filename>docs/atl/codesnippet/CPP/connection-point-global-functions_1.cpp LPUNKNOWN m_pSourceUnk; LPUNKNOWN m_pSinkUnk; DWORD m_dwCustCookie; // create source object HRESULT hr = CoCreateInstance (CLSID_MyComponent, NULL, CLSCTX_ALL, IID_IUnknown, (LPVOID*)&m_pSourceUnk); ATLASSERT(SUCCEEDED(hr)); // Create sink object. CMySink is a CComObjectRootEx-derived class // that implements the event interface methods. CComObject<CMySink>* pSinkClass; CComObject<CMySink>::CreateInstance(&pSinkClass); hr = pSinkClass->QueryInterface (IID_IUnknown, (LPVOID*)&m_pSinkUnk); ATLASSERT(SUCCEEDED(hr)); hr = AtlAdvise (m_pSourceUnk, m_pSinkUnk, __uuidof(_IMyComponentEvents), &m_dwCustCookie); ATLASSERT(SUCCEEDED(hr));
325
5,964
<filename>src/string-constants.h // Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_STRING_CONSTANTS_H_ #define V8_STRING_CONSTANTS_H_ #include "src/handles.h" #include "src/objects/string.h" #include "src/zone/zone.h" namespace v8 { namespace internal { enum class StringConstantKind { kStringLiteral, kNumberToStringConstant, kStringCons }; class StringConstantBase : public ZoneObject { public: explicit StringConstantBase(StringConstantKind kind) : kind_(kind) {} StringConstantKind kind() const { return kind_; } Handle<String> AllocateStringConstant(Isolate* isolate) const; size_t GetMaxStringConstantLength() const; bool operator==(const StringConstantBase& other) const; private: void Memoize(Handle<String> flattened) const { flattened_ = flattened; } StringConstantKind kind_; mutable Handle<String> flattened_ = Handle<String>::null(); }; size_t hash_value(StringConstantBase const& base); class StringLiteral final : public StringConstantBase { public: explicit StringLiteral(Handle<String> str, size_t length) : StringConstantBase(StringConstantKind::kStringLiteral), str_(str), length_(length) {} Handle<String> str() const { return str_; } size_t GetMaxStringConstantLength() const; private: Handle<String> str_; size_t length_; // We store this separately to avoid accessing the heap. }; bool operator==(StringLiteral const& lhs, StringLiteral const& rhs); bool operator!=(StringLiteral const& lhs, StringLiteral const& rhs); size_t hash_value(StringLiteral const& parameters); std::ostream& operator<<(std::ostream& os, StringLiteral const& parameters); class NumberToStringConstant final : public StringConstantBase { public: explicit NumberToStringConstant(double num) : StringConstantBase(StringConstantKind::kNumberToStringConstant), num_(num) {} double num() const { return num_; } size_t GetMaxStringConstantLength() const; private: double num_; }; bool operator==(NumberToStringConstant const& lhs, NumberToStringConstant const& rhs); bool operator!=(NumberToStringConstant const& lhs, NumberToStringConstant const& rhs); size_t hash_value(NumberToStringConstant const& parameters); std::ostream& operator<<(std::ostream& os, NumberToStringConstant const& parameters); class StringCons final : public StringConstantBase { public: explicit StringCons(const StringConstantBase* lhs, const StringConstantBase* rhs) : StringConstantBase(StringConstantKind::kStringCons), lhs_(lhs), rhs_(rhs) {} const StringConstantBase* lhs() const { return lhs_; } const StringConstantBase* rhs() const { return rhs_; } size_t GetMaxStringConstantLength() const; private: const StringConstantBase* lhs_; const StringConstantBase* rhs_; }; bool operator==(StringCons const& lhs, StringCons const& rhs); bool operator!=(StringCons const& lhs, StringCons const& rhs); size_t hash_value(StringCons const& parameters); std::ostream& operator<<(std::ostream& os, StringCons const& parameters); } // namespace internal } // namespace v8 #endif // V8_STRING_CONSTANTS_H_
1,136
399
<filename>src/main_MobViewer.cpp<gh_stars>100-1000 #include <memory> #include <BsFPSCamera.h> #include <Components/BsCCamera.h> #include <Scene/BsSceneObject.h> #include <BsZenLib/ImportSkeletalMesh.hpp> #include <core.hpp> #include <components/VisualInteractiveObject.hpp> #include <log/logging.hpp> #include <original-content/VirtualFileSystem.hpp> class REGothMobViewer : public REGoth::EmptyGame { public: using REGoth::EmptyGame::EmptyGame; void setupMainCamera() override { REGoth::Engine::setupMainCamera(); mFPSCamera = mMainCamera->SO()->addComponent<bs::FPSCamera>(); } void setupScene() override { using namespace REGoth; for (auto s : gVirtualFileSystem().listAllFiles()) { REGOTH_LOG(Info, Uncategorized, s); } bs::HSceneObject mobSO = bs::SceneObject::create("Mob"); HVisualInteractiveObject mobVis = mobSO->addComponent<VisualInteractiveObject>(); // auto mds = BsZenLib::ImportAndCacheMDS("CHESTBIG_OCCHESTMEDIUM.MDS", // gVirtualFileSystem().getFileIndex()); // for (auto s : mds->getMeshes()) // { // REGOTH_LOG(Info, Uncategorized, s->getName()); // } mobVis->setVisual("CHESTBIG_OCCHESTMEDIUM.MDS"); mMainCamera->SO()->setPosition(bs::Vector3(1, 0, 0)); mMainCamera->SO()->lookAt(bs::Vector3(0, 0, 0)); } protected: bs::HFPSCamera mFPSCamera; }; int main(int argc, char** argv) { auto config = REGoth::parseArguments<REGoth::EngineConfig>(argc, argv); REGothMobViewer engine{std::move(config)}; return REGoth::runEngine(engine); }
637
376
<reponame>BIGWangYuDong/mmfewshot # Copyright (c) OpenMMLab. All rights reserved. from .mse_loss import MSELoss from .nll_loss import NLLLoss __all__ = ['MSELoss', 'NLLLoss']
71
1,001
# 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. from aliyunsdkcore.request import RpcRequest from aliyunsdkecs.endpoint import endpoint_data class ModifyInstanceNetworkSpecRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Ecs', '2014-05-26', 'ModifyInstanceNetworkSpec','ecs') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_ResourceOwnerId(self): # Long return self.get_query_params().get('ResourceOwnerId') def set_ResourceOwnerId(self, ResourceOwnerId): # Long self.add_query_param('ResourceOwnerId', ResourceOwnerId) def get_ClientToken(self): # String return self.get_query_params().get('ClientToken') def set_ClientToken(self, ClientToken): # String self.add_query_param('ClientToken', ClientToken) def get_ISP(self): # String return self.get_query_params().get('ISP') def set_ISP(self, ISP): # String self.add_query_param('ISP', ISP) def get_InternetMaxBandwidthOut(self): # Integer return self.get_query_params().get('InternetMaxBandwidthOut') def set_InternetMaxBandwidthOut(self, InternetMaxBandwidthOut): # Integer self.add_query_param('InternetMaxBandwidthOut', InternetMaxBandwidthOut) def get_StartTime(self): # String return self.get_query_params().get('StartTime') def set_StartTime(self, StartTime): # String self.add_query_param('StartTime', StartTime) def get_AutoPay(self): # Boolean return self.get_query_params().get('AutoPay') def set_AutoPay(self, AutoPay): # Boolean self.add_query_param('AutoPay', AutoPay) def get_ResourceOwnerAccount(self): # String return self.get_query_params().get('ResourceOwnerAccount') def set_ResourceOwnerAccount(self, ResourceOwnerAccount): # String self.add_query_param('ResourceOwnerAccount', ResourceOwnerAccount) def get_OwnerAccount(self): # String return self.get_query_params().get('OwnerAccount') def set_OwnerAccount(self, OwnerAccount): # String self.add_query_param('OwnerAccount', OwnerAccount) def get_EndTime(self): # String return self.get_query_params().get('EndTime') def set_EndTime(self, EndTime): # String self.add_query_param('EndTime', EndTime) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId) def get_InstanceId(self): # String return self.get_query_params().get('InstanceId') def set_InstanceId(self, InstanceId): # String self.add_query_param('InstanceId', InstanceId) def get_NetworkChargeType(self): # String return self.get_query_params().get('NetworkChargeType') def set_NetworkChargeType(self, NetworkChargeType): # String self.add_query_param('NetworkChargeType', NetworkChargeType) def get_InternetMaxBandwidthIn(self): # Integer return self.get_query_params().get('InternetMaxBandwidthIn') def set_InternetMaxBandwidthIn(self, InternetMaxBandwidthIn): # Integer self.add_query_param('InternetMaxBandwidthIn', InternetMaxBandwidthIn) def get_AllocatePublicIp(self): # Boolean return self.get_query_params().get('AllocatePublicIp') def set_AllocatePublicIp(self, AllocatePublicIp): # Boolean self.add_query_param('AllocatePublicIp', AllocatePublicIp)
1,406
1,118
{"cym":{"common":"Angola","official":"Republic of Angola"},"deu":{"common":"Angola","official":"Republik Angola"},"fin":{"common":"Angola","official":"Angolan tasavalta"},"fra":{"common":"Angola","official":"République d'Angola"},"hrv":{"common":"Angola","official":"Republika Angola"},"ita":{"common":"Angola","official":"Repubblica dell'Angola"},"jpn":{"common":"アンゴラ","official":"アンゴラ共和国"},"nld":{"common":"Angola","official":"Republiek Angola"},"por":{"common":"Angola","official":"República de Angola"},"rus":{"common":"Ангола","official":"Республика Ангола"},"spa":{"common":"Angola","official":"República de Angola"}}
215
1,199
""" A collection of "worlds" suitable by solution by a CSP. Each world has a make_XXX_SCP function that creates a new CSP object, and some auxiliary utilities. """ import re, math from collections import defaultdict from types import StringTypes from csplib import CSP #---------------------------------------------------------------- # # Map coloring # def unequal_vals_constraint(A, a, B, b): """ A simple constraint: two neighbors must always have different values. """ return a != b def make_map_coloring_CSP(colors, neighbors): if isinstance(neighbors, StringTypes): neighbors = parse_neighbors_graph(neighbors) return CSP( vars=neighbors.keys(), domains=defaultdict(lambda: colors), neighbors=neighbors, binary_constraint=unequal_vals_constraint) def parse_neighbors_graph(neighbors, vars=[]): """ A utility for converting a string of the form 'X: Y Z; Y: Z' into a dict mapping variables to their neighbors. The syntax is a vertex name followed by a ':' followed by zero or more vertex names, followed by ';', repeated for each vertes. Neighborhood is commutative. 'vars' may contain vertices that have no neighbors. """ graph = defaultdict(list) for var in vars: graph[var] = [] specs = [spec.split(':') for spec in neighbors.split(';')] for (v, v_neighbors) in specs: v = v.strip() graph.setdefault(v, []) for u in v_neighbors.split(): graph[v].append(u) graph[u].append(v) return graph def make_australia_CSP(): # # WA---NT---Q # \ | / \ # \ | / \ # \ |/ \ # SA------NSW # \ / # \ / # \ / # V # # # T # return make_map_coloring_CSP( list('RGB'), 'SA: WA NT Q NSW V; NT: WA Q; NSW: Q V; T: ') def make_USA_CSP(): return make_map_coloring_CSP(list('RGBY'), """WA: OR ID; OR: ID NV CA; CA: NV AZ; NV: ID UT AZ; ID: MT WY UT; UT: WY CO AZ; MT: ND SD WY; WY: SD NE CO; CO: NE KA OK NM; NM: OK TX; ND: MN SD; SD: MN IA NE; NE: IA MO KA; KA: MO OK; OK: MO AR TX; TX: AR LA; MN: WI IA; IA: WI IL MO; MO: IL KY TN AR; AR: MS TN LA; LA: MS; WI: MI IL; IL: IN; IN: KY; MS: TN AL; AL: TN GA FL; MI: OH; OH: PA WV KY; KY: WV VA TN; TN: VA NC GA; GA: NC SC FL; PA: NY NJ DE MD WV; WV: MD VA; VA: MD DC NC; NC: SC; NY: VT MA CT NJ; NJ: DE; DE: MD; MD: DC; VT: NH MA; MA: NH RI CT; CT: RI; ME: NH; HI: ; AK: """) #---------------------------------------------------------------- # # N-Queens # # (var, val) is (column, row) # The domain is 0..N-1 # def queens_constraint(A, a, B, b): """ Constraint is satisfied if it's the same column (queens are assigned by columns), or if the queens are not in the same row or diagonal """ if A == B: return True return a != b and A + a != B + b and A - a != B - b class NQueensCSP(CSP): def to_str(self, assignment): s = '' for row in self.domains: for col in self.vars: if assignment[col] == row: s += '*' else: s += 'o' s += '\n' return s def make_NQueens_CSP(n): """ Creates a N-Queens CSP problem for a given N. Note that this isn't a particularly efficient representation. """ # columns vars = list(range(n)) # rows domains = list(range(n)) neighbors = {} for v in vars: neighbors[v] = vars[:] neighbors[v].remove(v) return NQueensCSP( vars=vars, domains=defaultdict(lambda: domains), neighbors=neighbors, binary_constraint=queens_constraint) #---------------------------------------------------------------- # # Sudoku # # Vars are (row, col) pairs. # Values are 1..9 # class SudokuCSP(CSP): def to_str(self, assignment): s = '' for row in range(9): if row % 3 == 0: s += '+-------+-------+-------+\n' s += '| ' for col in range(9): if (row, col) in assignment: s += str(assignment[(row, col)]) else: s += '_' if col % 3 == 2: s += ' | ' else: s += ' ' s += '\n' s += '+-------+-------+-------+\n' return s def cross(A, B): return [(a, b) for a in A for b in B] def parse_sudoku_assignment(grid): """ Given a string of 81 digits, return the assignment it represents. 0 means unassigned. Whitespace is ignored. """ digits = re.sub('\s', '', grid) assert len(digits) == 81 digit = iter(digits) asg = {} for row in range(9): for col in range(9): d = int(digit.next()) if d > 0: asg[(row, col)] = d return asg def make_sudoku_CSP(): """ A regular 9x9 Sudoku puzzle. Note that it's an 'empty' Sudoku board. Solving partially filled boards is done by passing an initial assignment (obtained with parse_sudoku_assignment) to the solve_search method of the CSP. """ # All (row, col) cells rows = range(9) cols = range(9) vars = cross(rows, cols) # Available values domains = defaultdict(lambda: range(1, 10)) triples = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] unitlist = ([cross(rows, [c]) for c in cols] + [cross([r], cols) for r in rows] + [cross(rs, cs) for rs in triples for cs in triples]) # Neighbors holds sets, but that's fine for CSP - it just # wants 'em to be iterable # neighbors = defaultdict(lambda: set([])) for unit in unitlist: for cell in unit: neighbors[cell].update(unit) neighbors[cell].remove(cell) return SudokuCSP( vars=vars, domains=domains, neighbors=neighbors, binary_constraint=unequal_vals_constraint) #---------------------------------------------------------------- # # Magic squares # class MagicSquareCSP(CSP): def to_str(self, assignment): s = '' ns = range(int(math.sqrt(len(self.vars)))) for row in ns: for col in ns: if (row, col) in assignment: s += str(assignment[(row, col)]) else: s += '_' s += ' ' s += '\n' return s def make_magic_square_CSP(n): """ A NxN additive magic square A sample solution for 3x3: 2 7 6 9 5 1 4 3 8 (row, column and diagonal sum = 15) """ rows = range(n) cols = range(n) vars = cross(rows, cols) domains = defaultdict(lambda: range(1, n*n + 1)) magic_sum = n * (n*n + 1) / 2 # All cells are different --> neighbors of one another. # neighbors = {} for v in vars: neighbors[v] = vars[:] neighbors[v].remove(v) def check_sum(values): s = sum(values) if s > magic_sum: return False return not (len(values) == n and s != magic_sum) def sum_constraint(new_asgn, cur_asgn): square = {} square.update(new_asgn) square.update(cur_asgn) # Only new assignments can cause conflicts... # for (vrow, vcol) in new_asgn.iterkeys(): #~ if check_sum([square.get((vrow, col), 0) for col in cols]) == False: if check_sum([square[(vrow, col)] for col in cols if (vrow, col) in square]) == False: return False #~ if check_sum([square.get((row, vcol), 0) for row in rows]) == False: if check_sum([square[(row, vcol)] for row in rows if (row, vcol) in square]) == False: return False # \ diagonal if ( vrow == vcol and check_sum([square[(row, row)] for row in rows if (row, row) in square]) == False): return False # / diagonal if ( vrow == n - 1 - vcol and check_sum([square[(n - 1 - row, row)] for row in rows if (n - 1 - row, row) in square]) == False): return False return True return MagicSquareCSP( vars=vars, domains=domains, neighbors=neighbors, binary_constraint=unequal_vals_constraint, global_constraint=sum_constraint) #---------------------------------------------------------------- # # Magic gons (Project Euler problem 68) # class Magic3gonCSP(CSP): def to_str(self, assignment): asgn = defaultdict(lambda: '*') asgn.update(assignment) s = '' s += ' %s\n' % asgn[2] s += '\n' s += ' %s\n' % asgn[4] s += '\n' s += ' %s %s %s\n' % (asgn[3], asgn[5], asgn[6]) s += '\n' s += '%s\n' % asgn[1] return s def make_magic_3gon_CSP(): vars = range(1, 7) domains = defaultdict(lambda: vars) # All cells are different --> neighbors of one another. # neighbors = {} for v in vars: neighbors[v] = vars[:] neighbors[v].remove(v) groups = [[1, 3, 4], [2, 4, 5], [6, 5, 3]] def sum_constraint(new_asgn, cur_asgn): asgn = defaultdict(lambda: 999) asgn.update(new_asgn) asgn.update(cur_asgn) last_total = None for group in groups: total = sum(asgn[i] for i in group) if total < 1000: if last_total is None: last_total = total elif last_total != total: return False return True return Magic3gonCSP( vars=vars, domains=domains, neighbors=neighbors, binary_constraint=unequal_vals_constraint, global_constraint=sum_constraint) class Magic5gonCSP(CSP): def to_str(self, assignment): asgn = defaultdict(lambda: '*') asgn.update(assignment) s = '' s += ' %s %s\n' % (asgn[2], asgn[9]) s += ' %s\n' % asgn[5] s += ' %s %s\n' % (asgn[3], asgn[8]) s += '%s\n' % (asgn[1]) s += ' %s %s %s\n' % (asgn[4], asgn[7], asgn[10]) s += '\n' s += ' %s\n' % asgn[6] return s def make_magic_5gon_CSP(): vars = range(1, 11) domains = defaultdict(lambda: vars) # All cells are different --> neighbors of one another. # neighbors = {} for v in vars: neighbors[v] = vars[:] neighbors[v].remove(v) groups = [[1, 3, 5], [2, 5, 8], [9, 8, 7], [10, 7, 4], [6, 4, 3]] def sum_constraint(new_asgn, cur_asgn): asgn = defaultdict(lambda: 999) asgn.update(new_asgn) asgn.update(cur_asgn) last_total = None for group in groups: total = sum(asgn[i] for i in group) if total < 1000: if last_total is None: last_total = total elif last_total != total: return False return True return Magic5gonCSP( vars=vars, domains=domains, neighbors=neighbors, binary_constraint=unequal_vals_constraint, global_constraint=sum_constraint)
6,539
647
/* * 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. */ /** * Standalone, feature-complete implementation of the <a href="https://raft.github.io/">Raft consensus algorithm</a>. * <p> * For information on the implementation of the Raft consensus algorithm, see the documentation on * <a href="http://atomix.io/copycat/docs/internals/">Copycat internals</a>. * * @author <a href="http://github.com/kuujo"><NAME></a> */ package io.atomix.copycat.server;
276
1,362
<reponame>FriedDede/rpi4-osdev #include "io.h" #include "bt.h" #include "fb.h" #define MAX_MSG_LEN 50 #define MAX_READ_RUN 100 unsigned char data_buf[MAX_MSG_LEN]; unsigned int data_len; unsigned int messages_received = 0; unsigned int poll_state = 0; enum { LE_EVENT_CODE = 0x3e, LE_CONNECT_CODE = 0x01, LE_ADREPORT_CODE = 0x02, HCI_ACL_PKT = 0x02, HCI_EVENT_PKT = 0x04 }; unsigned int got_echo_sid = 0; unsigned int got_echo_name = 0; unsigned char echo_addr[6]; unsigned int connected = 0; unsigned int connection_handle = 0; unsigned char dir = 50; int memcmp(const char *str1, const char *str2, int count) { const char *s1 = (const char*)str1; const char *s2 = (const char*)str2; while (count-- > 0) { if (*s1++ != *s2++) return s1[-1] < s2[-1] ? -1 : 1; } return 0; } void hci_poll2(unsigned char byte) { switch (poll_state) { case 0: if (byte != HCI_EVENT_PKT) poll_state = 0; else poll_state = 1; break; case 1: if (byte != LE_EVENT_CODE) poll_state = 0; else poll_state = 2; break; case 2: if (byte > MAX_MSG_LEN) poll_state = 0; else { poll_state = 3; data_len = byte; } break; default: data_buf[poll_state - 3] = byte; if (poll_state == data_len + 3 - 1) { messages_received++; poll_state = 0; } else poll_state++; } } unsigned char *hci_poll() { unsigned int goal = messages_received + 1; if (bt_isReadByteReady()) { unsigned int run = 0; while (run < MAX_READ_RUN && messages_received < goal && bt_isReadByteReady()) { unsigned char byte = bt_readByte(); hci_poll2(byte); run++; } if (run == MAX_READ_RUN) return 0; else return data_buf; } return 0; } void bt_search(void) { unsigned char *buf; while ( (buf = hci_poll()) ) { if (data_len >= 2) { if (buf[0] == LE_ADREPORT_CODE) { if (buf[1] == 1) { // num_reports if (buf[2] == 0) { // event_type int bufindex = 0; unsigned char ad_len = buf[11]; for (int c=9;c>=4;c--) echo_addr[9-c] = buf[bufindex + c]; // save the mac address bufindex += 11; got_echo_sid = 0; got_echo_name = 0; // Reset the search state machine do { ad_len = buf[bufindex]; unsigned char ad_type = buf[bufindex + 1]; bufindex += 2; if (ad_len >= 2) { if (ad_type == 0x03) { unsigned int sid = buf[bufindex] | (buf[bufindex + 1] << 8); if (sid == 0xEC00) { got_echo_sid = 1; debugstr("got sid... "); } } else if (ad_type == 0x09) { char remote_name[ad_len - 1]; unsigned int d=0; while (d<ad_len - 1) { remote_name[d] = buf[bufindex + d]; d++; } if (!memcmp(remote_name,"echo",4)) { got_echo_name = 1; debugstr("got name... "); } } } bufindex += ad_len - 1; } while (bufindex < data_len); } } } } } } void bt_conn() { unsigned char *buf; while ( (buf = hci_poll()) ) { if (!connected && data_len >= 2 && buf[0] == LE_CONNECT_CODE) { connected = !*(buf+1); debughex(connected); debugstr(" "); connection_handle = *(buf+2) | (*(buf+3) << 8); debughex(connection_handle); debugstr(" "); if (connection_handle == 0) wait_msec(0x186A); } } } // The screen #define WIDTH 1920 #define HEIGHT 1080 #define MARGIN 30 #define VIRTWIDTH (WIDTH-(2*MARGIN)) #define FONT_BPG 8 // For the bricks #define ROWS 5 #define COLS 10 // Gameplay #define NUM_LIVES 3 // OBJECT TRACKING struct Object { unsigned int type; unsigned int x; unsigned int y; unsigned int width; unsigned int height; unsigned char alive; }; enum { OBJ_NONE = 0, OBJ_BRICK = 1, OBJ_PADDLE = 2, OBJ_BALL = 3 }; unsigned int numobjs = 0; struct Object *objects = (struct Object *)SAFE_ADDRESS; struct Object *ball; struct Object *paddle; const int paddlewidth = 80; const int ballradius = 15; void removeObject(struct Object *object) { if (object->type == OBJ_BALL) { drawCircle(object->x + ballradius, object->y + ballradius, ballradius, 0, 1); } else { drawRect(object->x, object->y, object->x + object->width, object->y + object->height, 0, 1); } object->alive = 0; } void moveObjectAbs(struct Object *object, int x, int y) { if (object->type == OBJ_BALL) { drawCircle(object->x + ballradius, object->y + ballradius, ballradius, 0, 1); drawCircle(x + ballradius, y + ballradius, ballradius, 0x55, 1); } else { moveRectAbs(object->x, object->y, object->width, object->height, x, y, 0x00); } object->x = x; object->y = y; } struct Object *detectCollision(struct Object *with, int xoff, int yoff) { for (int i=0; i<numobjs;i++) { if (&objects[i] != with && objects[i].alive == 1) { if (with->x + xoff > objects[i].x + objects[i].width || objects[i].x > with->x + xoff + with->width) { // with is too far left or right to collide } else if (with->y + yoff > objects[i].y + objects[i].height || objects[i].y > with->y + yoff + with->height) { // with is too far up or down to collide } else { // Collision! return &objects[i]; } } } return 0; } // OBJECT INITIALISERS void initBricks() { int brickwidth = 32; int brickheight = 8; int brickspacer = 20; const int brickcols[] = { 0x11, 0x22, 0xEE, 0x44, 0x66 }; int ybrick = MARGIN + brickheight; for (int i=0; i<ROWS; i++) { int xbrick = MARGIN + (VIRTWIDTH/COLS/2) - (brickwidth/2); for (int j = 0; j<COLS; j++) { drawRect(xbrick, ybrick, xbrick+brickwidth, ybrick+brickheight, brickcols[i], 1); objects[numobjs].type = OBJ_BRICK; objects[numobjs].x = xbrick; objects[numobjs].y = ybrick; objects[numobjs].width = brickwidth; objects[numobjs].height = brickheight; objects[numobjs].alive = 1; numobjs++; xbrick += (VIRTWIDTH/COLS); } ybrick = ybrick + brickspacer; } } void initBall() { drawCircle(WIDTH/2, HEIGHT/2, ballradius, 0x55, 1); objects[numobjs].type = OBJ_BALL; objects[numobjs].x = (WIDTH/2) - ballradius; objects[numobjs].y = (HEIGHT/2) - ballradius; objects[numobjs].width = ballradius * 2; objects[numobjs].height = ballradius * 2; objects[numobjs].alive = 1; ball = &objects[numobjs]; numobjs++; } void initPaddle() { int paddleheight = 20; int startx = MARGIN + (dir * ((VIRTWIDTH - paddlewidth + MARGIN)/100)); drawRect(startx, (HEIGHT-MARGIN-paddleheight), startx + paddlewidth, (HEIGHT-MARGIN), 0x11, 1); objects[numobjs].type = OBJ_PADDLE; objects[numobjs].x = startx; objects[numobjs].y = (HEIGHT-MARGIN-paddleheight); objects[numobjs].width = paddlewidth; objects[numobjs].height = paddleheight; objects[numobjs].alive = 1; paddle = &objects[numobjs]; numobjs++; } void drawScoreboard(int score, int lives) { char tens = score / 10; score -= (10 * tens); char ones = score; drawString((WIDTH/2)-252, MARGIN-25, "Score: 0 Lives: ", 0x0f, 3); drawChar(tens + 0x30, (WIDTH/2)-252 + (8*8*3), MARGIN-25, 0x0f, 3); drawChar(ones + 0x30, (WIDTH/2)-252 + (8*9*3), MARGIN-25, 0x0f, 3); drawChar((char)lives + 0x30, (WIDTH/2)-252 + (8*20*3), MARGIN-25, 0x0f, 3); } void acl_poll() { while (bt_isReadByteReady()) { unsigned char byte = bt_readByte(); if (byte == HCI_EVENT_PKT) { bt_readByte(); // opcode unsigned char length = bt_readByte(); for (int i=0;i<length;i++) bt_readByte(); } else if (byte == HCI_ACL_PKT) { unsigned char h1 = bt_readByte(); // handle1 unsigned char h2 = bt_readByte(); // handle2 unsigned char thandle = h1 | (h2 << 8); unsigned char d1 = bt_readByte(); unsigned char d2 = bt_readByte(); unsigned int dlen = d1 | (d2 << 8); unsigned char data[dlen]; if (dlen > 7) { for (int i=0;i<dlen;i++) data[i] = bt_readByte(); unsigned int length = data[0] | (data[1] << 8); unsigned int channel = data[2] | (data[3] << 8); unsigned char opcode = data[4]; if (thandle == connection_handle && length == 4 && opcode == 0x1b) { if (channel == 4 && data[5] == 0x2a && data[6] == 0x00) { dir = data[7]; moveObjectAbs(paddle, MARGIN + (dir * ((VIRTWIDTH - paddlewidth + MARGIN)/100)), paddle->y); } } } } } } void breakout() { struct Object *foundObject; int bricks = ROWS * COLS; int lives = NUM_LIVES; int points = 0; int velocity_x = 1; int velocity_y = 3; initBricks(); initBall(); initPaddle(); drawScoreboard(points, lives); while (lives > 0 && bricks > 0) { acl_poll(); // Are we going to hit anything? foundObject = detectCollision(ball, velocity_x, velocity_y); if (foundObject) { if (foundObject == paddle) { velocity_y = -velocity_y; // Are we going to hit the side of the paddle if (ball->x + ball->width + velocity_x == paddle->x || ball->x + velocity_x == paddle->x + paddle->width) velocity_x = -velocity_x; } else if (foundObject->type == OBJ_BRICK) { removeObject(foundObject); velocity_y = -velocity_y; bricks--; points++; drawScoreboard(points, lives); } } wait_msec(0x186A); moveObjectAbs(ball, ball->x + velocity_x, ball->y + velocity_y); // Check we're in the game arena still if (ball->x + ball->width >= WIDTH-MARGIN) { velocity_x = -velocity_x; } else if (ball->x <= MARGIN) { velocity_x = -velocity_x; } else if (ball->y + ball->height >= HEIGHT-MARGIN) { lives--; removeObject(ball); removeObject(paddle); drawScoreboard(points, lives); if (lives) { initBall(); initPaddle(); } } else if (ball->y <= MARGIN) { velocity_y = -velocity_y; } } int zoom = WIDTH/192; int strwidth = 10 * FONT_BPG * zoom; int strheight = FONT_BPG * zoom; if (bricks == 0) drawString((WIDTH/2)-(strwidth/2), (HEIGHT/2)-(strheight/2), "Well done!", 0x02, zoom); else drawString((WIDTH/2)-(strwidth/2), (HEIGHT/2)-(strheight/2), "Game over!", 0x04, zoom); wait_msec(0x500000); // Wait 5 seconds drawRect((WIDTH/2)-(strwidth/2), (HEIGHT/2)-(strheight/2), (WIDTH/2)+(strwidth/2), (HEIGHT/2)+(strheight/2), 0, 1); numobjs = 0; } void main() { fb_init(); uart_init(); bt_init(); debugstr("Initialising Bluetooth: "); debugstr(">> reset: "); bt_reset(); debugstr(">> firmware load: "); bt_loadfirmware(); debugstr(">> set baud: "); bt_setbaud(); debugstr(">> set bdaddr: "); bt_setbdaddr(); // Print the BD_ADDR unsigned char local_addr[6]; bt_getbdaddr(local_addr); for (int c=5;c>=0;c--) debugch(local_addr[c]); debugcrlf(); // Start scanning debugstr("Setting event mask... "); setLEeventmask(0xff); debugstr("Starting scanning... "); startActiveScanning(); // Search for the echo debugstr("Waiting..."); debugcrlf(); while (!(got_echo_sid && got_echo_name)) bt_search(); stopScanning(); for (int c=0;c<=5;c++) debugch(echo_addr[c]); debugcrlf(); // Connecting to echo debugstr("Connecting to echo: "); connect(echo_addr); while (!(connected && connection_handle)) bt_conn(); debugstr("Connected!"); debugcrlf(); // Subscribe to updates debugstr("Sending read request: "); debughex(connection_handle); debugcrlf(); sendACLsubscribe(connection_handle); // Begin the game debugstr("Let the game commence...\n"); wait_msec(0x100000); // Wait a second while (1) breakout(); }
5,952
6,139
<reponame>uOOOO/mosby /* * Copyright 2016 <NAME>. * * 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.hannesdorfmann.mosby3.sample.mvi; import android.app.Application; import android.content.Context; import com.hannesdorfmann.mosby3.sample.mvi.dependencyinjection.DependencyInjection; import com.squareup.leakcanary.LeakCanary; import com.squareup.leakcanary.RefWatcher; import timber.log.Timber; /** * A custom Application class mainly used to provide dependency injection * * @author <NAME> */ public class SampleApplication extends Application { protected DependencyInjection dependencyInjection = new DependencyInjection(); { Timber.plant(new Timber.DebugTree()); } public static DependencyInjection getDependencyInjection(Context context) { return ((SampleApplication) context.getApplicationContext()).dependencyInjection; } public static RefWatcher getRefWatcher(Context context) { SampleApplication application = (SampleApplication) context.getApplicationContext(); return application.refWatcher; } private RefWatcher refWatcher; @Override public void onCreate() { super.onCreate(); if (LeakCanary.isInAnalyzerProcess(this)) { // This process is dedicated to LeakCanary for heap analysis. // You should not init your app in this process. return; } refWatcher = LeakCanary.install(this); Timber.d("Starting Application"); } }
568
3,710
#pragma once #include "pool.h"
15
460
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (<EMAIL>) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QFONTENGINE_P_H #define QFONTENGINE_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include "QtCore/qglobal.h" #include "QtCore/qatomic.h" #include <QtCore/qvarlengtharray.h> #include <QtCore/QLinkedList> #include "private/qtextengine_p.h" #include "private/qfont_p.h" #ifdef Q_WS_WIN # include "QtCore/qt_windows.h" #endif #ifdef Q_WS_MAC # include "private/qt_mac_p.h" # include "QtCore/qmap.h" # include "QtCore/qcache.h" # include "private/qcore_mac_p.h" #endif #include <private/qfontengineglyphcache_p.h> struct glyph_metrics_t; typedef unsigned int glyph_t; QT_BEGIN_NAMESPACE class QChar; class QPainterPath; class QTextEngine; struct QGlyphLayout; #define MAKE_TAG(ch1, ch2, ch3, ch4) (\ (((quint32)(ch1)) << 24) | \ (((quint32)(ch2)) << 16) | \ (((quint32)(ch3)) << 8) | \ ((quint32)(ch4)) \ ) class Q_GUI_EXPORT QFontEngine : public QObject { public: enum Type { Box, Multi, // X11 types XLFD, // MS Windows types Win, // Apple Mac OS types Mac, // QWS types Freetype, QPF1, QPF2, Proxy, // S60 types S60FontEngine, // Cannot be simply called "S60". Reason is qt_s60Data.h TestFontEngine = 0x1000 }; QFontEngine(); virtual ~QFontEngine(); // all of these are in unscaled metrics if the engine supports uncsaled metrics, // otherwise in design metrics struct Properties { QByteArray postscriptName; QByteArray copyright; QRectF boundingBox; QFixed emSquare; QFixed ascent; QFixed descent; QFixed leading; QFixed italicAngle; QFixed capHeight; QFixed lineWidth; }; virtual Properties properties() const; virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics); QByteArray getSfntTable(uint /*tag*/) const; virtual bool getSfntTableData(uint /*tag*/, uchar * /*buffer*/, uint * /*length*/) const { return false; } struct FaceId { FaceId() : index(0), encoding(0) {} QByteArray filename; int index; int encoding; }; virtual FaceId faceId() const { return FaceId(); } enum SynthesizedFlags { SynthesizedItalic = 0x1, SynthesizedBold = 0x2, SynthesizedStretch = 0x4 }; virtual int synthesized() const { return 0; } virtual QFixed emSquareSize() const { return ascent(); } /* returns 0 as glyph index for non existent glyphs */ virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const = 0; /** * This is a callback from harfbuzz. The font engine uses the font-system in use to find out the * advances of each glyph and set it on the layout. */ virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const {} virtual void doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const; #if !defined(Q_WS_X11) && !defined(Q_WS_WIN) && !defined(Q_WS_MAC) && !defined(Q_OS_SYMBIAN) virtual void draw(QPaintEngine *p, qreal x, qreal y, const QTextItemInt &si) = 0; #endif virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs, QPainterPath *path, QTextItem::RenderFlags flags); void getGlyphPositions(const QGlyphLayout &glyphs, const QTransform &matrix, QTextItem::RenderFlags flags, QVarLengthArray<glyph_t> &glyphs_out, QVarLengthArray<QFixedPoint> &positions); virtual void addOutlineToPath(qreal, qreal, const QGlyphLayout &, QPainterPath *, QTextItem::RenderFlags flags); void addBitmapFontToPath(qreal x, qreal y, const QGlyphLayout &, QPainterPath *, QTextItem::RenderFlags); /** * Create a qimage with the alpha values for the glyph. * Returns an image indexed_8 with index values ranging from 0=fully transparent to 255=opaque */ virtual QImage alphaMapForGlyph(glyph_t); virtual QImage alphaMapForGlyph(glyph_t, const QTransform &t); virtual QImage alphaRGBMapForGlyph(glyph_t, int margin, const QTransform &t); virtual void removeGlyphFromCache(glyph_t); virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs) = 0; virtual glyph_metrics_t boundingBox(glyph_t glyph) = 0; virtual glyph_metrics_t boundingBox(glyph_t glyph, const QTransform &matrix); glyph_metrics_t tightBoundingBox(const QGlyphLayout &glyphs); virtual QFixed ascent() const = 0; virtual QFixed descent() const = 0; virtual QFixed leading() const = 0; virtual QFixed xHeight() const; virtual QFixed averageCharWidth() const; virtual QFixed lineThickness() const; virtual QFixed underlinePosition() const; virtual qreal maxCharWidth() const = 0; virtual qreal minLeftBearing() const { return qreal(); } virtual qreal minRightBearing() const { return qreal(); } virtual void getGlyphBearings(glyph_t glyph, qreal *leftBearing = 0, qreal *rightBearing = 0); virtual const char *name() const = 0; virtual bool canRender(const QChar *string, int len) = 0; virtual Type type() const = 0; virtual int glyphCount() const; HB_Font harfbuzzFont() const; HB_Face harfbuzzFace() const; virtual HB_Error getPointInOutline(HB_Glyph glyph, int flags, hb_uint32 point, HB_Fixed *xpos, HB_Fixed *ypos, hb_uint32 *nPoints); void setGlyphCache(void *key, QFontEngineGlyphCache *data); QFontEngineGlyphCache *glyphCache(void *key, QFontEngineGlyphCache::Type type, const QTransform &transform) const; static const uchar *getCMap(const uchar *table, uint tableSize, bool *isSymbolFont, int *cmapSize); static quint32 getTrueTypeGlyphIndex(const uchar *cmap, uint unicode); static QByteArray convertToPostscriptFontFamilyName(const QByteArray &fontFamily); QAtomicInt ref; QFontDef fontDef; uint cache_cost; // amount of mem used in kb by the font int cache_count; uint fsType : 16; bool symbol; mutable HB_FontRec hbFont; mutable HB_Face hbFace; #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN) struct KernPair { uint left_right; QFixed adjust; inline bool operator<(const KernPair &other) const { return left_right < other.left_right; } }; QVector<KernPair> kerning_pairs; void loadKerningPairs(QFixed scalingFactor); #endif int glyphFormat; protected: static const QVector<QRgb> &grayPalette(); QFixed lastRightBearing(const QGlyphLayout &glyphs, bool round = false); private: struct GlyphCacheEntry { void *context; QFontEngineGlyphCache *cache; bool operator==(const GlyphCacheEntry &other) { return context == other.context && cache == other.cache; } }; mutable QLinkedList<GlyphCacheEntry> m_glyphCaches; }; inline bool operator ==(const QFontEngine::FaceId &f1, const QFontEngine::FaceId &f2) { return (f1.index == f2.index) && (f1.encoding == f2.encoding) && (f1.filename == f2.filename); } inline uint qHash(const QFontEngine::FaceId &f) { return qHash((f.index << 16) + f.encoding) + qHash(f.filename); } class QGlyph; #if defined(Q_WS_QWS) #ifndef QT_NO_QWS_QPF class QFontEngineQPF1Data; class QFontEngineQPF1 : public QFontEngine { public: QFontEngineQPF1(const QFontDef&, const QString &fn); ~QFontEngineQPF1(); virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const; virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const; virtual void draw(QPaintEngine *p, qreal x, qreal y, const QTextItemInt &si); virtual void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags); virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs); virtual glyph_metrics_t boundingBox(glyph_t glyph); virtual QFixed ascent() const; virtual QFixed descent() const; virtual QFixed leading() const; virtual qreal maxCharWidth() const; virtual qreal minLeftBearing() const; virtual qreal minRightBearing() const; virtual QFixed underlinePosition() const; virtual QFixed lineThickness() const; virtual Type type() const; virtual bool canRender(const QChar *string, int len); inline const char *name() const { return 0; } virtual QImage alphaMapForGlyph(glyph_t); QFontEngineQPF1Data *d; }; #endif // QT_NO_QWS_QPF #endif // QWS class QFontEngineBox : public QFontEngine { public: QFontEngineBox(int size); ~QFontEngineBox(); virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const; virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const; #if !defined(Q_WS_X11) && !defined(Q_WS_WIN) && !defined(Q_WS_MAC) && !defined(Q_OS_SYMBIAN) void draw(QPaintEngine *p, qreal x, qreal y, const QTextItemInt &si); #endif virtual void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags); virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs); virtual glyph_metrics_t boundingBox(glyph_t glyph); virtual QFixed ascent() const; virtual QFixed descent() const; virtual QFixed leading() const; virtual qreal maxCharWidth() const; virtual qreal minLeftBearing() const { return 0; } virtual qreal minRightBearing() const { return 0; } virtual QImage alphaMapForGlyph(glyph_t); #ifdef Q_WS_X11 int cmap() const; #endif virtual const char *name() const; virtual bool canRender(const QChar *string, int len); virtual Type type() const; inline int size() const { return _size; } private: friend class QFontPrivate; int _size; }; class QFontEngineMulti : public QFontEngine { public: explicit QFontEngineMulti(int engineCount); ~QFontEngineMulti(); virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const; virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs); virtual glyph_metrics_t boundingBox(glyph_t glyph); virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const; virtual void doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const; virtual void addOutlineToPath(qreal, qreal, const QGlyphLayout &, QPainterPath *, QTextItem::RenderFlags flags); virtual void getGlyphBearings(glyph_t glyph, qreal *leftBearing = 0, qreal *rightBearing = 0); virtual QFixed ascent() const; virtual QFixed descent() const; virtual QFixed leading() const; virtual QFixed xHeight() const; virtual QFixed averageCharWidth() const; virtual QImage alphaMapForGlyph(glyph_t); virtual QFixed lineThickness() const; virtual QFixed underlinePosition() const; virtual qreal maxCharWidth() const; virtual qreal minLeftBearing() const; virtual qreal minRightBearing() const; virtual inline Type type() const { return QFontEngine::Multi; } virtual bool canRender(const QChar *string, int len); inline virtual const char *name() const { return "Multi"; } QFontEngine *engine(int at) const {Q_ASSERT(at < engines.size()); return engines.at(at); } protected: friend class QPSPrintEnginePrivate; friend class QPSPrintEngineFontMulti; virtual void loadEngine(int at) = 0; QVector<QFontEngine *> engines; }; #if defined(Q_WS_MAC) struct QCharAttributes; class QFontEngineMacMulti; # if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5 class QCoreTextFontEngineMulti; class QCoreTextFontEngine : public QFontEngine { public: QCoreTextFontEngine(CTFontRef font, const QFontDef &def, QCoreTextFontEngineMulti *multiEngine = 0); ~QCoreTextFontEngine(); virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const; virtual void recalcAdvances(int , QGlyphLayout *, QTextEngine::ShaperFlags) const; virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs); virtual glyph_metrics_t boundingBox(glyph_t glyph); virtual QFixed ascent() const; virtual QFixed descent() const; virtual QFixed leading() const; virtual QFixed xHeight() const; virtual qreal maxCharWidth() const; virtual QFixed averageCharWidth() const; virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs, QPainterPath *path, QTextItem::RenderFlags); virtual const char *name() const { return "QCoreTextFontEngine"; } virtual bool canRender(const QChar *string, int len); virtual int synthesized() const { return synthesisFlags; } virtual Type type() const { return QFontEngine::Mac; } void draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight); virtual FaceId faceId() const; virtual bool getSfntTableData(uint /*tag*/, uchar * /*buffer*/, uint * /*length*/) const; virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics); virtual QImage alphaMapForGlyph(glyph_t); virtual QImage alphaRGBMapForGlyph(glyph_t, int margin, const QTransform &t); virtual qreal minRightBearing() const; virtual qreal minLeftBearing() const; private: QImage imageForGlyph(glyph_t glyph, int margin, bool colorful); CTFontRef ctfont; CGFontRef cgFont; QCoreTextFontEngineMulti *parentEngine; int synthesisFlags; CGAffineTransform transform; friend class QCoreTextFontEngineMulti; }; class QCoreTextFontEngineMulti : public QFontEngineMulti { public: QCoreTextFontEngineMulti(const ATSFontFamilyRef &atsFamily, const ATSFontRef &atsFontRef, const QFontDef &fontDef, bool kerning); ~QCoreTextFontEngineMulti(); virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const; bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags, unsigned short *logClusters, const HB_CharAttributes *charAttributes) const; virtual void recalcAdvances(int , QGlyphLayout *, QTextEngine::ShaperFlags) const; virtual void doKerning(int , QGlyphLayout *, QTextEngine::ShaperFlags) const; virtual const char *name() const { return "CoreText"; } protected: virtual void loadEngine(int at); private: inline const QCoreTextFontEngine *engineAt(int i) const { return static_cast<const QCoreTextFontEngine *>(engines.at(i)); } uint fontIndexForFont(CTFontRef id) const; CTFontRef ctfont; mutable QCFType<CFMutableDictionaryRef> attributeDict; CGAffineTransform transform; friend class QFontDialogPrivate; }; # endif //MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5 #ifndef QT_MAC_USE_COCOA class QFontEngineMac : public QFontEngine { friend class QFontEngineMacMulti; public: QFontEngineMac(ATSUStyle baseStyle, ATSUFontID fontID, const QFontDef &def, QFontEngineMacMulti *multiEngine = 0); virtual ~QFontEngineMac(); virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *numGlyphs, QTextEngine::ShaperFlags flags) const; virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const; virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs); virtual glyph_metrics_t boundingBox(glyph_t glyph); virtual QFixed ascent() const; virtual QFixed descent() const; virtual QFixed leading() const; virtual QFixed xHeight() const; virtual qreal maxCharWidth() const; virtual QFixed averageCharWidth() const; virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs, QPainterPath *path, QTextItem::RenderFlags); virtual const char *name() const { return "QFontEngineMac"; } virtual bool canRender(const QChar *string, int len); virtual int synthesized() const { return synthesisFlags; } virtual Type type() const { return QFontEngine::Mac; } void draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight); virtual FaceId faceId() const; virtual QByteArray getSfntTable(uint tag) const; virtual Properties properties() const; virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics); virtual QImage alphaMapForGlyph(glyph_t); virtual QImage alphaRGBMapForGlyph(glyph_t, int margin, const QTransform &t); private: QImage imageForGlyph(glyph_t glyph, int margin, bool colorful); ATSUFontID fontID; QCFType<CGFontRef> cgFont; ATSUStyle style; int synthesisFlags; mutable QGlyphLayout kashidaGlyph; QFontEngineMacMulti *multiEngine; mutable const unsigned char *cmap; mutable bool symbolCMap; mutable QByteArray cmapTable; CGAffineTransform transform; QFixed m_ascent; QFixed m_descent; QFixed m_leading; qreal m_maxCharWidth; QFixed m_xHeight; QFixed m_averageCharWidth; }; class QFontEngineMacMulti : public QFontEngineMulti { friend class QFontEngineMac; public: // internal struct ShaperItem { inline ShaperItem() : string(0), from(0), length(0), log_clusters(0), charAttributes(0) {} const QChar *string; int from; int length; QGlyphLayout glyphs; unsigned short *log_clusters; const HB_CharAttributes *charAttributes; QTextEngine::ShaperFlags flags; }; QFontEngineMacMulti(const ATSFontFamilyRef &atsFamily, const ATSFontRef &atsFontRef, const QFontDef &fontDef, bool kerning); virtual ~QFontEngineMacMulti(); virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const; bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags, unsigned short *logClusters, const HB_CharAttributes *charAttributes) const; virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const; virtual void doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const; virtual const char *name() const { return "ATSUI"; } virtual bool canRender(const QChar *string, int len); inline ATSUFontID macFontID() const { return fontID; } protected: virtual void loadEngine(int at); private: inline const QFontEngineMac *engineAt(int i) const { return static_cast<const QFontEngineMac *>(engines.at(i)); } bool stringToCMapInternal(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags, ShaperItem *item) const; int fontIndexForFontID(ATSUFontID id) const; ATSUFontID fontID; uint kerning : 1; mutable ATSUTextLayout textLayout; mutable ATSUStyle style; CGAffineTransform transform; }; #endif //!QT_MAC_USE_COCOA #endif class QTestFontEngine : public QFontEngineBox { public: QTestFontEngine(int size) : QFontEngineBox(size) {} virtual Type type() const { return TestFontEngine; } }; QT_END_NAMESPACE #ifdef Q_WS_WIN # include "private/qfontengine_win_p.h" #endif #if defined(Q_OS_SYMBIAN) && !defined(QT_NO_FREETYPE) # include "private/qfontengine_ft_p.h" #endif #endif // QFONTENGINE_P_H
8,775
412
<filename>regression/snapshot-harness/pointer_to_struct_01/main.c #include <assert.h> #include <malloc.h> struct S { struct S *next; }; struct S st; struct S *p; struct S *q; void initialize() { st.next = &st; p = &st; q = malloc(sizeof(struct S)); } void checkpoint() { } int main() { initialize(); checkpoint(); assert(p == &st); assert(p->next == &st); assert(p != q); q->next = &st; assert(p == q->next); }
185
416
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * 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.tencentcloudapi.essbasic.v20210526.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class Agent extends AbstractModel{ /** * 腾讯电子签颁发给渠道的应用ID,32位字符串 */ @SerializedName("AppId") @Expose private String AppId; /** * 腾讯电子签颁发给渠道侧合作企业的企业ID */ @SerializedName("ProxyOrganizationId") @Expose private String ProxyOrganizationId; /** * 腾讯电子签颁发给渠道侧合作企业的应用ID */ @SerializedName("ProxyAppId") @Expose private String ProxyAppId; /** * 渠道/平台合作企业经办人(操作员) */ @SerializedName("ProxyOperator") @Expose private UserInfo ProxyOperator; /** * 渠道/平台合作企业的企业ID */ @SerializedName("ProxyOrganizationOpenId") @Expose private String ProxyOrganizationOpenId; /** * Get 腾讯电子签颁发给渠道的应用ID,32位字符串 * @return AppId 腾讯电子签颁发给渠道的应用ID,32位字符串 */ public String getAppId() { return this.AppId; } /** * Set 腾讯电子签颁发给渠道的应用ID,32位字符串 * @param AppId 腾讯电子签颁发给渠道的应用ID,32位字符串 */ public void setAppId(String AppId) { this.AppId = AppId; } /** * Get 腾讯电子签颁发给渠道侧合作企业的企业ID * @return ProxyOrganizationId 腾讯电子签颁发给渠道侧合作企业的企业ID */ public String getProxyOrganizationId() { return this.ProxyOrganizationId; } /** * Set 腾讯电子签颁发给渠道侧合作企业的企业ID * @param ProxyOrganizationId 腾讯电子签颁发给渠道侧合作企业的企业ID */ public void setProxyOrganizationId(String ProxyOrganizationId) { this.ProxyOrganizationId = ProxyOrganizationId; } /** * Get 腾讯电子签颁发给渠道侧合作企业的应用ID * @return ProxyAppId 腾讯电子签颁发给渠道侧合作企业的应用ID */ public String getProxyAppId() { return this.ProxyAppId; } /** * Set 腾讯电子签颁发给渠道侧合作企业的应用ID * @param ProxyAppId 腾讯电子签颁发给渠道侧合作企业的应用ID */ public void setProxyAppId(String ProxyAppId) { this.ProxyAppId = ProxyAppId; } /** * Get 渠道/平台合作企业经办人(操作员) * @return ProxyOperator 渠道/平台合作企业经办人(操作员) */ public UserInfo getProxyOperator() { return this.ProxyOperator; } /** * Set 渠道/平台合作企业经办人(操作员) * @param ProxyOperator 渠道/平台合作企业经办人(操作员) */ public void setProxyOperator(UserInfo ProxyOperator) { this.ProxyOperator = ProxyOperator; } /** * Get 渠道/平台合作企业的企业ID * @return ProxyOrganizationOpenId 渠道/平台合作企业的企业ID */ public String getProxyOrganizationOpenId() { return this.ProxyOrganizationOpenId; } /** * Set 渠道/平台合作企业的企业ID * @param ProxyOrganizationOpenId 渠道/平台合作企业的企业ID */ public void setProxyOrganizationOpenId(String ProxyOrganizationOpenId) { this.ProxyOrganizationOpenId = ProxyOrganizationOpenId; } public Agent() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public Agent(Agent source) { if (source.AppId != null) { this.AppId = new String(source.AppId); } if (source.ProxyOrganizationId != null) { this.ProxyOrganizationId = new String(source.ProxyOrganizationId); } if (source.ProxyAppId != null) { this.ProxyAppId = new String(source.ProxyAppId); } if (source.ProxyOperator != null) { this.ProxyOperator = new UserInfo(source.ProxyOperator); } if (source.ProxyOrganizationOpenId != null) { this.ProxyOrganizationOpenId = new String(source.ProxyOrganizationOpenId); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "AppId", this.AppId); this.setParamSimple(map, prefix + "ProxyOrganizationId", this.ProxyOrganizationId); this.setParamSimple(map, prefix + "ProxyAppId", this.ProxyAppId); this.setParamObj(map, prefix + "ProxyOperator.", this.ProxyOperator); this.setParamSimple(map, prefix + "ProxyOrganizationOpenId", this.ProxyOrganizationOpenId); } }
2,668
5,250
/* 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.flowable.job.service.impl.asyncexecutor; import org.apache.commons.lang3.exception.ExceptionUtils; import org.flowable.job.api.JobInfo; import org.flowable.job.service.JobServiceConfiguration; import org.flowable.job.service.impl.persistence.entity.JobEntity; import org.flowable.job.service.impl.persistence.entity.SuspendedJobEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Swallow exception for the debugger executions and add debugger breakpoint again to the suspended jobs. * * @author martin.grofcik */ public class DefaultDebuggerExecutionExceptionHandler implements AsyncRunnableExecutionExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultDebuggerExecutionExceptionHandler.class); private static final String HANDLER_TYPE_BREAK_POINT = "breakpoint"; @Override public boolean handleException(final JobServiceConfiguration jobServiceConfiguration, final JobInfo job, final Throwable exception) { if (HANDLER_TYPE_BREAK_POINT.equals(job.getJobHandlerType())) { LOGGER.debug("break point execution throws an exception which will be swallowed", exception); jobServiceConfiguration.getCommandExecutor().execute( commandContext -> { JobEntity jobEntity = jobServiceConfiguration.getJobService().findJobById(job.getId()); SuspendedJobEntity suspendedJobEntity = jobServiceConfiguration.getJobService().moveJobToSuspendedJob(jobEntity); if (exception != null) { LOGGER.info("Debugger exception ", exception); suspendedJobEntity.setExceptionMessage(exception.getMessage()); suspendedJobEntity.setExceptionStacktrace(ExceptionUtils.getStackTrace(exception)); } return null; } ); return true; } return false; } }
933
1,144
<gh_stars>1000+ package de.metas.calendar; import java.time.DayOfWeek; import java.time.LocalDate; import javax.annotation.Nullable; import org.adempiere.exceptions.AdempiereException; import lombok.Builder; import lombok.NonNull; import lombok.Value; /* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2018 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ @Value @Builder public class RecurrentNonBusinessDay implements NonBusinessDay { @NonNull RecurrentNonBusinessDayFrequency frequency; @NonNull LocalDate startDate; @Nullable LocalDate endDate; @Nullable String name; @Override public boolean isMatching(@NonNull final LocalDate date) { if (!isInRange(date)) { return false; } if (frequency == RecurrentNonBusinessDayFrequency.WEEKLY) { final DayOfWeek dayOfWeek = this.startDate.getDayOfWeek(); return date.getDayOfWeek().equals(dayOfWeek); } else if (frequency == RecurrentNonBusinessDayFrequency.YEARLY) { LocalDate currentDate = startDate; while (isInRange(currentDate) && currentDate.compareTo(date) <= 0) { if (currentDate.equals(date)) { return true; } currentDate = currentDate.plusYears(1); } return false; } else { throw new AdempiereException("Unknown frequency type: " + frequency); } } private boolean isInRange(@NonNull final LocalDate date) { // Before start date if (date.compareTo(startDate) < 0) { return false; } // After end date if (endDate != null && date.compareTo(endDate) > 0) { return false; } return true; } }
784
648
<filename>spec/hl7.fhir.core/1.0.2/package/DataElement-ImagingObjectSelection.json {"resourceType":"DataElement","id":"ImagingObjectSelection","meta":{"lastUpdated":"2015-10-24T07:41:03.495+11:00"},"url":"http://hl7.org/fhir/DataElement/ImagingObjectSelection","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"path":"ImagingObjectSelection","short":"Key Object Selection","definition":"A manifest of a set of DICOM Service-Object Pair Instances (SOP Instances). The referenced SOP Instances (images or other content) are for a single patient, and may be from one or more studies. The referenced SOP Instances have been selected for a purpose, such as quality assurance, conference, or consult. Reflecting that range of purposes, typical ImagingObjectSelection resources may include all SOP Instances in a study (perhaps for sharing through a Health Information Exchange); key images from multiple studies (for reference by a referring or treating physician); a multi-frame ultrasound instance (\"cine\" video clip) and a set of measurements taken from that instance (for inclusion in a teaching file); and so on.","alias":["Manifest","XDS-I summary","Key Images","KOS"],"min":0,"max":"*","type":[{"code":"DomainResource"}],"isSummary":true,"mapping":[{"identity":"dicom","map":"Key Object Selection SOP Class (1.2.840.10008.5.1.4.1.1.88.59)"},{"identity":"w5","map":"clinical.diagnostics"}]}]}
377
14,668
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/cert_provisioning/cert_provisioning_worker.h" #include <memory> #include <string> #include "base/base64.h" #include "base/callback.h" #include "base/json/json_string_value_serializer.h" #include "base/json/json_writer.h" #include "base/strings/stringprintf.h" #include "base/test/gmock_callback_support.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/values_test_util.h" #include "base/time/time.h" #include "chrome/browser/ash/attestation/mock_tpm_challenge_key_subtle.h" #include "chrome/browser/ash/attestation/tpm_challenge_key_subtle.h" #include "chrome/browser/ash/cert_provisioning/cert_provisioning_common.h" #include "chrome/browser/ash/cert_provisioning/cert_provisioning_metrics.h" #include "chrome/browser/ash/cert_provisioning/cert_provisioning_test_helpers.h" #include "chrome/browser/ash/cert_provisioning/mock_cert_provisioning_invalidator.h" #include "chrome/browser/ash/platform_keys/key_permissions/fake_user_private_token_kpm_service.h" #include "chrome/browser/ash/platform_keys/key_permissions/key_permissions_manager.h" #include "chrome/browser/ash/platform_keys/key_permissions/key_permissions_manager_impl.h" #include "chrome/browser/ash/platform_keys/key_permissions/mock_key_permissions_manager.h" #include "chrome/browser/ash/platform_keys/key_permissions/user_private_token_kpm_service_factory.h" #include "chrome/browser/ash/platform_keys/mock_platform_keys_service.h" #include "chrome/browser/ash/platform_keys/platform_keys_service.h" #include "chrome/browser/ash/platform_keys/platform_keys_service_factory.h" #include "chrome/browser/platform_keys/platform_keys.h" #include "chromeos/dbus/attestation/fake_attestation_client.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_service.h" #include "components/prefs/testing_pref_service.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash { namespace cert_provisioning { namespace { namespace em = ::enterprise_management; using ::ash::attestation::MockTpmChallengeKeySubtle; using ::ash::platform_keys::KeyUsage; using ::base::test::IsJson; using ::base::test::ParseJson; using ::base::test::RunOnceCallback; using ::chromeos::platform_keys::HashAlgorithm; using ::chromeos::platform_keys::KeyAttributeType; using ::chromeos::platform_keys::Status; using ::chromeos::platform_keys::TokenId; using ::testing::_; using ::testing::AtLeast; using ::testing::Mock; using ::testing::SaveArg; using ::testing::StrictMock; // Generated by chrome/test/data/policy/test_certs/create_test_certs.sh constexpr char kFakeCertificate[] = R"(-----BEGIN CERTIFICATE----- MIIDJzCCAg+gAwIBAgIBATANBgkqhkiG9w0BAQsFADAXMRUwEwYDVQQDDAxyb290 X2NhX2NlcnQwHhcNMjAwMjI1MTUyNTU2WhcNMzAwMjIyMTUyNTU2WjAUMRIwEAYD VQQDDAkxMjcuMC4wLjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDW druvpaJovmyWzIcjtsSk/lp319+zNPSYGLzJzTeEmnFoDf/b89ft6xR1NIahmvVd UHGOMlzgDKnNkqWw+pgpn6U8dk+leWnwlUefzDz7OY8qXfX29Vh0m/kATQc64lnp rX19fEi2DOgH6heCQDSaHI/KAnAXccwl8kdGuTEnvdzbdHqQq8pPGpEqzC/NOjk7 kDNkUt0J74ZVMm4+jhVOgZ35mFLtC+xjfycBgbnt8yfPOzmOMwXTjYDPNaIy32AZ t66oIToteoW5Ilg+j5Mto3unBDHrw8rml3+W/nwHuOPEIgBqLQFfWtXpuX8CbcS6 SFNK4hxCJOvlzUbgTpsrAgMBAAGjgYAwfjAMBgNVHRMBAf8EAjAAMB0GA1UdDgQW BBRDEl1/2pL5LtKnpIly+XCj3N6MwDAfBgNVHSMEGDAWgBQrwVEnUQZlX850A2N+ URfS8BxoyzAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDwYDVR0RBAgw BocEfwAAATANBgkqhkiG9w0BAQsFAAOCAQEAXZd+Ul7GUFZPLSiTZ618hUI2UdO0 7rtPwBw3TephWuyEeHht+WhzA3sRL3nprEiJqIg5w/Tlfz4dsObpSU3vKmDhLzAx HJrN5vKdbEj9wyuhYSRJwvJka1ZOgPzhQcDQOp1SqonNxLx/sSMDR2UIDMBGzrkQ sDkn58N5eWm+hZADOAKROHR47j85VcsmYGK7z2x479YzsyWyOm0dbACXv7/HvFkz 56KvgxRaPZQzQUg5yuXa21IjQz07wyWSYnHpm2duAbYFl6CTR9Rlj5vpRkKsQP1W mMhGDBfgEskdbM+0agsZrJupoQMBUbD5gflcJlW3kwlboi3dTtiGixfYWw== -----END CERTIFICATE-----)"; // Extracted from the certificate using the command: // openssl x509 -pubkey -noout -in cert.pem // and reformatted as a single line. constexpr char kPublicKeyBase64[] = "<KEY>" "<KEY> "<KEY> "<KEY> "<KEY>+" "GVTJuPo4VToGd+ZhS7QvsY38nAYG57fMnzzs5jjMF042AzzWiMt9gGbeuqCE6LXqFuSJYPo+" "<KEY>"; constexpr char kCertProfileId[] = "cert_profile_1"; constexpr char kCertProfileName[] = "Certificate Profile 1"; constexpr char kCertProfileVersion[] = "cert_profile_version_1"; constexpr base::TimeDelta kCertProfileRenewalPeriod = base::Seconds(0); // Prefix + certificate profile name. constexpr char kCertScopeStrUser[] = "google/chromeos/user"; constexpr char kCertScopeStrDevice[] = "google/chromeos/device"; constexpr char kInvalidationTopic[] = "fake_invalidation_topic_1"; constexpr char kDataToSign[] = "fake_data_to_sign_1"; constexpr char kChallenge[] = "fake_va_challenge_1"; constexpr char kChallengeResponse[] = "fake_va_challenge_response_1"; constexpr char kSignature[] = "fake_signature_1"; constexpr unsigned int kNonVaKeyModulusLengthBits = 2048; const std::string& GetPublicKey() { static std::string public_key; if (public_key.empty()) { base::Base64Decode(kPublicKeyBase64, &public_key); } return public_key; } void VerifyDeleteKeyCalledOnce(CertScope cert_scope) { const std::vector<::attestation::DeleteKeysRequest> delete_keys_history = chromeos::AttestationClient::Get() ->GetTestInterface() ->delete_keys_history(); EXPECT_EQ(delete_keys_history.size(), 1); EXPECT_EQ(delete_keys_history[0].username().empty(), cert_scope != CertScope::kUser); EXPECT_EQ(delete_keys_history[0].key_label_match(), GetKeyName(kCertProfileId)); EXPECT_EQ(delete_keys_history[0].match_behavior(), ::attestation::DeleteKeysRequest::MATCH_BEHAVIOR_EXACT); } // Using macros to reduce boilerplate code, but keep real line numbers in // error messages in case of expectation failure. They use some of protected // fields of CertProvisioningWorkerTest class and may be considered as extra // methods of it. *_OK macros immediately call callbacks with some successful // results. *_NO_OP doesn't call callbacks. #define EXPECT_PREPARE_KEY_OK(MOCK_TPM_CHALLENGE_KEY, PREPARE_KEY_FUNC) \ { \ auto public_key_result = \ attestation::TpmChallengeKeyResult::MakePublicKey(GetPublicKey()); \ EXPECT_CALL((MOCK_TPM_CHALLENGE_KEY), PREPARE_KEY_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>(public_key_result)); \ } #define EXPECT_SIGN_CHALLENGE_OK(MOCK_TPM_CHALLENGE_KEY, SIGN_CHALLENGE_FUNC) \ { \ auto sign_challenge_result = \ attestation::TpmChallengeKeyResult::MakeChallengeResponse( \ kChallengeResponse); \ EXPECT_CALL((MOCK_TPM_CHALLENGE_KEY), SIGN_CHALLENGE_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<1>(sign_challenge_result)); \ } #define EXPECT_REGISTER_KEY_OK(MOCK_TPM_CHALLENGE_KEY, REGISTER_KEY_FUNC) \ { \ auto register_key_result = \ attestation::TpmChallengeKeyResult::MakeSuccess(); \ EXPECT_CALL((MOCK_TPM_CHALLENGE_KEY), REGISTER_KEY_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<0>(register_key_result)); \ } #define EXPECT_START_CSR_OK(START_CSR_FUNC, HASHING_ALGO) \ { \ EXPECT_CALL(cloud_policy_client_, START_CSR_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>( \ policy::DeviceManagementStatus::DM_STATUS_SUCCESS, \ /*response_error=*/absl::nullopt, \ /*try_again_later_ms=*/absl::nullopt, kInvalidationTopic, \ kChallenge, HASHING_ALGO, kDataToSign)); \ } #define EXPECT_START_CSR_OK_WITHOUT_VA(START_CSR_FUNC, HASHING_ALGO) \ { \ EXPECT_CALL(cloud_policy_client_, START_CSR_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>( \ policy::DeviceManagementStatus::DM_STATUS_SUCCESS, \ /*response_error=*/absl::nullopt, \ /*try_again_later_ms=*/absl::nullopt, kInvalidationTopic, \ /*va_challenge=*/"", HASHING_ALGO, kDataToSign)); \ } #define EXPECT_START_CSR_TRY_LATER(START_CSR_FUNC, DELAY_MS) \ { \ EXPECT_CALL(cloud_policy_client_, START_CSR_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>( \ policy::DeviceManagementStatus::DM_STATUS_SUCCESS, \ /*response_error=*/absl::nullopt, \ /*try_again_later_ms=*/(DELAY_MS), kInvalidationTopic, \ /*va_challenge=*/"", \ enterprise_management::HashingAlgorithm:: \ HASHING_ALGORITHM_UNSPECIFIED, \ /*data_to_sign=*/"")); \ } #define EXPECT_START_CSR_INVALID_REQUEST(START_CSR_FUNC) \ { \ EXPECT_CALL(cloud_policy_client_, START_CSR_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>( \ policy::DeviceManagementStatus::DM_STATUS_REQUEST_INVALID, \ /*response_error=*/absl::nullopt, \ /*try_again_later_ms=*/absl::nullopt, /*invalidation_topic=*/"", \ /*va_challenge=*/"", \ enterprise_management::HashingAlgorithm:: \ HASHING_ALGORITHM_UNSPECIFIED, \ /*data_to_sign=*/"")); \ } #define EXPECT_START_CSR_CA_ERROR(START_CSR_FUNC) \ { \ EXPECT_CALL(cloud_policy_client_, START_CSR_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>( \ policy::DeviceManagementStatus::DM_STATUS_SUCCESS, \ /*response_error=*/CertProvisioningResponseError::CA_ERROR, \ /*try_again_later_ms=*/absl::nullopt, /*invalidation_topic=*/"", \ /*va_challenge=*/"", \ enterprise_management::HashingAlgorithm:: \ HASHING_ALGORITHM_UNSPECIFIED, \ /*data_to_sign=*/"")); \ } #define EXPECT_START_CSR_TEMPORARY_UNAVAILABLE(START_CSR_FUNC) \ { \ EXPECT_CALL(cloud_policy_client_, START_CSR_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>( \ policy::DeviceManagementStatus::DM_STATUS_TEMPORARY_UNAVAILABLE, \ /*response_error=*/absl::nullopt, \ /*try_again_later_ms=*/absl::nullopt, /*invalidation_topic=*/"", \ /*va_challenge=*/"", \ enterprise_management::HashingAlgorithm:: \ HASHING_ALGORITHM_UNSPECIFIED, \ /*data_to_sign=*/"")); \ } #define EXPECT_START_CSR_SERVICE_ACTIVATION_PENDING(START_CSR_FUNC) \ { \ EXPECT_CALL(cloud_policy_client_, START_CSR_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>(policy::DeviceManagementStatus:: \ DM_STATUS_SERVICE_ACTIVATION_PENDING, \ /*response_error=*/absl::nullopt, \ /*try_again_later_ms=*/absl::nullopt, \ /*invalidation_topic=*/"", \ /*va_challenge=*/"", \ enterprise_management::HashingAlgorithm:: \ HASHING_ALGORITHM_UNSPECIFIED, \ /*data_to_sign=*/"")); \ } #define EXPECT_START_CSR_INCONSISTENT_DATA(START_CSR_FUNC) \ { \ EXPECT_CALL(cloud_policy_client_, START_CSR_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>( \ policy::DeviceManagementStatus:: \ DM_STATUS_SUCCESS, /*response_error=*/ \ CertProvisioningResponseError::INCONSISTENT_DATA, \ /*try_again_later_ms=*/absl::nullopt, /*invalidation_topic=*/"", \ /*va_challenge=*/"", \ enterprise_management::HashingAlgorithm:: \ HASHING_ALGORITHM_UNSPECIFIED, \ /*data_to_sign=*/"")); \ } #define EXPECT_START_CSR_NO_OP(START_CSR_FUNC) \ { EXPECT_CALL(cloud_policy_client_, START_CSR_FUNC).Times(1); } #define EXPECT_FINISH_CSR_OK(FINISH_CSR_FUNC) \ { \ EXPECT_CALL(cloud_policy_client_, FINISH_CSR_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<6>( \ policy::DeviceManagementStatus::DM_STATUS_SUCCESS, absl::nullopt, \ absl::nullopt)); \ } #define EXPECT_FINISH_CSR_TRY_LATER(FINISH_CSR_FUNC, DELAY_MS) \ { \ EXPECT_CALL(cloud_policy_client_, FINISH_CSR_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<6>( \ policy::DeviceManagementStatus::DM_STATUS_SUCCESS, absl::nullopt, \ /*try_again_later_ms=*/(DELAY_MS))); \ } #define EXPECT_FINISH_CSR_SERVICE_ACTIVATION_PENDING(FINISH_CSR_FUNC) \ { \ EXPECT_CALL(cloud_policy_client_, FINISH_CSR_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<6>(policy::DeviceManagementStatus:: \ DM_STATUS_SERVICE_ACTIVATION_PENDING, \ absl::nullopt, absl::nullopt)); \ } #define EXPECT_DOWNLOAD_CERT_OK(DOWNLOAD_CERT_FUNC) \ { \ EXPECT_CALL(cloud_policy_client_, DOWNLOAD_CERT_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>( \ policy::DeviceManagementStatus::DM_STATUS_SUCCESS, absl::nullopt, \ absl::nullopt, kFakeCertificate)); \ } #define EXPECT_DOWNLOAD_CERT_SERVICE_ACTIVATION_PENDING(DOWNLOAD_CERT_FUNC) \ { \ EXPECT_CALL(cloud_policy_client_, DOWNLOAD_CERT_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>(policy::DeviceManagementStatus:: \ DM_STATUS_SERVICE_ACTIVATION_PENDING, \ absl::nullopt, absl::nullopt, \ kFakeCertificate)); \ } #define EXPECT_DOWNLOAD_CERT_TRY_LATER(DOWNLOAD_CERT_FUNC, DELAY_MS) \ { \ EXPECT_CALL(cloud_policy_client_, DOWNLOAD_CERT_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>( \ policy::DeviceManagementStatus::DM_STATUS_SUCCESS, absl::nullopt, \ /*try_again_later_ms=*/(DELAY_MS), /*certificate=*/"")); \ } #define EXPECT_DOWNLOAD_CERT_NO_OP(DOWNLOAD_CERT_FUNC) \ { EXPECT_CALL(cloud_policy_client_, DOWNLOAD_CERT_FUNC).Times(1); } #define EXPECT_SET_ATTRIBUTE_FOR_KEY_OK(SET_FUNC) \ { \ EXPECT_CALL(*platform_keys_service_, SET_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>(Status::kSuccess)); \ } #define EXPECT_SET_ATTRIBUTE_FOR_KEY_FAIL(SET_FUNC) \ { \ EXPECT_CALL(*platform_keys_service_, SET_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>(Status::kErrorInternal)); \ } #define EXPECT_SIGN_RSAPKC1_DIGEST_OK(SIGN_FUNC) \ { \ EXPECT_CALL(*platform_keys_service_, SIGN_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<4>(kSignature, Status::kSuccess)); \ } #define EXPECT_SIGN_RSAPKC1_RAW_OK(SIGN_FUNC) \ { \ EXPECT_CALL(*platform_keys_service_, SIGN_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<3>(kSignature, Status::kSuccess)); \ } #define EXPECT_SIGN_RSAPKC1_DIGEST_FAIL(SIGN_FUNC) \ { \ EXPECT_CALL(*platform_keys_service_, SIGN_FUNC) \ .Times(1) \ .WillOnce( \ RunOnceCallback<4>(/*signature=*/"", Status::kErrorInternal)); \ } #define EXPECT_IMPORT_CERTIFICATE_OK(IMPORT_FUNC) \ { \ EXPECT_CALL(*platform_keys_service_, IMPORT_FUNC) \ .Times(1) \ .WillOnce(RunOnceCallback<2>(Status::kSuccess)); \ } // A mock for observing the result callback of the worker. class CallbackObserver { public: MOCK_METHOD(void, Callback, (const CertProfile& profile, CertProvisioningWorkerState state)); }; // A mock for observing the state change callback of the worker. class StateChangeCallbackObserver { public: MOCK_METHOD(void, StateChangeCallback, ()); }; class CertProvisioningWorkerTest : public ::testing::Test { public: CertProvisioningWorkerTest() { Init(); } CertProvisioningWorkerTest(const CertProvisioningWorkerTest&) = delete; CertProvisioningWorkerTest& operator=(const CertProvisioningWorkerTest&) = delete; ~CertProvisioningWorkerTest() override = default; void SetUp() override { ::chromeos::AttestationClient::InitializeFake(); // There should not be any calls to callback before this expect is // overridden. EXPECT_CALL(callback_observer_, Callback).Times(0); RegisterProfilePrefs(testing_pref_service_.registry()); RegisterLocalStatePrefs(testing_pref_service_.registry()); } void TearDown() override { EXPECT_FALSE( attestation::TpmChallengeKeySubtleFactory::WillReturnTestingInstance()); ::chromeos::AttestationClient::Shutdown(); } protected: void Init() { platform_keys_service_ = static_cast<platform_keys::MockPlatformKeysService*>( platform_keys::PlatformKeysServiceFactory::GetInstance() ->SetTestingFactoryAndUse( GetProfile(), base::BindRepeating( &platform_keys::BuildMockPlatformKeysService))); ASSERT_TRUE(platform_keys_service_); platform_keys::PlatformKeysServiceFactory::GetInstance() ->SetDeviceWideServiceForTesting(platform_keys_service_); key_permissions_manager_ = std::make_unique<platform_keys::MockKeyPermissionsManager>(); platform_keys::UserPrivateTokenKeyPermissionsManagerServiceFactory:: GetInstance() ->SetTestingFactory( GetProfile(), base::BindRepeating( &platform_keys:: BuildFakeUserPrivateTokenKeyPermissionsManagerService, key_permissions_manager_.get())); platform_keys::KeyPermissionsManagerImpl:: SetSystemTokenKeyPermissionsManagerForTesting( key_permissions_manager_.get()); // Only explicitly expected removals are allowed. EXPECT_CALL(*platform_keys_service_, RemoveCertificate).Times(0); EXPECT_CALL(*platform_keys_service_, RemoveKey).Times(0); } void FastForwardBy(base::TimeDelta delta) { task_environment_.FastForwardBy(delta); } // Replaces next result of TpmChallengeKeySubtleFactory and return pointer to // the mock. The mock will injected into next created worker and will live // until worker's destruction. Should be called before creation of every // worker. MockTpmChallengeKeySubtle* PrepareTpmChallengeKey() { auto mock_tpm_challenge_key_subtle_impl = std::make_unique<MockTpmChallengeKeySubtle>(); MockTpmChallengeKeySubtle* tpm_challenge_key_impl = mock_tpm_challenge_key_subtle_impl.get(); attestation::TpmChallengeKeySubtleFactory::SetForTesting( std::move(mock_tpm_challenge_key_subtle_impl)); CHECK(tpm_challenge_key_impl); return tpm_challenge_key_impl; } base::RepeatingClosure GetStateChangeCallback() { return base::BindRepeating( &StateChangeCallbackObserver ::StateChangeCallback, base::Unretained(&state_change_callback_observer_)); } CertProvisioningWorkerCallback GetResultCallback() { return base::BindOnce(&CallbackObserver::Callback, base::Unretained(&callback_observer_)); } Profile* GetProfile() { return profile_helper_for_testing_.GetProfile(); } std::unique_ptr<MockCertProvisioningInvalidator> MakeInvalidator() { return std::make_unique<MockCertProvisioningInvalidator>(); } std::unique_ptr<MockCertProvisioningInvalidator> MakeInvalidator( MockCertProvisioningInvalidator** mock_invalidator) { auto result = std::make_unique<MockCertProvisioningInvalidator>(); *mock_invalidator = result.get(); return result; } content::BrowserTaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; StrictMock<StateChangeCallbackObserver> state_change_callback_observer_; StrictMock<CallbackObserver> callback_observer_; ProfileHelperForTesting profile_helper_for_testing_; TestingPrefServiceSimple testing_pref_service_; policy::MockCloudPolicyClient cloud_policy_client_; platform_keys::MockPlatformKeysService* platform_keys_service_ = nullptr; std::unique_ptr<platform_keys::MockKeyPermissionsManager> key_permissions_manager_; }; // Checks that the worker makes all necessary requests to other modules during // success scenario. TEST_F(CertProvisioningWorkerTest, Success) { base::HistogramTester histogram_tester; CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); MockCertProvisioningInvalidator* mock_invalidator = nullptr; CertProvisioningWorkerImpl worker( CertScope::kUser, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(&mock_invalidator), GetStateChangeCallback(), GetResultCallback()); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_START_CSR_OK( ClientCertProvisioningStartCsr(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), em::HashingAlgorithm::SHA256); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_CALL(*mock_invalidator, Register(kInvalidationTopic, _)).Times(1); EXPECT_SIGN_CHALLENGE_OK(*mock_tpm_challenge_key, StartSignChallengeStep(kChallenge, /*callback=*/_)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_REGISTER_KEY_OK(*mock_tpm_challenge_key, StartRegisterKeyStep); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_CALL( *key_permissions_manager_, AllowKeyForUsage(/*callback=*/_, KeyUsage::kCorporate, GetPublicKey())); EXPECT_SET_ATTRIBUTE_FOR_KEY_OK(SetAttributeForKey( TokenId::kUser, GetPublicKey(), KeyAttributeType::kCertificateProvisioningId, kCertProfileId, _)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_SIGN_RSAPKC1_DIGEST_OK( SignRSAPKCS1Digest(::testing::Optional(TokenId::kUser), kDataToSign, GetPublicKey(), HashAlgorithm::HASH_ALGORITHM_SHA256, /*callback=*/_)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_FINISH_CSR_OK(ClientCertProvisioningFinishCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), kChallengeResponse, kSignature, /*callback=*/_)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_DOWNLOAD_CERT_OK(ClientCertProvisioningDownloadCert( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); EXPECT_IMPORT_CERTIFICATE_OK(ImportCertificate(TokenId::kUser, /*certificate=*/_, /*callback=*/_)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_CALL(*mock_invalidator, Unregister()).Times(1); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kSucceeded)) .Times(1); } worker.DoStep(); histogram_tester.ExpectUniqueSample("ChromeOS.CertProvisioning.Result.User", CertProvisioningWorkerState::kSucceeded, 1); histogram_tester.ExpectUniqueSample( "ChromeOS.CertProvisioning.Event.User", CertProvisioningEvent::kRegisteredToInvalidationTopic, 1); histogram_tester.ExpectTotalCount( "ChromeOS.CertProvisioning.KeypairGenerationTime.User", 1); histogram_tester.ExpectTotalCount("ChromeOS.CertProvisioning.VaTime.User", 1); histogram_tester.ExpectTotalCount( "ChromeOS.CertProvisioning.CsrSignTime.User", 1); } // Checks that the worker makes all necessary requests to other modules during // success scenario when VA challenge is not received. TEST_F(CertProvisioningWorkerTest, NoVaSuccess) { CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/false, kCertProfileRenewalPeriod); CertProvisioningWorkerImpl worker( CertScope::kUser, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_CALL(*platform_keys_service_, GenerateRSAKey(TokenId::kUser, kNonVaKeyModulusLengthBits, /*sw_backed=*/false, /*callback=*/_)) .Times(1) .WillOnce(RunOnceCallback<3>(GetPublicKey(), Status::kSuccess)); EXPECT_START_CSR_OK_WITHOUT_VA( ClientCertProvisioningStartCsr(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), em::HashingAlgorithm::SHA256); EXPECT_CALL( *key_permissions_manager_, AllowKeyForUsage(/*callback=*/_, KeyUsage::kCorporate, GetPublicKey())); EXPECT_SET_ATTRIBUTE_FOR_KEY_OK(SetAttributeForKey( TokenId::kUser, GetPublicKey(), KeyAttributeType::kCertificateProvisioningId, kCertProfileId, _)); EXPECT_SIGN_RSAPKC1_DIGEST_OK( SignRSAPKCS1Digest(::testing::Optional(TokenId::kUser), kDataToSign, GetPublicKey(), HashAlgorithm::HASH_ALGORITHM_SHA256, /*callback=*/_)); EXPECT_FINISH_CSR_OK(ClientCertProvisioningFinishCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*va_challenge_response=*/"", kSignature, /*callback=*/_)); EXPECT_DOWNLOAD_CERT_OK(ClientCertProvisioningDownloadCert( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); EXPECT_IMPORT_CERTIFICATE_OK( ImportCertificate(TokenId::kUser, /*certificate=*/_, /*callback=*/_)); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kSucceeded)) .Times(1); } worker.DoStep(); } // Checks that the worker correctly forwards a request with // hashing_algorithm=NO_HASH to platform_keys. TEST_F(CertProvisioningWorkerTest, NoHashInStartCsr) { CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); MockCertProvisioningInvalidator* mock_invalidator = nullptr; CertProvisioningWorkerImpl worker( CertScope::kUser, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(&mock_invalidator), GetStateChangeCallback(), GetResultCallback()); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_START_CSR_OK( ClientCertProvisioningStartCsr(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), em::HashingAlgorithm::NO_HASH); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_CALL(*mock_invalidator, Register(kInvalidationTopic, _)).Times(1); EXPECT_SIGN_CHALLENGE_OK(*mock_tpm_challenge_key, StartSignChallengeStep(kChallenge, /*callback=*/_)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_REGISTER_KEY_OK(*mock_tpm_challenge_key, StartRegisterKeyStep); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_CALL( *key_permissions_manager_, AllowKeyForUsage(/*callback=*/_, KeyUsage::kCorporate, GetPublicKey())); EXPECT_SET_ATTRIBUTE_FOR_KEY_OK(SetAttributeForKey( TokenId::kUser, GetPublicKey(), KeyAttributeType::kCertificateProvisioningId, kCertProfileId, _)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_SIGN_RSAPKC1_RAW_OK( SignRSAPKCS1Raw(::testing::Optional(TokenId::kUser), kDataToSign, GetPublicKey(), /*callback=*/_)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_FINISH_CSR_OK(ClientCertProvisioningFinishCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), kChallengeResponse, kSignature, /*callback=*/_)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_DOWNLOAD_CERT_OK(ClientCertProvisioningDownloadCert( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); EXPECT_IMPORT_CERTIFICATE_OK( ImportCertificate(TokenId::kUser, /*certificate=*/_, /*callback=*/_)); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback()); EXPECT_CALL(*mock_invalidator, Unregister()).Times(1); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kSucceeded)) .Times(1); } worker.DoStep(); } // Checks that when the server returns try_again_later field, the worker will // retry a request when it asked to continue the provisioning. TEST_F(CertProvisioningWorkerTest, TryLaterManualRetry) { CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); CertProvisioningWorkerImpl worker( CertScope::kDevice, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); const base::TimeDelta delay = base::Seconds(30); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_DEVICE, /*will_register_key=*/true, /*key_name=*/GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); EXPECT_START_CSR_TRY_LATER( ClientCertProvisioningStartCsr(kCertScopeStrDevice, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), delay.InMilliseconds()); worker.DoStep(); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kKeypairGenerated); } { testing::InSequence seq; EXPECT_START_CSR_OK( ClientCertProvisioningStartCsr(kCertScopeStrDevice, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), em::HashingAlgorithm::SHA256); EXPECT_SIGN_CHALLENGE_OK(*mock_tpm_challenge_key, StartSignChallengeStep(kChallenge, /*callback=*/_)); EXPECT_REGISTER_KEY_OK(*mock_tpm_challenge_key, StartRegisterKeyStep); EXPECT_CALL( *key_permissions_manager_, AllowKeyForUsage(/*callback=*/_, KeyUsage::kCorporate, GetPublicKey())); EXPECT_SET_ATTRIBUTE_FOR_KEY_OK(SetAttributeForKey( TokenId::kSystem, GetPublicKey(), KeyAttributeType::kCertificateProvisioningId, kCertProfileId, _)); EXPECT_SIGN_RSAPKC1_DIGEST_OK(SignRSAPKCS1Digest); EXPECT_FINISH_CSR_TRY_LATER( ClientCertProvisioningFinishCsr( kCertScopeStrDevice, kCertProfileId, kCertProfileVersion, GetPublicKey(), kChallengeResponse, kSignature, /*callback=*/_), delay.InMilliseconds()); worker.DoStep(); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kSignCsrFinished); } { testing::InSequence seq; EXPECT_FINISH_CSR_OK(ClientCertProvisioningFinishCsr( kCertScopeStrDevice, kCertProfileId, kCertProfileVersion, GetPublicKey(), kChallengeResponse, kSignature, /*callback=*/_)); EXPECT_DOWNLOAD_CERT_TRY_LATER( ClientCertProvisioningDownloadCert(kCertScopeStrDevice, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), delay.InMilliseconds()); worker.DoStep(); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kFinishCsrResponseReceived); } { testing::InSequence seq; EXPECT_DOWNLOAD_CERT_OK( ClientCertProvisioningDownloadCert(kCertScopeStrDevice, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); EXPECT_IMPORT_CERTIFICATE_OK( ImportCertificate(TokenId::kSystem, /*certificate=*/_, /*callback=*/_)); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kSucceeded)) .Times(1); worker.DoStep(); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kSucceeded); } } // Checks that when the server returns try_again_later field, the worker will // automatically retry a request after some time. TEST_F(CertProvisioningWorkerTest, TryLaterWait) { CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); CertProvisioningWorkerImpl worker( CertScope::kUser, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); const base::TimeDelta start_csr_delay = base::Seconds(30); const base::TimeDelta finish_csr_delay = base::Seconds(30); const base::TimeDelta download_cert_server_delay = base::Milliseconds(100); const base::TimeDelta download_cert_real_delay = base::Seconds(10); const base::TimeDelta small_delay = base::Milliseconds(500); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); EXPECT_START_CSR_TRY_LATER( ClientCertProvisioningStartCsr(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), start_csr_delay.InMilliseconds()); worker.DoStep(); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kKeypairGenerated); } { testing::InSequence seq; EXPECT_START_CSR_OK( ClientCertProvisioningStartCsr(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), em::HashingAlgorithm::SHA256); EXPECT_SIGN_CHALLENGE_OK(*mock_tpm_challenge_key, StartSignChallengeStep(kChallenge, /*callback=*/_)); EXPECT_REGISTER_KEY_OK(*mock_tpm_challenge_key, StartRegisterKeyStep); EXPECT_CALL( *key_permissions_manager_, AllowKeyForUsage(/*callback=*/_, KeyUsage::kCorporate, GetPublicKey())); EXPECT_SET_ATTRIBUTE_FOR_KEY_OK(SetAttributeForKey( TokenId::kUser, GetPublicKey(), KeyAttributeType::kCertificateProvisioningId, kCertProfileId, _)); EXPECT_SIGN_RSAPKC1_DIGEST_OK( SignRSAPKCS1Digest(::testing::Optional(TokenId::kUser), kDataToSign, GetPublicKey(), HashAlgorithm::HASH_ALGORITHM_SHA256, /*callback=*/_)); EXPECT_FINISH_CSR_TRY_LATER( ClientCertProvisioningFinishCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), kChallengeResponse, kSignature, /*callback=*/_), finish_csr_delay.InMilliseconds()); FastForwardBy(start_csr_delay + small_delay); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kSignCsrFinished); } { testing::InSequence seq; EXPECT_FINISH_CSR_OK(ClientCertProvisioningFinishCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), kChallengeResponse, kSignature, /*callback=*/_)); EXPECT_DOWNLOAD_CERT_TRY_LATER( ClientCertProvisioningDownloadCert(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), download_cert_server_delay.InMilliseconds()); FastForwardBy(finish_csr_delay + small_delay); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kFinishCsrResponseReceived); } { testing::InSequence seq; EXPECT_DOWNLOAD_CERT_OK(ClientCertProvisioningDownloadCert); EXPECT_IMPORT_CERTIFICATE_OK( ImportCertificate(TokenId::kUser, /*certificate=*/_, /*callback=*/_)); FastForwardBy(small_delay); // Check that minimum wait time is not too small even if the server // has responded with a small one. EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kFinishCsrResponseReceived); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kSucceeded)) .Times(1); FastForwardBy(download_cert_real_delay + small_delay); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kSucceeded); } } // Checks that when the device management server returns a // DM_STATUS_SERVICE_ACTIVATION_PENDING status error (which is 412 pending // approval) the server retries the request after the expected delay depending // on the request. TEST_F(CertProvisioningWorkerTest, ServiceActivationPendingResponse) { CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); CertProvisioningWorkerImpl worker( CertScope::kUser, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); const base::TimeDelta kSmallDelay = base::Milliseconds(500); const base::TimeDelta kExpectedStartCsrDelay = base::Hours(1); const base::TimeDelta kExpectedFinishCsrDelay = base::Hours(1); const base::TimeDelta kExpectedDownloadCsrDelay = base::Hours(8); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); EXPECT_START_CSR_SERVICE_ACTIVATION_PENDING(ClientCertProvisioningStartCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); worker.DoStep(); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kKeypairGenerated); } { testing::InSequence seq; // Verify that nothing happens after half of the expected StartCsr delay. FastForwardBy(kExpectedStartCsrDelay / 2); Mock::VerifyAndClearExpectations(&cloud_policy_client_); EXPECT_START_CSR_OK( ClientCertProvisioningStartCsr(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), em::HashingAlgorithm::SHA256); EXPECT_SIGN_CHALLENGE_OK(*mock_tpm_challenge_key, StartSignChallengeStep(kChallenge, /*callback=*/_)); EXPECT_REGISTER_KEY_OK(*mock_tpm_challenge_key, StartRegisterKeyStep); EXPECT_CALL( *key_permissions_manager_, AllowKeyForUsage(/*callback=*/_, KeyUsage::kCorporate, GetPublicKey())); EXPECT_SET_ATTRIBUTE_FOR_KEY_OK(SetAttributeForKey( TokenId::kUser, GetPublicKey(), KeyAttributeType::kCertificateProvisioningId, kCertProfileId, _)); EXPECT_SIGN_RSAPKC1_DIGEST_OK( SignRSAPKCS1Digest(::testing::Optional(TokenId::kUser), kDataToSign, GetPublicKey(), HashAlgorithm::HASH_ALGORITHM_SHA256, /*callback=*/_)); EXPECT_FINISH_CSR_SERVICE_ACTIVATION_PENDING( ClientCertProvisioningFinishCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), kChallengeResponse, kSignature, /*callback=*/_)); FastForwardBy(kExpectedStartCsrDelay / 2 + kSmallDelay); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kSignCsrFinished); } { testing::InSequence seq; // Verify that nothing happens after half of the expected FinishCsr delay. FastForwardBy(kExpectedFinishCsrDelay / 2); Mock::VerifyAndClearExpectations(&cloud_policy_client_); EXPECT_FINISH_CSR_OK(ClientCertProvisioningFinishCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), kChallengeResponse, kSignature, /*callback=*/_)); EXPECT_DOWNLOAD_CERT_SERVICE_ACTIVATION_PENDING( ClientCertProvisioningDownloadCert(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); FastForwardBy(kExpectedFinishCsrDelay / 2 + kSmallDelay); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kFinishCsrResponseReceived); } { testing::InSequence seq; // Verify that nothing happens after half of the expected DownloadCert // delay. FastForwardBy(kExpectedDownloadCsrDelay / 2); Mock::VerifyAndClearExpectations(&cloud_policy_client_); EXPECT_DOWNLOAD_CERT_OK(ClientCertProvisioningDownloadCert); EXPECT_IMPORT_CERTIFICATE_OK( ImportCertificate(TokenId::kUser, /*certificate=*/_, /*callback=*/_)); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kFinishCsrResponseReceived); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kSucceeded)) .Times(1); FastForwardBy(kExpectedDownloadCsrDelay / 2 + kSmallDelay); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kSucceeded); } } // Checks that when the server returns try_again_later field, the worker will // retry when the invalidation is triggered. TEST_F(CertProvisioningWorkerTest, InvalidationRespected) { CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); MockCertProvisioningInvalidator* mock_invalidator = nullptr; CertProvisioningWorkerImpl worker( CertScope::kUser, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(&mock_invalidator), GetStateChangeCallback(), GetResultCallback()); const base::TimeDelta start_csr_delay = base::Seconds(30); const base::TimeDelta finish_csr_delay = base::Seconds(30); const base::TimeDelta download_cert_server_delay = base::Milliseconds(100); const base::TimeDelta small_delay = base::Milliseconds(500); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); EXPECT_START_CSR_TRY_LATER( ClientCertProvisioningStartCsr(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), start_csr_delay.InMilliseconds()); worker.DoStep(); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kKeypairGenerated); } base::RepeatingClosure on_invalidation_callback; { testing::InSequence seq; EXPECT_START_CSR_OK( ClientCertProvisioningStartCsr(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), em::HashingAlgorithm::SHA256); EXPECT_CALL(*mock_invalidator, Register(kInvalidationTopic, _)) .WillOnce(SaveArg<1>(&on_invalidation_callback)); EXPECT_SIGN_CHALLENGE_OK(*mock_tpm_challenge_key, StartSignChallengeStep(kChallenge, /*callback=*/_)); EXPECT_REGISTER_KEY_OK(*mock_tpm_challenge_key, StartRegisterKeyStep); EXPECT_CALL( *key_permissions_manager_, AllowKeyForUsage(/*callback=*/_, KeyUsage::kCorporate, GetPublicKey())); EXPECT_SET_ATTRIBUTE_FOR_KEY_OK(SetAttributeForKey( TokenId::kUser, GetPublicKey(), KeyAttributeType::kCertificateProvisioningId, kCertProfileId, _)); EXPECT_SIGN_RSAPKC1_DIGEST_OK( SignRSAPKCS1Digest(::testing::Optional(TokenId::kUser), kDataToSign, GetPublicKey(), HashAlgorithm::HASH_ALGORITHM_SHA256, /*callback=*/_)); EXPECT_FINISH_CSR_TRY_LATER( ClientCertProvisioningFinishCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), kChallengeResponse, kSignature, /*callback=*/_), finish_csr_delay.InMilliseconds()); FastForwardBy(start_csr_delay + small_delay); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kSignCsrFinished); } { testing::InSequence seq; EXPECT_FINISH_CSR_OK(ClientCertProvisioningFinishCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), kChallengeResponse, kSignature, /*callback=*/_)); EXPECT_DOWNLOAD_CERT_TRY_LATER( ClientCertProvisioningDownloadCert(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), download_cert_server_delay.InMilliseconds()); FastForwardBy(finish_csr_delay + small_delay); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kFinishCsrResponseReceived); } { EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kFinishCsrResponseReceived); testing::InSequence seq; EXPECT_DOWNLOAD_CERT_OK(ClientCertProvisioningDownloadCert); EXPECT_IMPORT_CERTIFICATE_OK( ImportCertificate(TokenId::kUser, /*certificate=*/_, /*callback=*/_)); EXPECT_CALL(*mock_invalidator, Unregister()).Times(1); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kSucceeded)) .Times(1); on_invalidation_callback.Run(); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kSucceeded); } } // Checks that when the server returns error status, the worker will enter an // error state and stop the provisioning. TEST_F(CertProvisioningWorkerTest, StatusErrorHandling) { const CertScope kCertScope = CertScope::kUser; CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); CertProvisioningWorkerImpl worker( kCertScope, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); EXPECT_START_CSR_INVALID_REQUEST(ClientCertProvisioningStartCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kFailed)) .Times(1); } worker.DoStep(); FastForwardBy(base::Seconds(1)); VerifyDeleteKeyCalledOnce(kCertScope); } // Checks that when the server returns response error, the worker will enter an // error state and stop the provisioning. Also check factory. TEST_F(CertProvisioningWorkerTest, ResponseErrorHandling) { const CertScope kCertScope = CertScope::kUser; base::HistogramTester histogram_tester; CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); auto worker = CertProvisioningWorkerFactory::Get()->Create( kCertScope, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); EXPECT_START_CSR_CA_ERROR(ClientCertProvisioningStartCsr); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kFailed)) .Times(1); } worker->DoStep(); FastForwardBy(base::Seconds(1)); VerifyDeleteKeyCalledOnce(kCertScope); histogram_tester.ExpectBucketCount("ChromeOS.CertProvisioning.Result.User", CertProvisioningWorkerState::kFailed, 1); histogram_tester.ExpectBucketCount( "ChromeOS.CertProvisioning.Result.User", CertProvisioningWorkerState::kKeypairGenerated, 1); histogram_tester.ExpectTotalCount("ChromeOS.CertProvisioning.Result.User", 2); } TEST_F(CertProvisioningWorkerTest, InconsistentDataErrorHandling) { const CertScope kCertScope = CertScope::kUser; CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); auto worker = CertProvisioningWorkerFactory::Get()->Create( kCertScope, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); EXPECT_START_CSR_INCONSISTENT_DATA(ClientCertProvisioningStartCsr); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kInconsistentDataError)) .Times(1); } worker->DoStep(); FastForwardBy(base::Seconds(1)); VerifyDeleteKeyCalledOnce(kCertScope); } // Checks that when the server returns TEMPORARY_UNAVAILABLE status code, the // worker will automatically retry a request using exponential backoff strategy. TEST_F(CertProvisioningWorkerTest, BackoffStrategy) { CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); CertProvisioningWorkerImpl worker( CertScope::kUser, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); base::TimeDelta next_delay = base::Seconds(30); const base::TimeDelta small_delay = base::Milliseconds(500); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); EXPECT_START_CSR_TEMPORARY_UNAVAILABLE(ClientCertProvisioningStartCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); worker.DoStep(); } Mock::VerifyAndClearExpectations(&cloud_policy_client_); { EXPECT_START_CSR_TEMPORARY_UNAVAILABLE(ClientCertProvisioningStartCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); FastForwardBy(next_delay + small_delay * 10); next_delay *= 2; } Mock::VerifyAndClearExpectations(&cloud_policy_client_); { EXPECT_START_CSR_TEMPORARY_UNAVAILABLE(ClientCertProvisioningStartCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); FastForwardBy(next_delay + small_delay * 10); next_delay *= 2; } Mock::VerifyAndClearExpectations(&cloud_policy_client_); { EXPECT_START_CSR_TEMPORARY_UNAVAILABLE(ClientCertProvisioningStartCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); FastForwardBy(next_delay + small_delay); next_delay *= 2; } } // Checks that the worker removes a key when an error occurs after the key was // registered. TEST_F(CertProvisioningWorkerTest, RemoveRegisteredKey) { base::HistogramTester histogram_tester; CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); MockCertProvisioningInvalidator* mock_invalidator = nullptr; CertProvisioningWorkerImpl worker( CertScope::kUser, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(&mock_invalidator), GetStateChangeCallback(), GetResultCallback()); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); EXPECT_START_CSR_OK( ClientCertProvisioningStartCsr(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), em::HashingAlgorithm::SHA256); EXPECT_CALL(*mock_invalidator, Register(kInvalidationTopic, _)).Times(1); EXPECT_SIGN_CHALLENGE_OK(*mock_tpm_challenge_key, StartSignChallengeStep(kChallenge, /*callback=*/_)); EXPECT_REGISTER_KEY_OK(*mock_tpm_challenge_key, StartRegisterKeyStep); EXPECT_CALL( *key_permissions_manager_, AllowKeyForUsage(/*callback=*/_, KeyUsage::kCorporate, GetPublicKey())); EXPECT_SET_ATTRIBUTE_FOR_KEY_FAIL(SetAttributeForKey( TokenId::kUser, GetPublicKey(), KeyAttributeType::kCertificateProvisioningId, kCertProfileId, _)); EXPECT_CALL(*mock_invalidator, Unregister()).Times(1); EXPECT_CALL( *platform_keys_service_, RemoveKey(TokenId::kUser, /*public_key_spki_der=*/GetPublicKey(), /*callback=*/_)) .Times(1) .WillOnce(RunOnceCallback<2>(Status::kSuccess)); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kFailed)) .Times(1); } worker.DoStep(); FastForwardBy(base::Seconds(1)); histogram_tester.ExpectBucketCount("ChromeOS.CertProvisioning.Result.User", CertProvisioningWorkerState::kFailed, 1); histogram_tester.ExpectBucketCount( "ChromeOS.CertProvisioning.Result.User", CertProvisioningWorkerState::kKeyRegistered, 1); histogram_tester.ExpectTotalCount("ChromeOS.CertProvisioning.Result.User", 2); } class PrefServiceObserver { public: PrefServiceObserver(PrefService* service, const char* pref_name) : service_(service), pref_name_(pref_name) { pref_change_registrar_.Init(service); pref_change_registrar_.Add( pref_name, base::BindRepeating(&PrefServiceObserver::OnPrefsChange, weak_factory_.GetWeakPtr())); } void OnPrefsChange() { const base::Value* pref_value = service_->Get(pref_name_); DCHECK(pref_value); OnPrefValueUpdated(*pref_value); } // Allows to add expectations about preference changes and verify new values. MOCK_METHOD(void, OnPrefValueUpdated, (const base::Value& value)); private: PrefService* service_ = nullptr; const char* pref_name_ = nullptr; PrefChangeRegistrar pref_change_registrar_; base::WeakPtrFactory<PrefServiceObserver> weak_factory_{this}; }; TEST_F(CertProvisioningWorkerTest, SerializationSuccess) { const base::TimeDelta kRenewalPeriod = base::Seconds(1200300); CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kRenewalPeriod); const CertScope kCertScope = CertScope::kUser; std::unique_ptr<MockCertProvisioningInvalidator> mock_invalidator_obj; MockCertProvisioningInvalidator* mock_invalidator = nullptr; MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); std::unique_ptr<CertProvisioningWorker> worker = CertProvisioningWorkerFactory::Get()->Create( kCertScope, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); StrictMock<PrefServiceObserver> pref_observer( &testing_pref_service_, GetPrefNameForSerialization(kCertScope)); base::Value pref_val; EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); // Prepare key, send start csr request. { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); pref_val = ParseJson(base::StringPrintf( R"({ "cert_profile_1": { "cert_profile": { "policy_version": "cert_profile_version_1", "name": "Certificate Profile 1", "profile_id": "cert_profile_1", "va_enabled": true, "renewal_period": 1200300 }, "cert_scope": 0, "invalidation_topic": "", "public_key": "%s", "state": 1 } })", kPublicKeyBase64)); EXPECT_CALL(pref_observer, OnPrefValueUpdated(IsJson(pref_val))).Times(1); EXPECT_START_CSR_NO_OP(ClientCertProvisioningStartCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); worker->DoStep(); } // Recreate worker. { testing::InSequence seq; mock_tpm_challenge_key = PrepareTpmChallengeKey(); EXPECT_CALL(*mock_tpm_challenge_key, RestorePreparedKeyState( attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), GetPublicKey(), /*profile=*/_)) .Times(1); worker = CertProvisioningWorkerFactory::Get()->Deserialize( kCertScope, GetProfile(), &testing_pref_service_, *pref_val.FindKeyOfType(kCertProfileId, base::Value::Type::DICTIONARY), &cloud_policy_client_, MakeInvalidator(&mock_invalidator), GetStateChangeCallback(), GetResultCallback()); } // Retry start csr request, receive response, try sign challenge. { testing::InSequence seq; EXPECT_START_CSR_OK( ClientCertProvisioningStartCsr(kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_), em::HashingAlgorithm::SHA256); pref_val = ParseJson("{}"); EXPECT_CALL(pref_observer, OnPrefValueUpdated(IsJson(pref_val))).Times(1); EXPECT_CALL(*mock_invalidator, Register(kInvalidationTopic, _)).Times(1); EXPECT_SIGN_CHALLENGE_OK(*mock_tpm_challenge_key, StartSignChallengeStep(kChallenge, /*callback=*/_)); EXPECT_REGISTER_KEY_OK(*mock_tpm_challenge_key, StartRegisterKeyStep); EXPECT_CALL( *key_permissions_manager_, AllowKeyForUsage(/*callback=*/_, KeyUsage::kCorporate, GetPublicKey())); EXPECT_SET_ATTRIBUTE_FOR_KEY_OK(SetAttributeForKey( TokenId::kUser, GetPublicKey(), KeyAttributeType::kCertificateProvisioningId, kCertProfileId, _)); EXPECT_SIGN_RSAPKC1_DIGEST_OK( SignRSAPKCS1Digest(::testing::Optional(TokenId::kUser), kDataToSign, GetPublicKey(), HashAlgorithm::HASH_ALGORITHM_SHA256, /*callback=*/_)); EXPECT_FINISH_CSR_OK(ClientCertProvisioningFinishCsr( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), kChallengeResponse, kSignature, /*callback=*/_)); pref_val = ParseJson(base::StringPrintf( R"({ "cert_profile_1": { "cert_profile": { "policy_version": "cert_profile_version_1", "name": "Certificate Profile 1", "profile_id": "cert_profile_1", "va_enabled": true, "renewal_period": 1200300 }, "cert_scope": 0, "invalidation_topic": "fake_invalidation_topic_1", "public_key": "%s", "state": 7 } })", kPublicKeyBase64)); EXPECT_CALL(pref_observer, OnPrefValueUpdated(IsJson(pref_val))).Times(1); EXPECT_DOWNLOAD_CERT_NO_OP(ClientCertProvisioningDownloadCert( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); worker->DoStep(); } // Recreate worker. { testing::InSequence seq; mock_invalidator_obj = MakeInvalidator(&mock_invalidator); EXPECT_CALL(*mock_invalidator, Register(kInvalidationTopic, _)).Times(1); mock_tpm_challenge_key = PrepareTpmChallengeKey(); EXPECT_CALL(*mock_tpm_challenge_key, RestorePreparedKeyState( attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), GetPublicKey(), /*profile=*/_)) .Times(1); worker = CertProvisioningWorkerFactory::Get()->Deserialize( kCertScope, GetProfile(), &testing_pref_service_, *pref_val.FindKeyOfType(kCertProfileId, base::Value::Type::DICTIONARY), &cloud_policy_client_, std::move(mock_invalidator_obj), GetStateChangeCallback(), GetResultCallback()); } // Retry download cert request, receive response, try import certificate. { testing::InSequence seq; EXPECT_DOWNLOAD_CERT_OK(ClientCertProvisioningDownloadCert( kCertScopeStrUser, kCertProfileId, kCertProfileVersion, GetPublicKey(), /*callback=*/_)); EXPECT_IMPORT_CERTIFICATE_OK( ImportCertificate(TokenId::kUser, /*certificate=*/_, /*callback=*/_)); pref_val = ParseJson("{}"); EXPECT_CALL(pref_observer, OnPrefValueUpdated(IsJson(pref_val))).Times(1); EXPECT_CALL(*mock_invalidator, Unregister()).Times(1); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kSucceeded)) .Times(1); worker->DoStep(); } } TEST_F(CertProvisioningWorkerTest, SerializationOnFailure) { const CertScope kCertScope = CertScope::kUser; CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); auto worker = CertProvisioningWorkerFactory::Get()->Create( kCertScope, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); PrefServiceObserver pref_observer(&testing_pref_service_, GetPrefNameForSerialization(kCertScope)); base::Value pref_val; EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_USER, /*will_register_key=*/true, GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); pref_val = ParseJson(base::StringPrintf( R"({ "cert_profile_1": { "cert_profile": { "policy_version": "cert_profile_version_1", "name": "Certificate Profile 1", "profile_id": "cert_profile_1", "va_enabled": true }, "cert_scope": 0, "invalidation_topic": "", "public_key": "%s", "state": 1 } })", kPublicKeyBase64)); EXPECT_CALL(pref_observer, OnPrefValueUpdated(IsJson(pref_val))).Times(1); EXPECT_START_CSR_CA_ERROR(ClientCertProvisioningStartCsr); pref_val = ParseJson("{}"); EXPECT_CALL(pref_observer, OnPrefValueUpdated(IsJson(pref_val))).Times(1); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kFailed)) .Times(1); } worker->DoStep(); FastForwardBy(base::Seconds(1)); VerifyDeleteKeyCalledOnce(kCertScope); } TEST_F(CertProvisioningWorkerTest, InformationalGetters) { const CertScope kCertScope = CertScope::kUser; CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); CertProvisioningWorkerImpl worker( kCertScope, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); { testing::InSequence seq; EXPECT_PREPARE_KEY_OK(*mock_tpm_challenge_key, StartPrepareKeyStep); EXPECT_START_CSR_TRY_LATER(ClientCertProvisioningStartCsr, base::Seconds(30).InMilliseconds()); worker.DoStep(); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kKeypairGenerated); EXPECT_EQ(worker.GetPreviousState(), CertProvisioningWorkerState::kInitState); EXPECT_EQ(worker.GetCertProfile(), cert_profile); EXPECT_EQ(worker.GetPublicKey(), GetPublicKey()); } { testing::InSequence seq; EXPECT_START_CSR_CA_ERROR(ClientCertProvisioningStartCsr); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kFailed)) .Times(1); worker.DoStep(); FastForwardBy(base::Seconds(1)); VerifyDeleteKeyCalledOnce(kCertScope); EXPECT_EQ(worker.GetState(), CertProvisioningWorkerState::kFailed); EXPECT_EQ(worker.GetPreviousState(), CertProvisioningWorkerState::kKeypairGenerated); EXPECT_EQ(worker.GetCertProfile(), cert_profile); EXPECT_EQ(worker.GetPublicKey(), GetPublicKey()); } } TEST_F(CertProvisioningWorkerTest, CancelDeviceWorker) { base::HistogramTester histogram_tester; const CertScope kCertScope = CertScope::kDevice; CertProfile cert_profile(kCertProfileId, kCertProfileName, kCertProfileVersion, /*is_va_enabled=*/true, kCertProfileRenewalPeriod); EXPECT_CALL(state_change_callback_observer_, StateChangeCallback) .Times(AtLeast(1)); MockTpmChallengeKeySubtle* mock_tpm_challenge_key = PrepareTpmChallengeKey(); auto worker = CertProvisioningWorkerFactory::Get()->Create( kCertScope, GetProfile(), &testing_pref_service_, cert_profile, &cloud_policy_client_, MakeInvalidator(), GetStateChangeCallback(), GetResultCallback()); EXPECT_CALL(callback_observer_, Callback).Times(0); PrefServiceObserver pref_observer(&testing_pref_service_, GetPrefNameForSerialization(kCertScope)); base::Value pref_val; { testing::InSequence seq; EXPECT_PREPARE_KEY_OK( *mock_tpm_challenge_key, StartPrepareKeyStep(attestation::AttestationKeyType::KEY_DEVICE, /*will_register_key=*/true, /*key_name=*/GetKeyName(kCertProfileId), /*profile=*/_, /*callback=*/_, /*signals=*/_)); pref_val = ParseJson(base::StringPrintf( R"({ "cert_profile_1": { "cert_profile": { "policy_version": "cert_profile_version_1", "name": "Certificate Profile 1", "profile_id": "cert_profile_1", "va_enabled": true }, "cert_scope": 1, "invalidation_topic": "", "public_key": "%s", "state": 1 } })", kPublicKeyBase64)); EXPECT_CALL(pref_observer, OnPrefValueUpdated(IsJson(pref_val))).Times(1); EXPECT_START_CSR_NO_OP(ClientCertProvisioningStartCsr); worker->DoStep(); } { pref_val = ParseJson("{}"); EXPECT_CALL(pref_observer, OnPrefValueUpdated(IsJson(pref_val))).Times(1); worker->Stop(CertProvisioningWorkerState::kCanceled); EXPECT_CALL(callback_observer_, Callback(cert_profile, CertProvisioningWorkerState::kCanceled)) .Times(1); FastForwardBy(base::Seconds(1)); VerifyDeleteKeyCalledOnce(kCertScope); } histogram_tester.ExpectUniqueSample("ChromeOS.CertProvisioning.Result.Device", CertProvisioningWorkerState::kCanceled, 1); } } // namespace } // namespace cert_provisioning } // namespace ash
39,201
1,056
<gh_stars>1000+ /* * 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.netbeans.modules.maven.newproject; import java.awt.Component; import java.io.IOException; import java.util.Collections; import java.util.Set; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.SwingUtilities; import javax.swing.event.ChangeListener; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.templates.TemplateRegistration; import org.netbeans.modules.maven.api.archetype.ArchetypeWizards; import static org.netbeans.modules.maven.newproject.Bundle.*; import org.openide.WizardDescriptor; import org.openide.awt.Actions; import org.openide.util.NbBundle.Messages; import org.openide.util.RequestProcessor; /** * *@author mkleint */ @TemplateRegistration(folder=ArchetypeWizards.TEMPLATE_FOLDER, position=1000, displayName="#template.existing", iconBase="org/netbeans/modules/maven/resources/Maven2Icon.gif", description="ExistingDescription.html") @Messages("template.existing=Project with Existing POM") public class ExistingWizardIterator implements WizardDescriptor.ProgressInstantiatingIterator { private static final long serialVersionUID = 1L; private transient int index; private transient WizardDescriptor.Panel[] panels; private WizardDescriptor.Panel[] createPanels() { return new WizardDescriptor.Panel[] { new UseOpenWizardPanel() }; } @Messages("LBL_UseOpenStep=Existing Project") private String[] createSteps() { return new String[] { LBL_UseOpenStep(), }; } @Override public Set/*<FileObject>*/ instantiate() throws IOException { assert false : "Cannot call this method if implements WizardDescriptor.ProgressInstantiatingIterator."; //NOI18N return null; } @Override public Set instantiate(ProgressHandle handle) throws IOException { try { handle.start(2); handle.progress(1); RequestProcessor.getDefault().post(new Runnable() { @Override public void run() { tryOpenProject(); } }); return Collections.EMPTY_SET; } finally { handle.finish(); } } private void tryOpenProject() { final Action act = Actions.forID("Project", "org.netbeans.modules.project.ui.OpenProject"); //NOI18N if (act != null) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { act.actionPerformed(null); } }); } } @Override public void initialize(WizardDescriptor wiz) { index = 0; wiz.putProperty ("NewProjectWizard_Title", template_existing()); // NOI18N panels = createPanels(); // Make sure list of steps is accurate. String[] steps = createSteps(); for (int i = 0; i < panels.length; i++) { Component c = panels[i].getComponent(); if (steps[i] == null) { // Default step name to component name of panel. // Mainly useful for getting the name of the target // chooser to appear in the list of steps. steps[i] = c.getName(); } if (c instanceof JComponent) { // assume Swing components JComponent jc = (JComponent) c; // Step #. jc.putClientProperty("WizardPanel_contentSelectedIndex", new Integer(i)); //NOI18N // Step name (actually the whole list for reference). jc.putClientProperty("WizardPanel_contentData", steps); //NOI18N } } } @Override public void uninitialize(WizardDescriptor wiz) { panels = null; } @Messages({"# {0} - index", "# {1} - length", "MSG_One_of_Many={0} of {1}"}) @Override public String name() { return MSG_One_of_Many(index + 1, panels.length); } @Override public boolean hasNext() { return false; } @Override public boolean hasPrevious() { return false; } @Override public void nextPanel() { } @Override public void previousPanel() { } @Override public WizardDescriptor.Panel current() { return panels[index]; } // If nothing unusual changes in the middle of the wizard, simply: @Override public final void addChangeListener(ChangeListener l) {} @Override public final void removeChangeListener(ChangeListener l) {} }
2,205
7,482
/* * Copyright (c) 2010-2012, Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of Freescale Semiconductor, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*! * @file spdif_playback.c * @brief SPDIF test example * */ #include <stdio.h> #include "sdk.h" #include "audio/audio.h" extern audio_card_t snd_card_spdif; int32_t spdif_playback(audio_pcm_p pcm_file) { uint8_t recvCh; int32_t result; uint32_t bytes_written = 0; audio_dev_para_t dev_para; audio_card_p snd_card = &snd_card_spdif; printf("Please make sure : \n"); printf(" 1. The EVB board was mounted on the MX6QVPC board. \n"); printf (" 2. A rework should be done to connect \"TP6[SPDIF_OUT]\" with \"PORT2_P98\" on the MX6QVPC board\n"); printf (" 3. The \"SPDIF_OUT\" socket is connected with a SPDIF recording device, such as \"M-AUDIO\".\n"); if (!is_input_char('y', NULL)) { printf(" skip AUDIO test \n"); return TEST_BYPASSED; } dev_para.bus_mode = AUDIO_BUS_MODE_SLAVE; dev_para.bus_protocol = AUDIO_BUS_PROTOCOL_I2S; dev_para.sample_rate = pcm_file->para->sample_rate; dev_para.word_length = pcm_file->para->word_length; dev_para.trans_dir = AUDIO_TRANS_DIR_TX; if (0 != snd_card->ops->init(snd_card)) { printf("Init %s failed.\n", snd_card->name); return -1; } if (0 != snd_card->ops->config(snd_card, &dev_para)) { printf("Configure %s failed.\n", snd_card->name); return -1; } uint32_t cnt; while (1) { cnt = 2; while (cnt--) { snd_card->ops->write(snd_card, pcm_file->buf, pcm_file->size, &bytes_written); } printf(" Do you need to re-play it? (y/n)\n"); do { recvCh = getchar(); } while (recvCh == (uint8_t) 0xFF); if ((recvCh == 'Y') || (recvCh == 'y')) continue; /* hear again */ else break; /* by pass */ } printf(" Please replay the audio file just recorded on your PC. Do you hear audio? (y/n)\n"); do { recvCh = getchar(); } while (recvCh == (uint8_t) 0xFF); if ((recvCh == 'y') || (recvCh == 'Y')) result = 0; /* If user types 'Y' or 'y' test passed */ else result = -1; /* Else test failed */ return result; return true; }
1,553
314
<filename>Multiplex/IDEHeaders/IDEHeaders/IDEKit/IDEInspectorColorProperty.h // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "CDStructures.h" #import <IDEKit/IDEInspectorProperty.h> @class DVTColorPickerPopUpButton, IDEInspectorKeyPath, NSColor, NSString, NSTextField; @interface IDEInspectorColorProperty : IDEInspectorProperty { IDEInspectorKeyPath *_defaultColorKeyPath; IDEInspectorKeyPath *_supportsNilKeyPath; IDEInspectorKeyPath *_valueKeyPath; IDEInspectorKeyPath *_colorListKeyPath; NSColor *_defaultColor; BOOL _targettingCIColor; BOOL _defaultColorForNil; NSString *_title; DVTColorPickerPopUpButton *_popUpButton; NSTextField *_label; } @property(retain, nonatomic) NSTextField *label; // @synthesize label=_label; @property(retain, nonatomic) DVTColorPickerPopUpButton *popUpButton; // @synthesize popUpButton=_popUpButton; - (void)userDidChangeValue:(id)arg1; - (void)refresh; - (id)valueFromColor:(id)arg1; - (id)colorFromValue:(id)arg1; - (void)setupRefreshTriggersAndConfigure; - (id)nibName; - (double)baseline; - (id)initWithPropertyDefinition:(id)arg1 andController:(id)arg2; @end
479
534
<gh_stars>100-1000 { "variants": { "active=false": { "model": "mekanism:block/induction/port" }, "active=true": { "model": "mekanism:block/induction/port_output" } } }
96
1,165
/******************************************************************************* * Copyright 2018 T Mobile, Inc. or its affiliates. All Rights Reserved. * * 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.tmobile.pacman.api.admin.service; import static com.tmobile.pacman.api.admin.common.AdminConstants.UNEXPECTED_ERROR_OCCURRED; import java.io.File; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.tmobile.pacman.api.admin.util.AdminUtils; /** * AwsS3Bucket Service Implementations */ @Service public class AwsS3BucketService { private static final Logger log = LoggerFactory.getLogger(AwsS3BucketService.class); public boolean uploadFile(final AmazonS3 amazonS3, MultipartFile fileToUpload, String s3BucketName, String key) { try { File file = AdminUtils.convert(fileToUpload); long size = fileToUpload.getSize(); String contentType = fileToUpload.getContentType(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType(contentType); metadata.setContentLength(size); PutObjectRequest putObjectRequest = new PutObjectRequest(s3BucketName, key, file).withCannedAcl(CannedAccessControlList.PublicRead); amazonS3.putObject(putObjectRequest); return Boolean.TRUE; } catch (IOException exception) { log.error(UNEXPECTED_ERROR_OCCURRED, exception); } return Boolean.FALSE; } }
696
2,381
package io.jenkins.plugins.casc; import io.jenkins.plugins.casc.misc.ConfiguredWithReadme; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithReadmeRule; import jenkins.plugins.git.GitSCMSource; import org.jenkinsci.plugins.workflow.libs.GlobalLibraries; import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration; import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever; import org.junit.Rule; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author <a href="mailto:<EMAIL>"><NAME></a> */ public class WorkflowCpsGlobalLibTest { @Rule public JenkinsConfiguredWithReadmeRule j2 = new JenkinsConfiguredWithReadmeRule(); @Test @ConfiguredWithReadme("workflow-cps-global-lib/README.md") public void configure_global_library() { assertEquals(1, GlobalLibraries.get().getLibraries().size()); final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0); assertEquals("awesome-lib", library.getName()); final SCMSourceRetriever retriever = (SCMSourceRetriever) library.getRetriever(); final GitSCMSource scm = (GitSCMSource) retriever.getScm(); assertEquals("https://github.com/jenkins-infra/pipeline-library.git", scm.getRemote()); } }
462
2,151
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_NOTIFICATIONS_STUB_ALERT_DISPATCHER_MAC_H_ #define CHROME_BROWSER_NOTIFICATIONS_STUB_ALERT_DISPATCHER_MAC_H_ #import <Foundation/Foundation.h> #include <string> #include "chrome/browser/notifications/alert_dispatcher_mac.h" @interface StubAlertDispatcher : NSObject<AlertDispatcher> - (void)dispatchNotification:(NSDictionary*)data; - (void)closeNotificationWithId:(NSString*)notificationId withProfileId:(NSString*)profileId; - (void)closeAllNotifications; - (void) getDisplayedAlertsForProfileId:(NSString*)profileId incognito:(BOOL)incognito notificationCenter:(NSUserNotificationCenter*)notificationCenter callback:(GetDisplayedNotificationsCallback)callback; // Stub specific methods. - (NSArray*)alerts; @end #endif // CHROME_BROWSER_NOTIFICATIONS_STUB_ALERT_DISPATCHER_MAC_H_
397
369
/** @file @brief Header @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. #ifndef INCLUDED_ResolveFullTree_h_GUID_FBD87E7F_9F4B_43A3_4628_9F3E7D0187D7 #define INCLUDED_ResolveFullTree_h_GUID_FBD87E7F_9F4B_43A3_4628_9F3E7D0187D7 // Internal Includes #include <osvr/Common/PathTree_fwd.h> #include <osvr/Common/Export.h> // Library/third-party includes // - none // Standard includes #include <vector> #include <string> namespace osvr { namespace common { /// @brief Traverse the given path tree, resolving all aliases found to /// fully populate any generated sensor targets. /// /// @return A vector of paths that are aliases that could not be resolved. OSVR_COMMON_EXPORT std::vector<std::string> resolveFullTree(PathTree &tree); } // namespace common } // namespace osvr #endif // INCLUDED_ResolveFullTree_h_GUID_FBD87E7F_9F4B_43A3_4628_9F3E7D0187D7
518
1,652
package com.ctrip.xpipe.redis.core.protocal.cmd.pubsub; import com.ctrip.xpipe.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author chen.zhu * <p> * Apr 04, 2018 */ public class DefaultSubscribeMessageHandler extends AbstractSubscribeMessageHandler { private static final Logger logger = LoggerFactory.getLogger(DefaultSubscribeMessageHandler.class); @Override protected Pair<String, String> doHandle(String[] subscribeChannelResponse) { String flag = subscribeChannelResponse[0]; if(!Subscribe.MESSAGE_TYPE.MESSAGE.matches(flag)) { logger.error("[doHandle] Subscribe message not correct: {}", subscribeChannelResponse); return null; } return new Pair<>(subscribeChannelResponse[1], subscribeChannelResponse[2]); } }
292
1,907
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2020 <NAME>, The appleseedhq Organization // // 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. // // Interface header. #include "chromaticaberrationpostprocessingstage.h" // appleseed.renderer headers. #include "renderer/modeling/frame/frame.h" #include "renderer/modeling/postprocessingstage/effect/chromaticaberrationapplier.h" #include "renderer/modeling/postprocessingstage/postprocessingstage.h" // appleseed.foundation headers. #include "foundation/containers/dictionary.h" #include "foundation/image/canvasproperties.h" #include "foundation/image/image.h" #include "foundation/math/scalar.h" #include "foundation/math/vector.h" #include "foundation/utility/api/specializedapiarrays.h" // Standard headers. #include <cstddef> #include <memory> using namespace foundation; namespace renderer { namespace { // // Chromatic aberration post-processing stage. // const char* Model = "chromatic_aberration_post_processing_stage"; constexpr float DefaultStrength = 0.4f; constexpr std::size_t DefaultSampleCount = 3; class ChromaticAberrationPostProcessingStage : public PostProcessingStage { public: ChromaticAberrationPostProcessingStage( const char* name, const ParamArray& params) : PostProcessingStage(name, params) { } void release() override { delete this; } const char* get_model() const override { return Model; } bool on_frame_begin( const Project& project, const BaseGroup* parent, OnFrameBeginRecorder& recorder, IAbortSwitch* abort_switch) override { const OnFrameBeginMessageContext context("post-processing stage", this); m_strength = m_params.get_optional("strength", DefaultStrength, context); m_sample_count = 2 + m_params.get_optional("fringe_smoothness", DefaultSampleCount - 2, context); // >= 3 return true; } void execute(Frame& frame, const std::size_t thread_count) const override { // Skip chromatic aberration if strength is zero. if (m_strength == 0.0f) return; // Apply the effect onto each image tile, in parallel. const ChromaticAberrationApplier chromatic_aberration( frame.image(), m_strength, m_sample_count); chromatic_aberration.apply_on_tiles(frame.image(), thread_count); } private: float m_strength; std::size_t m_sample_count; }; } // // ChromaticAberrationPostProcessingStageFactory class implementation. // void ChromaticAberrationPostProcessingStageFactory::release() { delete this; } const char* ChromaticAberrationPostProcessingStageFactory::get_model() const { return Model; } Dictionary ChromaticAberrationPostProcessingStageFactory::get_model_metadata() const { return Dictionary() .insert("name", Model) .insert("label", "Chromatic Aberration"); } DictionaryArray ChromaticAberrationPostProcessingStageFactory::get_input_metadata() const { DictionaryArray metadata; add_common_input_metadata(metadata); metadata.push_back( Dictionary() .insert("name", "strength") .insert("label", "Strength") .insert("type", "numeric") .insert("min", Dictionary() .insert("value", "0.0") .insert("type", "hard")) .insert("max", Dictionary() .insert("value", "1.0") .insert("type", "hard")) .insert("use", "optional") .insert("default", "0.4")); metadata.push_back( Dictionary() .insert("name", "fringe_smoothness") .insert("label", "Fringe Smoothness") .insert("type", "integer") .insert("min", Dictionary() .insert("value", "1") .insert("type", "hard")) .insert("max", Dictionary() .insert("value", "20") .insert("type", "soft")) .insert("use", "optional") .insert("default", "6")); return metadata; } auto_release_ptr<PostProcessingStage> ChromaticAberrationPostProcessingStageFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<PostProcessingStage>( new ChromaticAberrationPostProcessingStage(name, params)); } } // namespace renderer
2,439
663
# (C) Datadog, Inc. 2019-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import os from copy import deepcopy import prestodb import pytest from datadog_checks.dev import docker_run, get_here from datadog_checks.dev.conditions import CheckDockerLogs, WaitFor from datadog_checks.dev.utils import load_jmx_config @pytest.fixture(scope='session') def dd_environment(instance): compose_file = os.path.join(get_here(), 'docker', 'docker-compose.yaml') with docker_run(compose_file, conditions=[WaitFor(make_query), CheckDockerLogs(compose_file, 'SERVER STARTED')]): yield instance, {'use_jmx': True} def make_query(): # make a query so that all metrics are emitted in the e2e test conn = prestodb.dbapi.connect( host='localhost', port=8080, user='test', catalog='test', schema='test', ) cur = conn.cursor() cur.execute('SELECT * FROM system.runtime.nodes') cur.fetchall() @pytest.fixture(scope='session', autouse=True) @pytest.mark.usefixtures('dd_environment') def instance(): inst = load_jmx_config() # Add presto coordinator to the configuration inst.get('instances').append(deepcopy(inst.get('instances')[0])) inst['instances'][0]['port'] = 9997 return inst
486
1,121
<filename>gita/common.py import os def get_config_dir(root=None) -> str: if root is None: root = os.environ.get('XDG_CONFIG_HOME') or os.path.join( os.path.expanduser('~'), '.config') return os.path.join(root, "gita") else: return os.path.join(root, ".gita") def get_config_fname(fname: str, root=None) -> str: """ Return the file name that stores the repo locations. """ return os.path.join(get_config_dir(root), fname)
212
4,339
<reponame>vvteplygin/ignite<gh_stars>1000+ /* * 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.ignite.internal.visor.verify; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.compute.ComputeJobContext; import org.apache.ignite.compute.ComputeTask; import org.apache.ignite.compute.ComputeTaskFuture; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.visor.VisorJob; import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.lang.IgniteInClosure; import org.apache.ignite.resources.JobContextResource; import org.apache.ignite.resources.LoggerResource; /** * */ class VisorIdleVerifyJob<ResultT> extends VisorJob<VisorIdleVerifyTaskArg, ResultT> { /** */ private static final long serialVersionUID = 0L; /** */ private ComputeTaskFuture<ResultT> fut; /** Auto-inject job context. */ @JobContextResource protected transient ComputeJobContext jobCtx; /** Injected logger. */ @LoggerResource private IgniteLogger log; /** Task class for execution */ private final Class<? extends ComputeTask<VisorIdleVerifyTaskArg, ResultT>> taskCls; /** * @param arg Argument. * @param debug Debug. * @param taskCls Task class for execution. */ VisorIdleVerifyJob( VisorIdleVerifyTaskArg arg, boolean debug, Class<? extends ComputeTask<VisorIdleVerifyTaskArg, ResultT>> taskCls ) { super(arg, debug); this.taskCls = taskCls; } /** {@inheritDoc} */ @Override protected ResultT run(VisorIdleVerifyTaskArg arg) throws IgniteException { if (fut == null) { fut = ignite.compute().executeAsync(taskCls, arg); if (!fut.isDone()) { jobCtx.holdcc(); fut.listen((IgniteInClosure<IgniteFuture<ResultT>>)f -> jobCtx.callcc()); return null; } } return fut.get(); } /** {@inheritDoc} */ @Override public void cancel() { log.warning("Idle verify was cancelled."); super.cancel(); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(VisorIdleVerifyJob.class, this); } }
1,102
323
<filename>spot_bullet/src/sac_lib/__init__.py from .sac import SoftActorCritic from .policynetwork import PolicyNetwork from .replay_buffer import ReplayBuffer from .normalized_actions import NormalizedActions
62
335
<reponame>Safal08/Hacktoberfest-1<gh_stars>100-1000 { "word": "Relay", "definitions": [ "Receive and pass on (information or a message)", "Broadcast (something) by passing signals received from elsewhere through a transmitting station." ], "parts-of-speech": "Verb" }
113
2,879
<gh_stars>1000+ /* * Copyright (C) 2016 <NAME> * * 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.github.nisrulz.sensey; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.util.Log; public class SoundLevelDetector { public interface SoundLevelListener { void onSoundDetected(float level); } private static final String LOGTAG = "SoundLevelDetector"; private final int SAMPLE_RATE; private final int audioChannel = AudioFormat.CHANNEL_IN_MONO; private final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT; private Thread audioRecordingThread = null; private final int audioSource = MediaRecorder.AudioSource.VOICE_RECOGNITION; private int bufferSize; private boolean shouldContinueProcessingAudio; private SoundLevelListener soundLevelListener; private final Runnable audioRecordRunnable = new Runnable() { @Override public void run() { // Setup thread priority android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO); if (SAMPLE_RATE == 0 || bufferSize == 0) { Log.e(LOGTAG, "Invalid SampleRate/BufferSize! AudioRecord cannot be initialized. Exiting!"); return; } // If there was an error if (bufferSize == AudioRecord.ERROR || bufferSize == AudioRecord.ERROR_BAD_VALUE) { bufferSize = SAMPLE_RATE * 2; } short[] audioBuffer = new short[bufferSize / 2]; AudioRecord audioRecord = new AudioRecord(audioSource, SAMPLE_RATE, audioChannel, audioEncoding, bufferSize); if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) { Log.e(LOGTAG, "AudioRecord could not be initialized. Exiting!"); return; } // start recording audioRecord.startRecording(); shouldContinueProcessingAudio = true; long shortsRead = 0; while (shouldContinueProcessingAudio) { // Read the recorded data from audio buffer int numberOfShort = audioRecord.read(audioBuffer, 0, audioBuffer.length); shortsRead += numberOfShort; double sumLevel = 0; for (int i = 0; i < numberOfShort; i++) { sumLevel += audioBuffer[i] / 32768.0; } // calculate the sound level double rms = Math.sqrt(Math.abs(sumLevel / numberOfShort)); float soundLevel = (float) (20.0 * Math.log10(rms)); // Check that the value is neither NaN nor infinite if (!Float.isNaN(soundLevel) && !Float.isInfinite(soundLevel) && shouldContinueProcessingAudio) { // since 0db is the max loudness and negative values are used to represent the loudness // if we add 100 to the actual soundlevel, it will result in values on a scale of 0 to 100 // The more negative the value will be +100 would yield a lower value on the scale of 0-100 // and would mean that sound is of lesser loudness and vice versa soundLevel = soundLevel + 100f; // only then pass it to the listener soundLevelListener.onSoundDetected(soundLevel); } } // stop recording and release the microphone try { if (audioRecord != null) { audioRecord.stop(); } } catch (Exception e) { e.printStackTrace(); } finally { if (audioRecord != null) { audioRecord.release(); audioRecord = null; } } } }; public SoundLevelDetector(SoundLevelListener soundLevelListener) { this.soundLevelListener = soundLevelListener; // Get valid sample rate and bufferSize SAMPLE_RATE = getValidSampleRates(audioChannel, audioEncoding); bufferSize = getValidBufferSize(audioSource, SAMPLE_RATE, audioChannel, audioEncoding); } void start() { if (audioRecordingThread == null) { audioRecordingThread = new Thread(audioRecordRunnable); audioRecordingThread.start(); } else if (audioRecordingThread.isAlive()) { stopThreadAndProcessing(); audioRecordingThread = new Thread(audioRecordRunnable); audioRecordingThread.start(); } } void stop() { stopThreadAndProcessing(); soundLevelListener = null; } private int getValidBufferSize(int audioSource, int fs, int channelConfiguration, int audioEncoding) { for (int bufferSize : new int[]{ 256, 512, 1024, 2048, 4096 }) { // add the rates you wish to check against AudioRecord audioRecordTemp = new AudioRecord(audioSource, fs, channelConfiguration, audioEncoding, bufferSize); if (audioRecordTemp != null && audioRecordTemp.getState() == AudioRecord.STATE_INITIALIZED) { return bufferSize; } } return 0; } private int getValidSampleRates(int channelConfiguration, int audioEncoding) { for (int rate : new int[]{ 8000, 11025, 16000, 22050, 44100, 48000 }) { // add the rates you wish to check against int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfiguration, audioEncoding); if (bufferSize > 0) { return rate; } } return 0; } private void stopThreadAndProcessing() { // Stop audio processing shouldContinueProcessingAudio = false; // interrupt the thread if (audioRecordingThread != null) { audioRecordingThread.interrupt(); audioRecordingThread = null; } } }
2,836
2,151
// Copyright (c) 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #define VK_USE_PLATFORM_XLIB_KHR #include "gpu/vulkan/x/vulkan_implementation_x11.h" #include "gpu/vulkan/vulkan_instance.h" #include "gpu/vulkan/vulkan_surface.h" #include "ui/gfx/x/x11_types.h" namespace gpu { VulkanImplementationX11::VulkanImplementationX11() : VulkanImplementationX11(gfx::GetXDisplay()) {} VulkanImplementationX11::VulkanImplementationX11(XDisplay* x_display) : x_display_(x_display) {} VulkanImplementationX11::~VulkanImplementationX11() {} bool VulkanImplementationX11::InitializeVulkanInstance() { std::vector<const char*> required_extensions; required_extensions.push_back(VK_KHR_XLIB_SURFACE_EXTENSION_NAME); if (!vulkan_instance_.Initialize(required_extensions)) { vulkan_instance_.Destroy(); return false; } return true; } VkInstance VulkanImplementationX11::GetVulkanInstance() { return vulkan_instance_.vk_instance(); } std::unique_ptr<VulkanSurface> VulkanImplementationX11::CreateViewSurface( gfx::AcceleratedWidget window) { VkSurfaceKHR surface; VkXlibSurfaceCreateInfoKHR surface_create_info = {}; surface_create_info.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; surface_create_info.dpy = x_display_; surface_create_info.window = window; VkResult result = vkCreateXlibSurfaceKHR( GetVulkanInstance(), &surface_create_info, nullptr, &surface); if (VK_SUCCESS != result) { DLOG(ERROR) << "vkCreateXlibSurfaceKHR() failed: " << result; return nullptr; } return std::make_unique<VulkanSurface>(GetVulkanInstance(), surface); } bool VulkanImplementationX11::GetPhysicalDevicePresentationSupport( VkPhysicalDevice device, const std::vector<VkQueueFamilyProperties>& queue_family_properties, uint32_t queue_family_index) { return vkGetPhysicalDeviceXlibPresentationSupportKHR( device, queue_family_index, x_display_, XVisualIDFromVisual( DefaultVisual(x_display_, DefaultScreen(x_display_)))); } } // namespace gpu
762
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.password_entry_edit; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditMediator.BLOCKED_CREDENTIAL_ACTION_HISTOGRAM; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditMediator.CredentialEditError.DUPLICATE_USERNAME; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditMediator.CredentialEditError.EMPTY_PASSWORD; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditMediator.EDIT_ERROR_HISTOGRAM; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditMediator.FEDERATED_CREDENTIAL_ACTION_HISTOGRAM; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditMediator.SAVED_PASSWORD_ACTION_HISTOGRAM; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditProperties.ALL_KEYS; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditProperties.DUPLICATE_USERNAME_ERROR; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditProperties.EMPTY_PASSWORD_ERROR; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditProperties.FEDERATION_ORIGIN; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditProperties.PASSWORD; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditProperties.PASSWORD_VISIBLE; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditProperties.UI_ACTION_HANDLER; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditProperties.UI_DISMISSED_BY_NATIVE; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditProperties.URL_OR_APP; import static org.chromium.chrome.browser.password_entry_edit.CredentialEditProperties.USERNAME; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.res.Resources; import androidx.test.core.app.ApplicationProvider; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.annotation.Config; import org.chromium.base.Callback; import org.chromium.base.metrics.RecordHistogram; import org.chromium.base.metrics.test.ShadowRecordHistogram; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.password_entry_edit.CredentialEditCoordinator.CredentialActionDelegate; import org.chromium.chrome.browser.password_entry_edit.CredentialEditMediator.CredentialEntryAction; import org.chromium.chrome.browser.password_manager.ConfirmationDialogHelper; import org.chromium.chrome.browser.password_manager.settings.PasswordAccessReauthenticationHelper; import org.chromium.chrome.browser.password_manager.settings.PasswordAccessReauthenticationHelper.ReauthReason; import org.chromium.ui.modelutil.PropertyModel; /** * Tests verifying that the credential edit mediator modifies the model correctly. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = {ShadowRecordHistogram.class}) public class CredentialEditControllerTest { private static final String TEST_URL = "https://m.a.xyz/signin"; private static final String TEST_USERNAME = "TestUsername"; private static final String NEW_TEST_USERNAME = "TestNewUsername"; private static final String TEST_PASSWORD = "<PASSWORD>"; private static final String NEW_TEST_PASSWORD = "<PASSWORD>"; @Mock private PasswordAccessReauthenticationHelper mReauthenticationHelper; @Mock private ConfirmationDialogHelper mDeleteDialogHelper; @Mock private CredentialActionDelegate mCredentialActionDelegate; @Mock private Runnable mHelpLauncher; CredentialEditMediator mMediator; PropertyModel mModel; @Before public void setUp() { MockitoAnnotations.initMocks(this); mMediator = new CredentialEditMediator(mReauthenticationHelper, mDeleteDialogHelper, mCredentialActionDelegate, mHelpLauncher, false); mModel = new PropertyModel.Builder(ALL_KEYS) .with(UI_ACTION_HANDLER, mMediator) .with(URL_OR_APP, TEST_URL) .with(FEDERATION_ORIGIN, "") .build(); mMediator.initialize(mModel); } @Test public void testSetsCredential() { mMediator.setCredential(TEST_USERNAME, TEST_PASSWORD, false); assertEquals(TEST_USERNAME, mModel.get(USERNAME)); assertEquals(TEST_PASSWORD, mModel.get(PASSWORD)); assertFalse(mModel.get(PASSWORD_VISIBLE)); } @Test public void testDismissPropagatesToTheModel() { mMediator.dismiss(); assertTrue(mModel.get(UI_DISMISSED_BY_NATIVE)); } @Test public void testMaskingWithoutReauth() { mModel.set(PASSWORD_VISIBLE, true); mMediator.onMaskOrUnmaskPassword(); verify(mReauthenticationHelper, never()).canReauthenticate(); verify(mReauthenticationHelper, never()).reauthenticate(anyInt(), any(Callback.class)); } @Test public void testCannotReauthPromptsToast() { when(mReauthenticationHelper.canReauthenticate()).thenReturn(false); mModel.set(PASSWORD_VISIBLE, false); mMediator.onMaskOrUnmaskPassword(); verify(mReauthenticationHelper).showScreenLockToast(eq(ReauthReason.VIEW_PASSWORD)); verify(mReauthenticationHelper, never()).reauthenticate(anyInt(), any(Callback.class)); } @Test public void testUnmaskTriggersReauthenticate() { when(mReauthenticationHelper.canReauthenticate()).thenReturn(true); mModel.set(PASSWORD_VISIBLE, false); mMediator.onMaskOrUnmaskPassword(); verify(mReauthenticationHelper) .reauthenticate(eq(ReauthReason.VIEW_PASSWORD), any(Callback.class)); } @Test public void testCannotUnmaskIfReauthFailed() { when(mReauthenticationHelper.canReauthenticate()).thenReturn(true); mModel.set(PASSWORD_VISIBLE, false); doAnswer((invocation) -> { Callback callback = (Callback) invocation.getArguments()[1]; callback.onResult(false); return null; }) .when(mReauthenticationHelper) .reauthenticate(eq(ReauthReason.VIEW_PASSWORD), any(Callback.class)); mMediator.onMaskOrUnmaskPassword(); verify(mReauthenticationHelper) .reauthenticate(eq(ReauthReason.VIEW_PASSWORD), any(Callback.class)); assertFalse(mModel.get(PASSWORD_VISIBLE)); } @Test public void testCopyPasswordTriggersReauth() { when(mReauthenticationHelper.canReauthenticate()).thenReturn(true); mMediator.onCopyPassword(ApplicationProvider.getApplicationContext()); verify(mReauthenticationHelper) .reauthenticate(eq(ReauthReason.COPY_PASSWORD), any(Callback.class)); } @Test public void testCantCopyPasswordIfReauthFails() { mModel.set(PASSWORD, <PASSWORD>); when(mReauthenticationHelper.canReauthenticate()).thenReturn(true); doAnswer((invocation) -> { Callback callback = (Callback) invocation.getArguments()[1]; callback.onResult(false); return null; }) .when(mReauthenticationHelper) .reauthenticate(eq(ReauthReason.COPY_PASSWORD), any(Callback.class)); Context context = ApplicationProvider.getApplicationContext(); mMediator.onCopyPassword(context); verify(mReauthenticationHelper) .reauthenticate(eq(ReauthReason.COPY_PASSWORD), any(Callback.class)); ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); assertNull(clipboard.getPrimaryClip()); } @Test public void testCanCopyPasswordIfReauthSucceeds() { mModel.set(PASSWORD, <PASSWORD>); when(mReauthenticationHelper.canReauthenticate()).thenReturn(true); doAnswer((invocation) -> { Callback callback = (Callback) invocation.getArguments()[1]; callback.onResult(true); return null; }) .when(mReauthenticationHelper) .reauthenticate(eq(ReauthReason.COPY_PASSWORD), any(Callback.class)); Context context = ApplicationProvider.getApplicationContext(); mMediator.onCopyPassword(context); ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); ClipData expectedClip = ClipData.newPlainText("password", <PASSWORD>); assertEquals(expectedClip.toString(), clipboard.getPrimaryClip().toString()); } @Test public void callsTheDelegateWithCorrectDataWhenSaving() { mModel.set(USERNAME, TEST_USERNAME); mModel.set(PASSWORD, <PASSWORD>); mMediator.onSave(); verify(mCredentialActionDelegate).saveChanges(TEST_USERNAME, TEST_PASSWORD); } @Test public void testUsernameTextChangedUpdatesModel() { mMediator.setCredential(TEST_USERNAME, TEST_PASSWORD, false); mMediator.setExistingUsernames(new String[] {TEST_USERNAME}); mMediator.onUsernameTextChanged(NEW_TEST_USERNAME); assertEquals(NEW_TEST_USERNAME, mModel.get(USERNAME)); } @Test public void testPasswordTextChangedUpdatesModel() { mMediator.setCredential(TEST_USERNAME, TEST_PASSWORD, false); mMediator.onPasswordTextChanged(<PASSWORD>); assertEquals(NEW_TEST_PASSWORD, mModel.get(PASSWORD)); } @Test public void testEmptyPasswordTriggersError() { mMediator.setCredential(TEST_USERNAME, TEST_PASSWORD, false); mMediator.onPasswordTextChanged(""); assertTrue(mModel.get(EMPTY_PASSWORD_ERROR)); assertThat(RecordHistogram.getHistogramValueCountForTesting( EDIT_ERROR_HISTOGRAM, EMPTY_PASSWORD), is(1)); mMediator.onPasswordTextChanged(<PASSWORD>_PASSWORD); assertFalse(mModel.get(EMPTY_PASSWORD_ERROR)); } @Test public void testDuplicateUsernameTriggersError() { mMediator.setCredential(TEST_USERNAME, TEST_PASSWORD, false); mMediator.setExistingUsernames(new String[] {TEST_USERNAME, NEW_TEST_USERNAME}); mMediator.onUsernameTextChanged(NEW_TEST_USERNAME); assertTrue(mModel.get(DUPLICATE_USERNAME_ERROR)); assertThat(RecordHistogram.getHistogramValueCountForTesting( EDIT_ERROR_HISTOGRAM, DUPLICATE_USERNAME), is(1)); mMediator.onUsernameTextChanged(TEST_USERNAME); assertFalse(mModel.get(DUPLICATE_USERNAME_ERROR)); } @Test public void testDeletingCredentialPromptsConfirmation() { mMediator.setCredential(TEST_USERNAME, TEST_PASSWORD, false); Resources resources = ApplicationProvider.getApplicationContext().getResources(); when(mDeleteDialogHelper.getResources()).thenReturn(resources); String title = resources.getString(R.string.password_entry_edit_delete_credential_dialog_title); String message = resources.getString(R.string.password_entry_edit_deletion_dialog_body, TEST_URL); int confirmButtonTextId = R.string.password_entry_edit_delete_credential_dialog_confirm; doAnswer((invocation) -> { Runnable callback = (Runnable) invocation.getArguments()[3]; callback.run(); return null; }) .when(mDeleteDialogHelper) .showConfirmation( eq(title), eq(message), eq(confirmButtonTextId), any(Runnable.class)); mMediator.onDelete(); verify(mDeleteDialogHelper) .showConfirmation( eq(title), eq(message), eq(confirmButtonTextId), any(Runnable.class)); verify(mCredentialActionDelegate).deleteCredential(); assertThat(RecordHistogram.getHistogramValueCountForTesting( SAVED_PASSWORD_ACTION_HISTOGRAM, CredentialEntryAction.DELETED), is(1)); } @Test public void testDeletingCompromisedCredentialPromptsCorrectMessage() { mMediator.setCredential(TEST_USERNAME, TEST_PASSWORD, true); Resources resources = ApplicationProvider.getApplicationContext().getResources(); when(mDeleteDialogHelper.getResources()).thenReturn(resources); String title = resources.getString(R.string.password_entry_edit_delete_credential_dialog_title); String message = resources.getString( R.string.password_check_delete_credential_dialog_body, TEST_URL); int confirmButtonTextId = R.string.password_entry_edit_delete_credential_dialog_confirm; mMediator.onDelete(); verify(mDeleteDialogHelper) .showConfirmation( eq(title), eq(message), eq(confirmButtonTextId), any(Runnable.class)); } @Test public void testDeletingFederatedCredentialPromptsConfirmation() { initMediatorWithFederatedCredential(); mMediator.setCredential(TEST_USERNAME, "", false); Resources resources = ApplicationProvider.getApplicationContext().getResources(); when(mDeleteDialogHelper.getResources()).thenReturn(resources); String title = resources.getString(R.string.password_entry_edit_delete_credential_dialog_title); String message = resources.getString(R.string.password_entry_edit_deletion_dialog_body, TEST_URL); int confirmButtonTextId = R.string.password_entry_edit_delete_credential_dialog_confirm; doAnswer((invocation) -> { Runnable callback = (Runnable) invocation.getArguments()[3]; callback.run(); return null; }) .when(mDeleteDialogHelper) .showConfirmation( eq(title), eq(message), eq(confirmButtonTextId), any(Runnable.class)); mMediator.onDelete(); verify(mDeleteDialogHelper) .showConfirmation( eq(title), eq(message), eq(confirmButtonTextId), any(Runnable.class)); verify(mCredentialActionDelegate).deleteCredential(); assertThat(RecordHistogram.getHistogramValueCountForTesting( FEDERATED_CREDENTIAL_ACTION_HISTOGRAM, CredentialEntryAction.DELETED), is(1)); } @Test public void testDeletingBlockedCredentialDoesntPromptDialog() { mMediator = new CredentialEditMediator(mReauthenticationHelper, mDeleteDialogHelper, mCredentialActionDelegate, mHelpLauncher, true); mModel = new PropertyModel.Builder(ALL_KEYS) .with(UI_ACTION_HANDLER, mMediator) .with(URL_OR_APP, TEST_URL) .with(FEDERATION_ORIGIN, "") .build(); mMediator.initialize(mModel); mMediator.onDelete(); verify(mDeleteDialogHelper, never()).getResources(); verify(mDeleteDialogHelper, never()) .showConfirmation( any(String.class), any(String.class), anyInt(), any(Runnable.class)); verify(mCredentialActionDelegate).deleteCredential(); assertThat(RecordHistogram.getHistogramValueCountForTesting( BLOCKED_CREDENTIAL_ACTION_HISTOGRAM, CredentialEntryAction.DELETED), is(1)); } private void initMediatorWithFederatedCredential() { mModel = new PropertyModel.Builder(ALL_KEYS) .with(UI_ACTION_HANDLER, mMediator) .with(URL_OR_APP, TEST_URL) .with(FEDERATION_ORIGIN, "accounts.example.com") .build(); mMediator.initialize(mModel); } @Test public void testHandleHelpCallsHelpLauncher() { mMediator.handleHelp(); verify(mHelpLauncher).run(); } }
6,966
1,615
package com.immomo.mls; /** * Description: * Author: xuejingfei * E-mail: <EMAIL> * Date: 2020-03-19 12:15 */ public class User extends Person { private String name; public String getName() { return name; } public void setName(String name) { String old = this.name; this.name = name; notifyPropertyChanged("name",old,this.name); } } class Person extends PropertyObservable{ } class PropertyObservable { public void notifyPropertyChanged(String fieldName,Object older,Object newer) {} }
216
1,405
<filename>sample1/recompiled_java/sources/com/xxGameAssistant/utility/FileUtil.java package com.xxGameAssistant.utility; import android.annotation.SuppressLint; import android.content.Context; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class FileUtil { static Context mContext; static FileOutputStream mFileStream; static String mfileName; public FileUtil(Context context, String fileName) { mContext = context; mfileName = fileName; mFileStream = null; } public void fprintf(String content) { try { mFileStream = mContext.openFileOutput(mfileName, 32768); mFileStream.write(content.getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } } public void fflush() { try { mFileStream.flush(); } catch (IOException e) { e.printStackTrace(); } } @SuppressLint({"SimpleDateFormat"}) public void fclose() { try { if (mFileStream != null) { mFileStream.write(("==Terminated at " + new SimpleDateFormat("yyyy-MM-dd#HH:mm:ss").format(new Date()).toString() + "==\n\n").getBytes()); mFileStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }
674
578
/* * Copyright (c) 2003-2021 <NAME> <<EMAIL>>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ #ifndef _BITOPS_H #define _BITOPS_H // Following from libtomcrypt, for twofish & SHA256 /* Controls endianness and size of registers. Leave uncommented to get platform neutral [slower] code * * Note: in order to use the optimized macros your platform must support unaligned 32 and 64 bit read/writes. * The x86 platforms allow this but some others [ARM for instance] do not. On those platforms you **MUST** * use the portable [slower] macros. */ #ifndef _MSC_VER #include <stdint.h> #endif /* detect x86-32 machines somewhat */ #if defined(INTEL_CC) || (defined(_MSC_VER) && defined(WIN32)) || (defined(__GNUC__) && (defined(__DJGPP__) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__i386__))) #define ENDIAN_LITTLE #define ENDIAN_32BITWORD #endif /* detects MIPS R5900 processors (PS2) */ #if (defined(__R5900) || defined(R5900) || defined(__R5900__)) && (defined(_mips) || defined(__mips__) || defined(mips)) #define ENDIAN_LITTLE #define ENDIAN_64BITWORD #endif /* detect amd64 */ #if defined(__x86_64__) || defined(__amd64__) || (defined(_MSC_VER) && defined(WIN64)) #define ENDIAN_LITTLE #define ENDIAN_64BITWORD #endif /* detect loongarch64 */ #if defined(__loongarch64) #define ENDIAN_LITTLE #define ENDIAN_64BITWORD #endif /* #define ENDIAN_LITTLE */ /* #define ENDIAN_BIG */ /* #define ENDIAN_32BITWORD */ /* #define ENDIAN_64BITWORD */ #if (defined(ENDIAN_BIG) || defined(ENDIAN_LITTLE)) && !(defined(ENDIAN_32BITWORD) || defined(ENDIAN_64BITWORD)) #error You must specify a word size as well as endianness #endif #if !(defined(ENDIAN_BIG) || defined(ENDIAN_LITTLE)) #define ENDIAN_NEUTRAL #endif /* fix for MSVC ...evil! */ #ifdef _MSC_VER #define CONST64(n) n ## ui64 typedef unsigned __int64 ulong64; #else #define CONST64(n) n ## ULL typedef uint64_t ulong64; #endif /* this is the "32-bit at least" data type * Re-define it to suit your platform but it must be at least 32-bits */ #if defined(__x86_64__) typedef unsigned ulong32; #endif #if defined(__linux__) || defined(__CYGWIN__) || defined (macintosh) || defined(Macintosh) || defined(__APPLE__) || defined(__MACH__) || defined(__FreeBSD) || defined(__FreeBSD__) /* Following seems needed on Linux/cygwin and on macs to avoid "Impossible constraint in 'asm'" errors in ROLc() and RORc() functions below */ #define LTC_NO_ROLC #endif /* ---- HELPER MACROS ---- */ #ifdef ENDIAN_NEUTRAL #define STORE32L(x, y) \ { (y)[3] = static_cast<unsigned char>(((x)>>24)&255); (y)[2] = static_cast<unsigned char>(((x)>>16)&255); \ (y)[1] = static_cast<unsigned char>(((x)>>8)&255); (y)[0] = static_cast<unsigned char>((x)&255); } #define LOAD32L(x, y) \ { x = (static_cast<unsigned long>((y)[3] & 255)<<24) | \ (static_cast<unsigned long>((y)[2] & 255)<<16) | \ (static_cast<unsigned long>((y)[1] & 255)<<8) | \ (static_cast<unsigned long>((y)[0] & 255)); } #define STORE64L(x, y) \ { (y)[7] = static_cast<unsigned char>(((x)>>56)&255); (y)[6] = static_cast<unsigned char>(((x)>>48)&255); \ (y)[5] = static_cast<unsigned char>(((x)>>40)&255); (y)[4] = static_cast<unsigned char>(((x)>>32)&255); \ (y)[3] = static_cast<unsigned char>(((x)>>24)&255); (y)[2] = static_cast<unsigned char>(((x)>>16)&255); \ (y)[1] = static_cast<unsigned char>(((x)>>8)&255); (y)[0] = static_cast<unsigned char>((x)&255); } #define LOAD64L(x, y) \ { x = ((static_cast<ulong64>((y)[7] & 255))<<56)|((static_cast<ulong64>((y)[6] & 255))<<48)| \ ((static_cast<ulong64>((y)[5] & 255))<<40)|((static_cast<ulong64>((y)[4] & 255))<<32)| \ ((static_cast<ulong64>((y)[3] & 255))<<24)|((static_cast<ulong64>((y)[2] & 255))<<16)| \ ((static_cast<ulong64>((y)[1] & 255))<<8)|((static_cast<ulong64>((y)[0] & 255))); } #define STORE32H(x, y) \ { (y)[0] = static_cast<unsigned char>(((x)>>24)&255); (y)[1] = static_cast<unsigned char>(((x)>>16)&255); \ (y)[2] = static_cast<unsigned char>(((x)>>8)&255); (y)[3] = static_cast<unsigned char>((x)&255); } #define LOAD32H(x, y) \ { x = (static_cast<unsigned long>((y)[0] & 255)<<24) | \ (static_cast<unsigned long>((y)[1] & 255)<<16) | \ (static_cast<unsigned long>((y)[2] & 255)<<8) | \ (static_cast<unsigned long>((y)[3] & 255)); } #define STORE64H(x, y) \ { (y)[0] = static_cast<unsigned char>(((x)>>56)&255); (y)[1] = static_cast<unsigned char>(((x)>>48)&255); \ (y)[2] = static_cast<unsigned char>(((x)>>40)&255); (y)[3] = static_cast<unsigned char>(((x)>>32)&255); \ (y)[4] = static_cast<unsigned char>(((x)>>24)&255); (y)[5] = static_cast<unsigned char>(((x)>>16)&255); \ (y)[6] = static_cast<unsigned char>(((x)>>8)&255); (y)[7] = static_cast<unsigned char>((x)&255); } #define LOAD64H(x, y) \ { x = ((static_cast<ulong64>((y)[0] & 255))<<56)|((static_cast<ulong64>((y)[1] & 255))<<48) | \ ((static_cast<ulong64>((y)[2] & 255))<<40)|((static_cast<ulong64>((y)[3] & 255))<<32) | \ ((static_cast<ulong64>((y)[4] & 255))<<24)|((static_cast<ulong64>((y)[5] & 255))<<16) | \ ((static_cast<ulong64>((y)[6] & 255))<<8)|((static_cast<ulong64>((y)[7] & 255))); } #endif /* ENDIAN_NEUTRAL */ #ifdef ENDIAN_LITTLE #define STORE32H(x, y) \ { (y)[0] = static_cast<unsigned char>(((x)>>24)&255); (y)[1] = static_cast<unsigned char>(((x)>>16)&255); \ (y)[2] = static_cast<unsigned char>(((x)>>8)&255); (y)[3] = static_cast<unsigned char>((x)&255); } #define LOAD32H(x, y) \ { x = static_cast<ulong32>((static_cast<unsigned long>((y)[0] & 255)<<24) | \ (static_cast<unsigned long>((y)[1] & 255)<<16) | \ (static_cast<unsigned long>((y)[2] & 255)<<8) | \ (static_cast<unsigned long>((y)[3] & 255))); } #define STORE64H(x, y) \ { (y)[0] = static_cast<unsigned char>(((x)>>56)&255); (y)[1] = static_cast<unsigned char>(((x)>>48)&255); \ (y)[2] = static_cast<unsigned char>(((x)>>40)&255); (y)[3] = static_cast<unsigned char>(((x)>>32)&255); \ (y)[4] = static_cast<unsigned char>(((x)>>24)&255); (y)[5] = static_cast<unsigned char>(((x)>>16)&255); \ (y)[6] = static_cast<unsigned char>(((x)>>8)&255); (y)[7] = static_cast<unsigned char>((x)&255); } #define LOAD64H(x, y) \ { x = ((static_cast<ulong64>((y)[0] & 255))<<56)|((static_cast<ulong64>((y)[1] & 255))<<48) | \ ((static_cast<ulong64>((y)[2] & 255))<<40)|((static_cast<ulong64>((y)[3] & 255))<<32) | \ ((static_cast<ulong64>((y)[4] & 255))<<24)|((static_cast<ulong64>((y)[5] & 255))<<16) | \ ((static_cast<ulong64>((y)[6] & 255))<<8)|((static_cast<ulong64>((y)[7] & 255))); } #ifdef ENDIAN_32BITWORD #define STORE32L(x, y) \ { unsigned long __t = (x); memcpy(y, &__t, 4); } #define LOAD32L(x, y) \ memcpy(&(x), y, 4); #define STORE64L(x, y) \ { (y)[7] = static_cast<unsigned char>(((x)>>56)&255); (y)[6] = static_cast<unsigned char>(((x)>>48)&255); \ (y)[5] = static_cast<unsigned char>(((x)>>40)&255); (y)[4] = static_cast<unsigned char>(((x)>>32)&255); \ (y)[3] = static_cast<unsigned char>(((x)>>24)&255); (y)[2] = static_cast<unsigned char>(((x)>>16)&255); \ (y)[1] = static_cast<unsigned char>(((x)>>8)&255); (y)[0] = static_cast<unsigned char>((x)&255); } #define LOAD64L(x, y) \ { x = ((static_cast<ulong64>((y)[7] & 255))<<56)|((static_cast<ulong64>((y)[6] & 255))<<48)| \ ((static_cast<ulong64>((y)[5] & 255))<<40)|((static_cast<ulong64>((y)[4] & 255))<<32)| \ ((static_cast<ulong64>((y)[3] & 255))<<24)|((static_cast<ulong64>((y)[2] & 255))<<16)| \ ((static_cast<ulong64>((y)[1] & 255))<<8)|((static_cast<ulong64>((y)[0] & 255))); } #else /* 64-bit words then */ #define STORE32L(x, y) \ { unsigned long __t = (x); memcpy(y, &__t, 4); } #define LOAD32L(x, y) \ { memcpy(&(x), y, 4); x &= 0xFFFFFFFF; } #define STORE64L(x, y) \ { ulong64 __t = (x); memcpy(y, &__t, 8); } #define LOAD64L(x, y) \ { memcpy(&(x), y, 8); } #endif /* ENDIAN_64BITWORD */ #endif /* ENDIAN_LITTLE */ #ifdef ENDIAN_BIG #define STORE32L(x, y) \ { (y)[3] = static_cast<unsigned char>(((x)>>24)&255); (y)[2] = static_cast<unsigned char>(((x)>>16)&255); \ (y)[1] = static_cast<unsigned char>(((x)>>8)&255); (y)[0] = static_cast<unsigned char>((x)&255); } #define LOAD32L(x, y) \ { x = (static_cast<unsigned long>((y)[3] & 255)<<24) | \ (static_cast<unsigned long>((y)[2] & 255)<<16) | \ (static_cast<unsigned long>((y)[1] & 255)<<8) | \ (static_cast<unsigned long>((y)[0] & 255)); } #define STORE64L(x, y) \ { (y)[7] = static_cast<unsigned char>(((x)>>56)&255); (y)[6] = static_cast<unsigned char>(((x)>>48)&255); \ (y)[5] = static_cast<unsigned char>(((x)>>40)&255); (y)[4] = static_cast<unsigned char>(((x)>>32)&255); \ (y)[3] = static_cast<unsigned char>(((x)>>24)&255); (y)[2] = static_cast<unsigned char>(((x)>>16)&255); \ (y)[1] = static_cast<unsigned char>(((x)>>8)&255); (y)[0] = static_cast<unsigned char>((x)&255); } #define LOAD64L(x, y) \ { x = ((static_cast<ulong64>((y)[7] & 255))<<56)|((static_cast<ulong64>((y)[6] & 255))<<48) | \ ((static_cast<ulong64>((y)[5] & 255))<<40)|((static_cast<ulong64>((y)[4] & 255))<<32) | \ ((static_cast<ulong64>((y)[3] & 255))<<24)|((static_cast<ulong64>((y)[2] & 255))<<16) | \ ((static_cast<ulong64>((y)[1] & 255))<<8)|((static_cast<ulong64>((y)[0] & 255))); } #ifdef ENDIAN_32BITWORD #define STORE32H(x, y) \ { unsigned long __t = (x); memcpy(y, &__t, 4); } #define LOAD32H(x, y) \ memcpy(&(x), y, 4); #define STORE64H(x, y) \ { (y)[0] = static_cast<unsigned char>(((x)>>56)&255); (y)[1] = static_cast<unsigned char>(((x)>>48)&255); \ (y)[2] = static_cast<unsigned char>(((x)>>40)&255); (y)[3] = static_cast<unsigned char>(((x)>>32)&255); \ (y)[4] = static_cast<unsigned char>(((x)>>24)&255); (y)[5] = static_cast<unsigned char>(((x)>>16)&255); \ (y)[6] = static_cast<unsigned char>(((x)>>8)&255); (y)[7] = static_cast<unsigned char>((x)&255); } #define LOAD64H(x, y) \ { x = ((static_cast<ulong64>((y)[0] & 255))<<56)|((static_cast<ulong64>((y)[1] & 255))<<48)| \ ((static_cast<ulong64>((y)[2] & 255))<<40)|((static_cast<ulong64>((y)[3] & 255))<<32)| \ ((static_cast<ulong64>((y)[4] & 255))<<24)|((static_cast<ulong64>((y)[5] & 255))<<16)| \ ((static_cast<ulong64>((y)[6] & 255))<<8)| ((static_cast<ulong64>((y)[7] & 255))); } #else /* 64-bit words then */ #define STORE32H(x, y) \ { unsigned long __t = (x); memcpy(y, &__t, 4); } #define LOAD32H(x, y) \ { memcpy(&(x), y, 4); x &= 0xFFFFFFFF; } #define STORE64H(x, y) \ { ulong64 __t = (x); memcpy(y, &__t, 8); } #define LOAD64H(x, y) \ { memcpy(&(x), y, 8); } #endif /* ENDIAN_64BITWORD */ #endif /* ENDIAN_BIG */ #define BSWAP(x) ( ((x>>24)&0x000000FFUL) | ((x<<24)&0xFF000000UL) | \ ((x>>8)&0x0000FF00UL) | ((x<<8)&0x00FF0000UL) ) /* 32-bit Rotates */ #if defined(_MSC_VER) /* instrinsic rotate */ #include <stdlib.h> #pragma intrinsic(_lrotr,_lrotl) #define ROR(x,n) _lrotr(x,n) #define ROL(x,n) _lrotl(x,n) #define RORc(x,n) _lrotr(x,n) #define ROLc(x,n) _lrotl(x,n) #elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) && !defined(INTEL_CC) && !defined(LTC_NO_ASM) static inline unsigned ROL(unsigned word, int i) { asm("roll %%cl,%0" :"=r" (word) : "0" (word), "c" (i)); return word; } static inline unsigned ROR(unsigned word, int i) { asm("rorl %%cl,%0" :"=r" (word) : "0" (word), "c" (i)); return word; } #ifndef LTC_NO_ROLC static inline unsigned ROLc(unsigned word, const int i) { asm("roll %2,%0" :"=r" (word) : "0" (word), "I" (i)); return word; } static inline unsigned RORc(unsigned word, const int i) { asm("rorl %2,%0" :"=r" (word) : "0" (word), "I" (i)); return word; } #else #define ROLc ROL #define RORc ROR #endif #else /* rotates the hard way */ #define ROL(x, y) ( ((static_cast<unsigned long>(x)<<static_cast<unsigned long>((y)&31)) | ((static_cast<unsigned long>(x)&0xFFFFFFFFUL)>>static_cast<unsigned long>(32-((y)&31)))) & 0xFFFFFFFFUL) #define ROR(x, y) ( (((static_cast<unsigned long>(x)&0xFFFFFFFFUL)>>static_cast<unsigned long>((y)&31)) | (static_cast<unsigned long>(x)<<static_cast<unsigned long>(32-((y)&31)))) & 0xFFFFFFFFUL) #define ROLc(x, y) ( ((static_cast<unsigned long>(x)<<static_cast<unsigned long>((y)&31)) | ((static_cast<unsigned long>(x)&0xFFFFFFFFUL)>>static_cast<unsigned long>(32-((y)&31)))) & 0xFFFFFFFFUL) #define RORc(x, y) ( (((static_cast<unsigned long>(x)&0xFFFFFFFFUL)>>static_cast<unsigned long>((y)&31)) | (static_cast<unsigned long>(x)<<static_cast<unsigned long>(32-((y)&31)))) & 0xFFFFFFFFUL) #endif /* 64-bit Rotates */ #if defined(__GNUC__) && defined(__x86_64__) && !defined(LTC_NO_ASM) static inline unsigned long ROL64(unsigned long word, int i) { asm("rolq %%cl,%0" :"=r" (word) : "0" (word), "c" (i)); return word; } static inline unsigned long ROR64(unsigned long word, int i) { asm("rorq %%cl,%0" :"=r" (word) : "0" (word), "c" (i)); return word; } #ifndef LTC_NO_ROLC static inline unsigned long ROL64c(unsigned long word, const int i) { asm("rolq %2,%0" :"=r" (word) : "0" (word), "J" (i)); return word; } static inline unsigned long ROR64c(unsigned long word, const int i) { asm("rorq %2,%0" :"=r" (word) : "0" (word), "J" (i)); return word; } #else /* LTC_NO_ROLC */ #define ROL64c ROL #define ROR64c ROR #endif #else /* Not x86_64 */ #define ROL64(x, y) \ ( (((x)<<(static_cast<ulong64>(y)&63)) | \ (((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>(static_cast<ulong64>64-((y)&63)))) & CONST64(0xFFFFFFFFFFFFFFFF)) #define ROR64(x, y) \ ( ((((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>(static_cast<ulong64>(y)&CONST64(63))) | \ ((x)<<(static_cast<ulong64>(64-((y)&CONST64(63)))))) & CONST64(0xFFFFFFFFFFFFFFFF)) #define ROL64c(x, y) \ ( (((x)<<(static_cast<ulong64>(y)&63)) | \ (((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>(static_cast<ulong64>64-((y)&63)))) & CONST64(0xFFFFFFFFFFFFFFFF)) #define ROR64c(x, y) \ ( ((((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>(static_cast<ulong64>(y)&CONST64(63))) | \ ((x)<<(static_cast<ulong64>(64-((y)&CONST64(63)))))) & CONST64(0xFFFFFFFFFFFFFFFF)) #endif /* extract a byte portably */ #ifdef _MSC_VER #define byte(x, n) (static_cast<unsigned char>((x) >> (8 * (n)))) #else #define byte(x, n) (((x) >> (8 * (n))) & 255) #endif #endif // !_BITOPS_H
7,683
344
<gh_stars>100-1000 #include "refill.h" #include "z64.h" void health_and_magic_refill() { z64_file.refill_hearts = 0x140; z64_file.magic = z64_file.magic_capacity_set * 0x30; }
89
796
#include <string> #include <array> #include <unordered_map> #include <cmath> #include <cstring> #include <dlfcn.h> #include <jni.h> #include "modscript_shared.h" #include "mcpelauncher.h" #include "dobby_public.h" #include "mcpe/mce/textureptr.h" #include <android/log.h> #include <vector> // HumanoidMobRenderer::prepareArmor class ScreenContext; static int (*bl_HumanoidMobRenderer_prepareArmor_real)(HumanoidMobRenderer* self, ScreenContext&, Entity* mob, int armorPart, float partialTicks); static bool (*bl_ItemInstance_isArmorItem)(ItemInstance*); std::array<mce::TexturePtr*, BL_ITEMS_EXPANDED_COUNT> bl_armorRenders; bool bl_setArmorTexture(int, std::string const&); bool bl_setArmorTexture(int, mce::TexturePtr*); static std::vector<std::pair<int, std::string>> bl_queuedArmorTextures; static bool needsReload = true; bool bl_setArmorTexture(int id, std::string const& filename) { bl_queuedArmorTextures.emplace_back(id, filename); return true; } bool bl_setArmorTextureReal(int id, std::string const& filename) { __android_log_print(ANDROID_LOG_INFO, "BlockLauncher", "set armor texture real id: %d, %s", id, filename.c_str()); mce::TexturePtr* texturePtr = new mce::TexturePtr(bl_minecraft->getTextures(), ResourceLocation(filename)); return bl_setArmorTexture(id, texturePtr); } bool bl_setArmorTexture(int id, mce::TexturePtr* texturePtr) { if (id < 0 || id >= bl_item_id_count) return false; if (bl_armorRenders[id] != nullptr) delete bl_armorRenders[id]; bl_armorRenders[id] = texturePtr; return true; } extern "C" { static void bl_reload_armor_textures_real() { /* auto& textures = bl_minecraft->getTextures(); for (auto t: bl_armorRenders) { if (!t) continue; textures.loadTexture(ResourceLocation(t->textureName), false); } */ } void bl_reload_armor_textures() { needsReload = true; } // armour #if 0 int bl_HumanoidMobRenderer_prepareArmor_hook(HumanoidMobRenderer* self, ScreenContext& screenContext, Mob* mob, int armorPart, float partialTicks) { int retval = bl_HumanoidMobRenderer_prepareArmor_real(self, screenContext, mob, armorPart, partialTicks); ItemInstance* armor = mob->getArmor((ArmorSlot)armorPart); if (!armor->isArmorItem()) return retval; // no armour ArmorItem* armorItem = (ArmorItem*) armor->item; if (armorItem->renderIndex != 42) return retval; HumanoidModel* armorModel = armorItem->armorType == 2? self->modelArmorChestplate: self->modelArmor; if (needsReload) { needsReload = false; bl_reload_armor_textures_real(); } armorModel->activeTexture = bl_armorRenders[armorItem->itemId]; return retval; } #endif // end JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeSetCape (JNIEnv *env, jclass clazz, int entity, jstring value) { } JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeClearCapes (JNIEnv *env, jclass clazz) { } JNIEXPORT void JNICALL Java_net_zhuoweizhang_mcpelauncher_ScriptManager_nativeArmorAddQueuedTextures (JNIEnv *env, jclass clazz) { } void bl_armorInit_postLoad() { if (!bl_minecraft) return; // WTF for (auto& t: bl_queuedArmorTextures) { bl_setArmorTextureReal(t.first, t.second); } //bl_queuedArmorTextures.clear(); } void bl_cape_init(void* mcpelibinfo) { // FIXME 1.2.13 #if 0 void* prepareArmor = dlsym(mcpelibinfo, "_ZN19HumanoidMobRenderer12prepareArmorER13ScreenContextR3Mob9ArmorSlotf"); mcpelauncher_hook(prepareArmor, (void*) &bl_HumanoidMobRenderer_prepareArmor_hook, (void**) &bl_HumanoidMobRenderer_prepareArmor_real); #endif } } // extern "C"
1,294
852
<filename>Fireworks/Core/src/FWOverlapTableView.cc // -*- C++ -*- // // Package: Core // Class : FWOverlapTableView // // Implementation: // [Notes on implementation] // // Original Author: // Created: Wed Jan 4 00:06:35 CET 2012 // // system include files #include <functional> // user include files #include "Fireworks/Core/src/FWOverlapTableView.h" #include "Fireworks/Core/src/FWGeoTopNodeScene.h" #include "Fireworks/Core/src/FWOverlapTableManager.h" #include "Fireworks/Core/src/FWEveOverlap.h" #include "Fireworks/Core/interface/FWGeometryTableViewManager.h" #include "Fireworks/Core/interface/CmsShowViewPopup.h" #include "Fireworks/Core/src/FWPopupMenu.cc" #include "Fireworks/Core/interface/fwLog.h" #include "Fireworks/Core/src/FWGUIValidatingTextEntry.h" #include "Fireworks/Core/interface/FWValidatorBase.h" #include "Fireworks/Core/src/FWEveDigitSetScalableMarker.h" #include "TEveScene.h" #include "TEveSceneInfo.h" #include "TEveWindow.h" #include "TEveManager.h" #include "TGeoVolume.h" #include "TGeoMatrix.h" #include "TGeoShape.h" #include "TGeoBBox.h" #include "TGeoMatrix.h" #include "TGeoManager.h" #include "TGLViewer.h" #include "KeySymbols.h" #include "TGLabel.h" #include "TGNumberEntry.h" #include "TGListBox.h" #include "TGButton.h" #include "TEveViewer.h" #include "TGeoOverlap.h" #include "TGClient.h" static const std::string sUpdateMsg = "Please press Apply button to update overlaps.\n"; FWOverlapTableView::FWOverlapTableView(TEveWindowSlot* iParent, FWColorManager* colMng) : FWGeometryTableViewBase(iParent, FWViewType::kOverlapTable, colMng), m_applyButton(nullptr), m_listOptionButton(nullptr), m_tableManager(nullptr), m_numEntry(nullptr), m_runChecker(true), m_path(this, "Path:", std::string("/cms:World_1/cms:CMSE_1")), m_precision(this, "Precision", 0.05, 0.000001, 10), m_listAllNodes(this, "ListAllNodes", true), m_rnrOverlap(this, "Overlap", true), m_rnrExtrusion(this, "Extrusion", true), m_drawPoints(this, "DrawPoints", true), m_pointSize(this, "PointSize", 4l, 0l, 10l), m_extrusionMarkerColor(this, "ExtrusionMarkerColor", 0l, 0l, 20l), m_overlapMarkerColor(this, "OverlapMarkerColor", 9l, 0l, 20l) { // top row TGHorizontalFrame* hp = new TGHorizontalFrame(m_frame); { m_viewBox = new FWViewCombo(hp, this); hp->AddFrame(m_viewBox, new TGLayoutHints(kLHintsExpandY, 2, 2, 0, 0)); } { TGTextButton* rb = new TGTextButton(hp, "CdTop"); hp->AddFrame(rb, new TGLayoutHints(kLHintsNormal, 2, 2, 0, 0)); rb->Connect("Clicked()", "FWGeometryTableViewBase", this, "cdTop()"); } { TGTextButton* rb = new TGTextButton(hp, "CdUp"); hp->AddFrame(rb, new TGLayoutHints(kLHintsNormal, 2, 2, 0, 0)); rb->Connect("Clicked()", "FWGeometryTableViewBase", this, "cdUp()"); } { hp->AddFrame(new TGLabel(hp, "Precision:"), new TGLayoutHints(kLHintsBottom, 10, 0, 0, 2)); m_numEntry = new TGNumberEntry(hp, m_precision.value(), 5, -1, TGNumberFormat::kNESReal, TGNumberFormat::kNEAAnyNumber, TGNumberFormat::kNELLimitMinMax, m_precision.min(), m_precision.max()); hp->AddFrame(m_numEntry, new TGLayoutHints(kLHintsNormal, 2, 2, 0, 0)); m_numEntry->Connect("ValueSet(Long_t)", "FWOverlapTableView", this, "precisionCallback(Long_t)"); } { m_listOptionButton = new TGCheckButton(hp, m_listAllNodes.name().c_str()); m_listOptionButton->SetState(m_listAllNodes.value() ? kButtonDown : kButtonUp); m_listOptionButton->Connect("Clicked()", "FWOverlapTableView", this, "setListAllNodes()"); hp->AddFrame(m_listOptionButton, new TGLayoutHints(kLHintsLeft | kLHintsCenterY, 2, 0, 1, 1)); } { m_applyButton = new TGTextButton(hp, "Apply"); hp->AddFrame(m_applyButton, new TGLayoutHints(kLHintsNormal, 2, 2, 0, 0)); m_applyButton->Connect("Clicked()", "FWOverlapTableView", this, "recalculate()"); } m_frame->AddFrame(hp, new TGLayoutHints(kLHintsLeft | kLHintsExpandX, 4, 2, 2, 0)); m_tableManager = new FWOverlapTableManager(this); // std::cerr << " FWOverlapTableView::initGeometry \n"; FWGeoTopNodeGLScene* gls = new FWGeoTopNodeGLScene(nullptr); #if ROOT_VERSION_CODE < ROOT_VERSION(5, 32, 0) m_eveScene = new FWGeoTopNodeEveScene(gls, "TopGeoNodeScene", ""); #else m_eveScene = new TEveScene(gls, "TopGeoNodeScene", ""); #endif gEve->GetScenes()->AddElement(m_eveScene); m_eveTopNode = new FWEveOverlap(this); m_eveTopNode->SetElementNameTitle("overlapNode", "opverlapNodetitle"); m_eveTopNode->IncDenyDestroy(); m_eveTopNode->SetPickable(true); m_eveScene->AddElement(m_eveTopNode); gls->m_eveTopNode = m_eveTopNode; m_eveTopNode->m_scene = gls; m_marker = new FWEveDigitSetScalableMarker(); m_marker->SetMainColor(kRed); m_marker->IncDenyDestroy(); m_marker->Reset(TEveQuadSet::kQT_FreeQuad, kFALSE, 32); m_marker->SetOwnIds(kTRUE); m_marker->SetAlwaysSecSelect(kTRUE); m_marker->SetPickable(kTRUE); m_marker->SetOwnIds(kTRUE); m_drawPoints.changed_.connect(std::bind(&FWOverlapTableView::drawPoints, this)); m_pointSize.changed_.connect(std::bind(&FWOverlapTableView::pointSize, this)); m_rnrOverlap.changed_.connect(std::bind(&FWOverlapTableView::refreshTable3D, this)); m_overlapMarkerColor.changed_.connect(std::bind(&FWOverlapTableView::refreshTable3D, this)); m_extrusionMarkerColor.changed_.connect(std::bind(&FWOverlapTableView::refreshTable3D, this)); m_rnrExtrusion.changed_.connect(std::bind(&FWGeometryTableViewBase::refreshTable3D, this)); postConst(); } //______________________________________________________________________________ FWOverlapTableView::~FWOverlapTableView() { if (m_marker) m_marker->DecDenyDestroy(); } //______________________________________________________________________________ FWGeometryTableManagerBase* FWOverlapTableView::getTableManager() { return m_tableManager; } //______________________________________________________________________________ bool FWOverlapTableView::listAllNodes() const { return m_listAllNodes.value(); } //______________________________________________________________________________ void FWOverlapTableView::setListAllNodes() { m_listAllNodes.set(m_listOptionButton->IsOn()); refreshTable3D(); } //______________________________________________________________________________ TEveElement* FWOverlapTableView::getEveGeoElement() const { return m_eveTopNode; } //______________________________________________________________________________ void FWOverlapTableView::precisionCallback(Long_t) { // std::cout << " ----------------------------- PRECISION \n" << m_numEntry->GetNumber(); setCheckerState(true); m_precision.set(m_numEntry->GetNumber()); std::cout << sUpdateMsg; } void FWOverlapTableView::recalculate() { //m_path.set(m_pathEntry->GetText()); // m_precision.set(m_numEntry->GetNumber()); // std::cout << " $$$$ " << m_path.value() << std::endl; m_tableManager->importOverlaps(m_path.value(), m_precision.value()); checkExpandLevel(); getTableManager()->setLevelOffset(getTableManager()->refEntries().at(getTopNodeIdx()).m_level); refreshTable3D(); setCheckerState(false); } //______________________________________________________________________________ void FWOverlapTableView::setFrom(const FWConfiguration& iFrom) { m_enableRedraw = false; for (const_iterator it = begin(), itEnd = end(); it != itEnd; ++it) { (*it)->setFrom(iFrom); } m_viewersConfig = iFrom.valueForKey("Viewers"); m_numEntry->SetNumber(m_precision.value()); // refreshTable3D(); m_enableRedraw = true; recalculate(); } //______________________________________________________________________________ void FWOverlapTableView::populateController(ViewerParameterGUI& gui) const { gui.requestTab("Style") . // addParam(&m_enableHighlight). // separator(). addParam(&m_rnrOverlap) .addParam(&m_rnrExtrusion) .separator() .addParam(&m_extrusionMarkerColor) .addParam(&m_overlapMarkerColor) .addParam(&m_pointSize); FWGeometryTableViewBase::populateController(gui); } //______________________________________________________________________________ void FWOverlapTableView::drawPoints() { m_marker->SetRnrSelf(m_drawPoints.value()); m_marker->ElementChanged(); gEve->Redraw3D(); } //______________________________________________________________________________ void FWOverlapTableView::pointSize() { m_marker->SetMarkerSize(m_pointSize.value()); m_marker->ElementChanged(); gEve->Redraw3D(); } //______________________________________________________________________________ void FWOverlapTableView::cdUp() { setCheckerState(true); FWGeometryTableViewBase::cdUp(); } //______________________________________________________________________________ void FWOverlapTableView::cdTop() { if (m_topNodeIdx.value() == -1) return; setCheckerState(true); FWGeometryTableViewBase::cdTop(); } //______________________________________________________________________________ void FWOverlapTableView::setCheckerState(bool x) { m_runChecker = x; m_applyButton->SetForegroundColor(x ? 0xff0000 : 0x000000); gClient->NeedRedraw(m_applyButton); } //______________________________________________________________________________ void FWOverlapTableView::chosenItem(int menuIdx) { // printf(" FWOverlapTableView::chosenItem chosen item %s \n", ni->name()); switch (menuIdx) { case FWGeoTopNode::kPrintOverlap: { std::cout << "=============================================================================" << std::endl << std::endl; m_tableManager->printOverlaps(m_eveTopNode->getFirstSelectedTableIndex()); break; } default: FWGeometryTableViewBase::chosenItem(menuIdx); } } //______________________________________________________________________________ void FWOverlapTableView::refreshTable3D() { using namespace TMath; if (!m_enableRedraw) return; FWGeometryTableViewBase::refreshTable3D(); for (int i = 0; i < m_marker->GetPlex()->Size(); ++i) { FWOverlapTableManager::QuadId* id = (FWOverlapTableManager::QuadId*)m_marker->GetId(i); TEveQuadSet::QFreeQuad_t* q = (TEveQuadSet::QFreeQuad_t*)m_marker->GetDigit(i); q->fValue = -1; // check if any of the overlaping nodes is visible -> is in the subtree bool rnr = false; for (std::vector<int>::iterator j = id->m_nodes.begin(); j < id->m_nodes.end(); ++j) { if ((id->m_ovl->IsExtrusion() && m_rnrExtrusion.value()) || (id->m_ovl->IsOverlap() && m_rnrOverlap.value())) { if (*j == getTopNodeIdx() || m_tableManager->isNodeRendered(*j, getTopNodeIdx())) { rnr = true; break; } } } if (rnr) { q->fValue = (id->m_ovl->IsOverlap()) ? m_overlapMarkerColor.value() : m_extrusionMarkerColor.value(); q->fValue += 1000; } } m_marker->ElementChanged(); gEve->FullRedraw3D(false, true); }
4,337
14,668
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/blocklist/opt_out_blocklist/opt_out_blocklist.h" #include <algorithm> #include <map> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/cxx17_backports.h" #include "base/memory/ptr_util.h" #include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/simple_test_clock.h" #include "base/test/task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "components/blocklist/opt_out_blocklist/opt_out_blocklist_delegate.h" #include "components/blocklist/opt_out_blocklist/opt_out_blocklist_item.h" #include "components/blocklist/opt_out_blocklist/opt_out_store.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace blocklist { namespace { const char kTestHost1[] = "testhost1.com"; const char kTestHost2[] = "testhost2.com"; // Mock class to test that OptOutBlocklist notifies the delegate with correct // events (e.g. New host blocklisted, user blocklisted, and blocklist cleared). class TestOptOutBlocklistDelegate : public OptOutBlocklistDelegate { public: TestOptOutBlocklistDelegate() : blocklist_cleared_time_(base::Time::Now()) {} // OptOutBlocklistDelegate: void OnNewBlocklistedHost(const std::string& host, base::Time time) override { blocklisted_hosts_[host] = time; } void OnUserBlocklistedStatusChange(bool blocklisted) override { user_blocklisted_ = blocklisted; } void OnLoadingStateChanged(bool is_loaded) override { blocklist_loaded_ = is_loaded; } void OnBlocklistCleared(base::Time time) override { blocklist_cleared_ = true; blocklist_cleared_time_ = time; } // Gets the set of blocklisted hosts recorded. const std::unordered_map<std::string, base::Time>& blocklisted_hosts() const { return blocklisted_hosts_; } // Gets the state of user blocklisted status. bool user_blocklisted() const { return user_blocklisted_; } // Gets the load state of blocklist. bool blocklist_loaded() const { return blocklist_loaded_; } // Gets the state of blocklisted cleared status of |this| for testing. bool blocklist_cleared() const { return blocklist_cleared_; } // Gets the event time of blocklist is as cleared. base::Time blocklist_cleared_time() const { return blocklist_cleared_time_; } private: // The user blocklisted status of |this| blocklist_delegate. bool user_blocklisted_ = false; // The blocklist load status of |this| blocklist_delegate. bool blocklist_loaded_ = false; // Check if the blocklist is notified as cleared on |this| blocklist_delegate. bool blocklist_cleared_ = false; // The time when blocklist is cleared. base::Time blocklist_cleared_time_; // |this| blocklist_delegate's collection of blocklisted hosts. std::unordered_map<std::string, base::Time> blocklisted_hosts_; }; class TestOptOutStore : public OptOutStore { public: TestOptOutStore() = default; ~TestOptOutStore() override = default; int clear_blocklist_count() { return clear_blocklist_count_; } void SetBlocklistData(std::unique_ptr<BlocklistData> data) { data_ = std::move(data); } private: // OptOutStore implementation: void AddEntry(bool opt_out, const std::string& host_name, int type, base::Time now) override {} void LoadBlockList(std::unique_ptr<BlocklistData> blocklist_data, LoadBlockListCallback callback) override { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), data_ ? std::move(data_) : std::move(blocklist_data))); } void ClearBlockList(base::Time begin_time, base::Time end_time) override { ++clear_blocklist_count_; } int clear_blocklist_count_ = 0; std::unique_ptr<BlocklistData> data_; }; class TestOptOutBlocklist : public OptOutBlocklist { public: TestOptOutBlocklist(std::unique_ptr<OptOutStore> opt_out_store, base::Clock* clock, OptOutBlocklistDelegate* blocklist_delegate) : OptOutBlocklist(std::move(opt_out_store), clock, blocklist_delegate) {} ~TestOptOutBlocklist() override = default; void SetSessionRule(std::unique_ptr<BlocklistData::Policy> policy) { session_policy_ = std::move(policy); } void SetPersistentRule(std::unique_ptr<BlocklistData::Policy> policy) { persistent_policy_ = std::move(policy); } void SetHostRule(std::unique_ptr<BlocklistData::Policy> policy, size_t max_hosts) { host_policy_ = std::move(policy); max_hosts_ = max_hosts; } void SetTypeRule(std::unique_ptr<BlocklistData::Policy> policy) { type_policy_ = std::move(policy); } void SetAllowedTypes(BlocklistData::AllowedTypesAndVersions allowed_types) { allowed_types_ = std::move(allowed_types); } private: bool ShouldUseSessionPolicy(base::TimeDelta* duration, size_t* history, int* threshold) const override { if (!session_policy_) return false; *duration = session_policy_->duration; *history = session_policy_->history; *threshold = session_policy_->threshold; return true; } bool ShouldUsePersistentPolicy(base::TimeDelta* duration, size_t* history, int* threshold) const override { if (!persistent_policy_) return false; *duration = persistent_policy_->duration; *history = persistent_policy_->history; *threshold = persistent_policy_->threshold; return true; } bool ShouldUseHostPolicy(base::TimeDelta* duration, size_t* history, int* threshold, size_t* max_hosts) const override { if (!host_policy_) return false; *duration = host_policy_->duration; *history = host_policy_->history; *threshold = host_policy_->threshold; *max_hosts = max_hosts_; return true; } bool ShouldUseTypePolicy(base::TimeDelta* duration, size_t* history, int* threshold) const override { if (!type_policy_) return false; *duration = type_policy_->duration; *history = type_policy_->history; *threshold = type_policy_->threshold; return true; } BlocklistData::AllowedTypesAndVersions GetAllowedTypes() const override { return allowed_types_; } std::unique_ptr<BlocklistData::Policy> session_policy_; std::unique_ptr<BlocklistData::Policy> persistent_policy_; std::unique_ptr<BlocklistData::Policy> host_policy_; std::unique_ptr<BlocklistData::Policy> type_policy_; size_t max_hosts_ = 0; BlocklistData::AllowedTypesAndVersions allowed_types_; }; class OptOutBlocklistTest : public testing::Test { public: OptOutBlocklistTest() = default; OptOutBlocklistTest(const OptOutBlocklistTest&) = delete; OptOutBlocklistTest& operator=(const OptOutBlocklistTest&) = delete; ~OptOutBlocklistTest() override = default; void StartTest(bool null_opt_out_store) { std::unique_ptr<TestOptOutStore> opt_out_store = null_opt_out_store ? nullptr : std::make_unique<TestOptOutStore>(); opt_out_store_ = opt_out_store.get(); block_list_ = std::make_unique<TestOptOutBlocklist>( std::move(opt_out_store), &test_clock_, &blocklist_delegate_); if (session_policy_) { block_list_->SetSessionRule(std::move(session_policy_)); } if (persistent_policy_) { block_list_->SetPersistentRule(std::move(persistent_policy_)); } if (host_policy_) { block_list_->SetHostRule(std::move(host_policy_), max_hosts_); } if (type_policy_) { block_list_->SetTypeRule(std::move(type_policy_)); } block_list_->SetAllowedTypes(std::move(allowed_types_)); block_list_->Init(); start_ = test_clock_.Now(); passed_reasons_ = {}; } void SetSessionRule(std::unique_ptr<BlocklistData::Policy> policy) { session_policy_ = std::move(policy); } void SetPersistentRule(std::unique_ptr<BlocklistData::Policy> policy) { persistent_policy_ = std::move(policy); } void SetHostRule(std::unique_ptr<BlocklistData::Policy> policy, size_t max_hosts) { host_policy_ = std::move(policy); max_hosts_ = max_hosts; } void SetTypeRule(std::unique_ptr<BlocklistData::Policy> policy) { type_policy_ = std::move(policy); } void SetAllowedTypes(BlocklistData::AllowedTypesAndVersions allowed_types) { allowed_types_ = std::move(allowed_types); } protected: base::test::SingleThreadTaskEnvironment task_environment_; // Observer to |block_list_|. TestOptOutBlocklistDelegate blocklist_delegate_; base::SimpleTestClock test_clock_; raw_ptr<TestOptOutStore> opt_out_store_; base::Time start_; std::unique_ptr<TestOptOutBlocklist> block_list_; std::vector<BlocklistReason> passed_reasons_; private: std::unique_ptr<BlocklistData::Policy> session_policy_; std::unique_ptr<BlocklistData::Policy> persistent_policy_; std::unique_ptr<BlocklistData::Policy> host_policy_; std::unique_ptr<BlocklistData::Policy> type_policy_; size_t max_hosts_ = 0; BlocklistData::AllowedTypesAndVersions allowed_types_; }; TEST_F(OptOutBlocklistTest, HostBlockListNoStore) { // Tests the block list behavior when a null OptOutStore is passed in. auto host_policy = std::make_unique<BlocklistData::Policy>(base::Days(365), 4u, 2); SetHostRule(std::move(host_policy), 5); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(true /* null_opt_out */); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost2, 1, false, &passed_reasons_)); block_list_->AddEntry(kTestHost1, true, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, true, 1); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfHost, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, true, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost2, 1, false, &passed_reasons_)); block_list_->AddEntry(kTestHost2, true, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost2, true, 1); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfHost, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, true, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfHost, block_list_->IsLoadedAndAllowed(kTestHost2, 1, false, &passed_reasons_)); block_list_->AddEntry(kTestHost2, false, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost2, false, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost2, false, 1); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfHost, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, true, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost2, 1, false, &passed_reasons_)); block_list_->ClearBlockList(start_, test_clock_.Now()); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost2, 1, false, &passed_reasons_)); } TEST_F(OptOutBlocklistTest, TypeBlockListWithStore) { // Tests the block list behavior when a non-null OptOutStore is passed in. auto type_policy = std::make_unique<BlocklistData::Policy>(base::Days(365), 4u, 2); SetTypeRule(std::move(type_policy)); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); allowed_types.insert({2, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(false /* null_opt_out */); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kBlocklistNotLoaded, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kBlocklistNotLoaded, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kBlocklistNotLoaded, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); base::RunLoop().RunUntilIdle(); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); block_list_->AddEntry(kTestHost1, true, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, true, 1); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfType, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfType, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 2, true, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); block_list_->AddEntry(kTestHost1, true, 2); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, true, 2); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfType, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfType, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfType, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); block_list_->AddEntry(kTestHost1, false, 2); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, false, 2); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, false, 2); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfType, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfType, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); EXPECT_EQ(0, opt_out_store_->clear_blocklist_count()); block_list_->ClearBlockList(start_, base::Time::Now()); EXPECT_EQ(1, opt_out_store_->clear_blocklist_count()); EXPECT_EQ( BlocklistReason::kBlocklistNotLoaded, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kBlocklistNotLoaded, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kBlocklistNotLoaded, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, opt_out_store_->clear_blocklist_count()); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); } TEST_F(OptOutBlocklistTest, TypeBlockListNoStore) { // Tests the block list behavior when a null OptOutStore is passed in. auto type_policy = std::make_unique<BlocklistData::Policy>(base::Days(365), 4u, 2); SetTypeRule(std::move(type_policy)); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); allowed_types.insert({2, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(true /* null_opt_out */); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); block_list_->AddEntry(kTestHost1, true, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, true, 1); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfType, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, true, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); block_list_->AddEntry(kTestHost1, true, 2); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, true, 2); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfType, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, true, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfType, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); block_list_->AddEntry(kTestHost1, false, 2); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, false, 2); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, false, 2); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfType, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, true, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); block_list_->ClearBlockList(start_, test_clock_.Now()); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 2, false, &passed_reasons_)); } TEST_F(OptOutBlocklistTest, HostIndifferentBlocklist) { // Tests the block list behavior when a null OptOutStore is passed in. const std::string hosts[] = { "url_0.com", "url_1.com", "url_2.com", "url_3.com", }; int host_indifferent_threshold = 4; auto persistent_policy = std::make_unique<BlocklistData::Policy>( base::Days(365), 4u, host_indifferent_threshold); SetPersistentRule(std::move(persistent_policy)); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(true /* null_opt_out */); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(hosts[0], 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(hosts[1], 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(hosts[2], 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(hosts[3], 1, false, &passed_reasons_)); for (int i = 0; i < host_indifferent_threshold; i++) { block_list_->AddEntry(hosts[i], true, 1); EXPECT_EQ( i != 3 ? BlocklistReason::kAllowed : BlocklistReason::kUserOptedOutInGeneral, block_list_->IsLoadedAndAllowed(hosts[0], 1, false, &passed_reasons_)); test_clock_.Advance(base::Seconds(1)); } EXPECT_EQ( BlocklistReason::kUserOptedOutInGeneral, block_list_->IsLoadedAndAllowed(hosts[0], 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutInGeneral, block_list_->IsLoadedAndAllowed(hosts[1], 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutInGeneral, block_list_->IsLoadedAndAllowed(hosts[2], 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutInGeneral, block_list_->IsLoadedAndAllowed(hosts[3], 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(hosts[3], 1, true, &passed_reasons_)); block_list_->AddEntry(hosts[3], false, 1); test_clock_.Advance(base::Seconds(1)); // New non-opt-out entry will cause these to be allowed now. EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(hosts[0], 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(hosts[1], 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(hosts[2], 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(hosts[3], 1, false, &passed_reasons_)); } TEST_F(OptOutBlocklistTest, QueueBehavior) { // Tests the block list asynchronous queue behavior. Methods called while // loading the opt-out store are queued and should run in the order they were // queued. std::vector<bool> test_opt_out{true, false}; for (auto opt_out : test_opt_out) { auto host_policy = std::make_unique<BlocklistData::Policy>(base::Days(365), 4u, 2); SetHostRule(std::move(host_policy), 5); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(false /* null_opt_out */); EXPECT_EQ(BlocklistReason::kBlocklistNotLoaded, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); block_list_->AddEntry(kTestHost1, opt_out, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, opt_out, 1); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ(BlocklistReason::kBlocklistNotLoaded, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(opt_out ? BlocklistReason::kUserOptedOutOfHost : BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); block_list_->AddEntry(kTestHost1, opt_out, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, opt_out, 1); test_clock_.Advance(base::Seconds(1)); EXPECT_EQ(0, opt_out_store_->clear_blocklist_count()); block_list_->ClearBlockList(start_, test_clock_.Now() + base::Seconds(1)); EXPECT_EQ(1, opt_out_store_->clear_blocklist_count()); block_list_->AddEntry(kTestHost2, opt_out, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost2, opt_out, 1); test_clock_.Advance(base::Seconds(1)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, opt_out_store_->clear_blocklist_count()); EXPECT_EQ(BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ(opt_out ? BlocklistReason::kUserOptedOutOfHost : BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost2, 1, false, &passed_reasons_)); } } TEST_F(OptOutBlocklistTest, MaxHosts) { // Test that the block list only stores n hosts, and it stores the correct n // hosts. const std::string test_host_3("host3.com"); const std::string test_host_4("host4.com"); const std::string test_host_5("host5.com"); auto host_policy = std::make_unique<BlocklistData::Policy>(base::Days(365), 1u, 1); SetHostRule(std::move(host_policy), 2); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(true /* null_opt_out */); block_list_->AddEntry(kTestHost1, true, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost2, false, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(test_host_3, false, 1); // kTestHost1 should stay in the map, since it has an opt out time. EXPECT_EQ( BlocklistReason::kUserOptedOutOfHost, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost2, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(test_host_3, 1, false, &passed_reasons_)); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(test_host_4, true, 1); test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(test_host_5, true, 1); // test_host_4 and test_host_5 should remain in the map, but host should be // evicted. EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfHost, block_list_->IsLoadedAndAllowed(test_host_4, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutOfHost, block_list_->IsLoadedAndAllowed(test_host_5, 1, false, &passed_reasons_)); } TEST_F(OptOutBlocklistTest, SingleOptOut) { // Test that when a user opts out of an action, actions won't be allowed until // |single_opt_out_duration| has elapsed. int single_opt_out_duration = 5; const std::string test_host_3("host3.com"); auto session_policy = std::make_unique<BlocklistData::Policy>( base::Seconds(single_opt_out_duration), 1u, 1); SetSessionRule(std::move(session_policy)); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(true /* null_opt_out */); block_list_->AddEntry(kTestHost1, false, 1); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(test_host_3, 1, false, &passed_reasons_)); test_clock_.Advance(base::Seconds(single_opt_out_duration + 1)); block_list_->AddEntry(kTestHost2, true, 1); EXPECT_EQ( BlocklistReason::kUserOptedOutInSession, block_list_->IsLoadedAndAllowed(kTestHost2, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutInSession, block_list_->IsLoadedAndAllowed(test_host_3, 1, false, &passed_reasons_)); test_clock_.Advance(base::Seconds(single_opt_out_duration - 1)); EXPECT_EQ( BlocklistReason::kUserOptedOutInSession, block_list_->IsLoadedAndAllowed(kTestHost2, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kUserOptedOutInSession, block_list_->IsLoadedAndAllowed(test_host_3, 1, false, &passed_reasons_)); test_clock_.Advance(base::Seconds(single_opt_out_duration + 1)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost2, 1, false, &passed_reasons_)); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(test_host_3, 1, false, &passed_reasons_)); } TEST_F(OptOutBlocklistTest, ClearingBlockListClearsRecentNavigation) { // Tests that clearing the block list for a long amount of time (relative to // "single_opt_out_duration_in_seconds") resets the blocklist's recent opt out // rule. auto session_policy = std::make_unique<BlocklistData::Policy>(base::Seconds(5), 1u, 1); SetSessionRule(std::move(session_policy)); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(false /* null_opt_out */); block_list_->AddEntry(kTestHost1, true /* opt_out */, 1); test_clock_.Advance(base::Seconds(1)); block_list_->ClearBlockList(start_, test_clock_.Now()); base::RunLoop().RunUntilIdle(); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); } TEST_F(OptOutBlocklistTest, ObserverIsNotifiedOnHostBlocklisted) { // Tests the block list behavior when a null OptOutStore is passed in. auto host_policy = std::make_unique<BlocklistData::Policy>(base::Days(365), 4u, 2); SetHostRule(std::move(host_policy), 5); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(true /* null_opt_out */); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); // Observer is not notified as blocklisted when the threshold does not met. test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, true, 1); base::RunLoop().RunUntilIdle(); EXPECT_THAT(blocklist_delegate_.blocklisted_hosts(), ::testing::SizeIs(0)); // Observer is notified as blocklisted when the threshold is met. test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, true, 1); base::RunLoop().RunUntilIdle(); const base::Time blocklisted_time = test_clock_.Now(); EXPECT_THAT(blocklist_delegate_.blocklisted_hosts(), ::testing::SizeIs(1)); EXPECT_EQ(blocklisted_time, blocklist_delegate_.blocklisted_hosts().find(kTestHost1)->second); // Observer is not notified when the host is already blocklisted. test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(kTestHost1, true, 1); base::RunLoop().RunUntilIdle(); EXPECT_THAT(blocklist_delegate_.blocklisted_hosts(), ::testing::SizeIs(1)); EXPECT_EQ(blocklisted_time, blocklist_delegate_.blocklisted_hosts().find(kTestHost1)->second); // Observer is notified when blocklist is cleared. EXPECT_FALSE(blocklist_delegate_.blocklist_cleared()); test_clock_.Advance(base::Seconds(1)); block_list_->ClearBlockList(start_, test_clock_.Now()); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(blocklist_delegate_.blocklist_cleared()); EXPECT_EQ(test_clock_.Now(), blocklist_delegate_.blocklist_cleared_time()); } TEST_F(OptOutBlocklistTest, ObserverIsNotifiedOnUserBlocklisted) { // Tests the block list behavior when a null OptOutStore is passed in. const std::string hosts[] = { "url_0.com", "url_1.com", "url_2.com", "url_3.com", }; int host_indifferent_threshold = 4; auto persistent_policy = std::make_unique<BlocklistData::Policy>( base::Days(30), 4u, host_indifferent_threshold); SetPersistentRule(std::move(persistent_policy)); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(true /* null_opt_out */); // Initially no host is blocklisted, and user is not blocklisted. EXPECT_THAT(blocklist_delegate_.blocklisted_hosts(), ::testing::SizeIs(0)); EXPECT_FALSE(blocklist_delegate_.user_blocklisted()); for (int i = 0; i < host_indifferent_threshold; ++i) { test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(hosts[i], true, 1); base::RunLoop().RunUntilIdle(); EXPECT_THAT(blocklist_delegate_.blocklisted_hosts(), ::testing::SizeIs(0)); // Observer is notified when number of recently opt out meets // |host_indifferent_threshold|. EXPECT_EQ(i >= host_indifferent_threshold - 1, blocklist_delegate_.user_blocklisted()); } // Observer is notified when the user is no longer blocklisted. test_clock_.Advance(base::Seconds(1)); block_list_->AddEntry(hosts[3], false, 1); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(blocklist_delegate_.user_blocklisted()); } TEST_F(OptOutBlocklistTest, ObserverIsNotifiedWhenLoadBlocklistDone) { int host_indifferent_threshold = 4; size_t host_indifferent_history = 4u; auto persistent_policy = std::make_unique<BlocklistData::Policy>( base::Days(30), host_indifferent_history, host_indifferent_threshold); SetPersistentRule(std::move(persistent_policy)); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(false /* null_opt_out */); allowed_types.clear(); allowed_types[0] = 0; std::unique_ptr<BlocklistData> data = std::make_unique<BlocklistData>( nullptr, std::make_unique<BlocklistData::Policy>(base::Seconds(365), host_indifferent_history, host_indifferent_threshold), nullptr, nullptr, 0, std::move(allowed_types)); base::SimpleTestClock test_clock; for (int i = 0; i < host_indifferent_threshold; ++i) { test_clock.Advance(base::Seconds(1)); data->AddEntry(kTestHost1, true, 0, test_clock.Now(), true); } std::unique_ptr<TestOptOutStore> opt_out_store = std::make_unique<TestOptOutStore>(); opt_out_store->SetBlocklistData(std::move(data)); EXPECT_FALSE(blocklist_delegate_.user_blocklisted()); EXPECT_FALSE(blocklist_delegate_.blocklist_loaded()); allowed_types.clear(); allowed_types[1] = 0; auto block_list = std::make_unique<TestOptOutBlocklist>( std::move(opt_out_store), &test_clock, &blocklist_delegate_); block_list->SetAllowedTypes(std::move(allowed_types)); persistent_policy = std::make_unique<BlocklistData::Policy>( base::Days(30), host_indifferent_history, host_indifferent_threshold); block_list->SetPersistentRule(std::move(persistent_policy)); block_list->Init(); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(blocklist_delegate_.user_blocklisted()); EXPECT_TRUE(blocklist_delegate_.blocklist_loaded()); } TEST_F(OptOutBlocklistTest, ObserverIsNotifiedOfHistoricalBlocklistedHosts) { // Tests the block list behavior when a non-null OptOutStore is passed in. int host_indifferent_threshold = 2; size_t host_indifferent_history = 4u; auto host_policy = std::make_unique<BlocklistData::Policy>( base::Days(365), host_indifferent_history, host_indifferent_threshold); SetHostRule(std::move(host_policy), 5); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(false /* null_opt_out */); base::SimpleTestClock test_clock; allowed_types.clear(); allowed_types[static_cast<int>(1)] = 0; std::unique_ptr<BlocklistData> data = std::make_unique<BlocklistData>( nullptr, nullptr, std::make_unique<BlocklistData::Policy>(base::Days(365), host_indifferent_history, host_indifferent_threshold), nullptr, 2, std::move(allowed_types)); test_clock.Advance(base::Seconds(1)); data->AddEntry(kTestHost1, true, static_cast<int>(1), test_clock.Now(), true); test_clock.Advance(base::Seconds(1)); data->AddEntry(kTestHost1, true, static_cast<int>(1), test_clock.Now(), true); base::Time blocklisted_time = test_clock.Now(); base::RunLoop().RunUntilIdle(); std::vector<BlocklistReason> reasons; EXPECT_NE(BlocklistReason::kAllowed, data->IsAllowed(kTestHost1, static_cast<int>(1), false, test_clock.Now(), &reasons)); // Host |url_b| is not blocklisted. test_clock.Advance(base::Seconds(1)); data->AddEntry(kTestHost2, true, static_cast<int>(1), test_clock.Now(), true); std::unique_ptr<TestOptOutStore> opt_out_store = std::make_unique<TestOptOutStore>(); opt_out_store->SetBlocklistData(std::move(data)); allowed_types.clear(); allowed_types[static_cast<int>(1)] = 0; auto block_list = std::make_unique<TestOptOutBlocklist>( std::move(opt_out_store), &test_clock, &blocklist_delegate_); block_list->SetAllowedTypes(std::move(allowed_types)); host_policy = std::make_unique<BlocklistData::Policy>( base::Days(30), host_indifferent_history, host_indifferent_threshold); block_list->SetPersistentRule(std::move(host_policy)); block_list->Init(); base::RunLoop().RunUntilIdle(); ASSERT_THAT(blocklist_delegate_.blocklisted_hosts(), ::testing::SizeIs(1)); EXPECT_EQ(blocklisted_time, blocklist_delegate_.blocklisted_hosts().find(kTestHost1)->second); } TEST_F(OptOutBlocklistTest, PassedReasonsWhenBlocklistDataNotLoaded) { // Test that IsLoadedAndAllow, push checked BlocklistReasons to the // |passed_reasons| vector. BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(false /* null_opt_out */); EXPECT_EQ( BlocklistReason::kBlocklistNotLoaded, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ(0UL, passed_reasons_.size()); } TEST_F(OptOutBlocklistTest, PassedReasonsWhenUserRecentlyOptedOut) { // Test that IsLoadedAndAllow, push checked BlocklistReasons to the // |passed_reasons| vector. auto session_policy = std::make_unique<BlocklistData::Policy>(base::Seconds(5), 1u, 1); SetSessionRule(std::move(session_policy)); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(true /* null_opt_out */); block_list_->AddEntry(kTestHost1, true, 1); EXPECT_EQ( BlocklistReason::kUserOptedOutInSession, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); EXPECT_EQ(1UL, passed_reasons_.size()); EXPECT_EQ(BlocklistReason::kBlocklistNotLoaded, passed_reasons_[0]); } TEST_F(OptOutBlocklistTest, PassedReasonsWhenUserBlocklisted) { // Test that IsLoadedAndAllow, push checked BlocklistReasons to the // |passed_reasons| vector. const std::string hosts[] = { "http://www.url_0.com", "http://www.url_1.com", "http://www.url_2.com", "http://www.url_3.com", }; auto session_policy = std::make_unique<BlocklistData::Policy>(base::Seconds(1), 1u, 1); SetSessionRule(std::move(session_policy)); auto persistent_policy = std::make_unique<BlocklistData::Policy>(base::Days(365), 4u, 4); SetPersistentRule(std::move(persistent_policy)); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(true /* null_opt_out */); test_clock_.Advance(base::Seconds(1)); for (auto host : hosts) { block_list_->AddEntry(host, true, 1); } test_clock_.Advance(base::Seconds(2)); EXPECT_EQ( BlocklistReason::kUserOptedOutInGeneral, block_list_->IsLoadedAndAllowed(hosts[0], 1, false, &passed_reasons_)); BlocklistReason expected_reasons[] = { BlocklistReason::kBlocklistNotLoaded, BlocklistReason::kUserOptedOutInSession, }; EXPECT_EQ(base::size(expected_reasons), passed_reasons_.size()); for (size_t i = 0; i < passed_reasons_.size(); i++) { EXPECT_EQ(expected_reasons[i], passed_reasons_[i]); } } TEST_F(OptOutBlocklistTest, PassedReasonsWhenHostBlocklisted) { // Test that IsLoadedAndAllow, push checked BlocklistReasons to the // |passed_reasons| vector. auto session_policy = std::make_unique<BlocklistData::Policy>(base::Days(5), 3u, 3); SetSessionRule(std::move(session_policy)); auto persistent_policy = std::make_unique<BlocklistData::Policy>(base::Days(365), 4u, 4); SetPersistentRule(std::move(persistent_policy)); auto host_policy = std::make_unique<BlocklistData::Policy>(base::Days(30), 4u, 2); SetHostRule(std::move(host_policy), 2); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(true /* null_opt_out */); block_list_->AddEntry(kTestHost1, true, 1); block_list_->AddEntry(kTestHost1, true, 1); EXPECT_EQ( BlocklistReason::kUserOptedOutOfHost, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); BlocklistReason expected_reasons[] = { BlocklistReason::kBlocklistNotLoaded, BlocklistReason::kUserOptedOutInSession, BlocklistReason::kUserOptedOutInGeneral, }; EXPECT_EQ(base::size(expected_reasons), passed_reasons_.size()); for (size_t i = 0; i < passed_reasons_.size(); i++) { EXPECT_EQ(expected_reasons[i], passed_reasons_[i]); } } TEST_F(OptOutBlocklistTest, PassedReasonsWhenAllowed) { // Test that IsLoadedAndAllow, push checked BlocklistReasons to the // |passed_reasons| vector. auto session_policy = std::make_unique<BlocklistData::Policy>(base::Seconds(1), 1u, 1); SetSessionRule(std::move(session_policy)); auto persistent_policy = std::make_unique<BlocklistData::Policy>(base::Days(365), 4u, 4); SetPersistentRule(std::move(persistent_policy)); auto host_policy = std::make_unique<BlocklistData::Policy>(base::Days(30), 4u, 4); SetHostRule(std::move(host_policy), 1); auto type_policy = std::make_unique<BlocklistData::Policy>(base::Days(30), 4u, 4); SetTypeRule(std::move(type_policy)); BlocklistData::AllowedTypesAndVersions allowed_types; allowed_types.insert({1, 0}); SetAllowedTypes(std::move(allowed_types)); StartTest(true /* null_opt_out */); EXPECT_EQ( BlocklistReason::kAllowed, block_list_->IsLoadedAndAllowed(kTestHost1, 1, false, &passed_reasons_)); BlocklistReason expected_reasons[] = { BlocklistReason::kBlocklistNotLoaded, BlocklistReason::kUserOptedOutInSession, BlocklistReason::kUserOptedOutInGeneral, BlocklistReason::kUserOptedOutOfHost, BlocklistReason::kUserOptedOutOfType, }; EXPECT_EQ(base::size(expected_reasons), passed_reasons_.size()); for (size_t i = 0; i < passed_reasons_.size(); i++) { EXPECT_EQ(expected_reasons[i], passed_reasons_[i]); } } } // namespace } // namespace blocklist
17,292
1,337
<gh_stars>1000+ /* * Copyright 2015 <NAME> * * 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.haulmont.cuba.web.widgets.client.addons.dragdroplayouts.ui.interfaces; import com.vaadin.shared.Connector; import com.vaadin.shared.communication.SharedState; import com.haulmont.cuba.web.widgets.client.addons.dragdroplayouts.ui.DragCaptionInfo; import com.haulmont.cuba.web.widgets.client.addons.dragdroplayouts.ui.LayoutDragMode; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class DDLayoutState extends SharedState { // The current drag mode, default is dragging is not supported public LayoutDragMode dragMode = LayoutDragMode.NONE; // Are the iframes shimmed public boolean iframeShims = true; // Which connectors are draggable public List<Connector> draggable = new ArrayList<>(); // Which connectors cannot be used as anchor public List<Connector> nonGrabbable = new ArrayList<>(); // Reference drag images public Map<Connector, Connector> referenceImageComponents = new HashMap<>(); // Custom DragCaption's with icon and caption public Map<Connector, DragCaptionInfo> dragCaptions = new HashMap<>(); public Map<Connector, String> dragIcons = new HashMap<>(); }
537
591
<reponame>orivej/rs_asio #include "stdafx.h" #pragma comment(lib, "propsys.lib")
43
2,151
<gh_stars>1000+ // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/conflicts/module_database_win.h" #include <algorithm> #include <memory> #include <vector> #include "base/bind.h" #include "base/task_scheduler/post_task.h" #include "base/task_scheduler/task_scheduler.h" #include "base/test/scoped_mock_time_message_loop_task_runner.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/time/time.h" #include "chrome/browser/conflicts/module_database_observer_win.h" #include "chrome/test/base/scoped_testing_local_state.h" #include "chrome/test/base/testing_browser_process.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" namespace { constexpr content::ProcessType kProcessType1 = content::PROCESS_TYPE_BROWSER; constexpr content::ProcessType kProcessType2 = content::PROCESS_TYPE_RENDERER; constexpr wchar_t kDll1[] = L"dummy.dll"; constexpr wchar_t kDll2[] = L"foo.dll"; constexpr size_t kSize1 = 100 * 4096; constexpr size_t kSize2 = 20 * 4096; constexpr uint32_t kTime1 = 0xDEADBEEF; constexpr uint32_t kTime2 = 0xBAADF00D; constexpr uintptr_t kGoodAddress1 = 0x04000000u; constexpr uintptr_t kGoodAddress2 = 0x05000000u; } // namespace class ModuleDatabaseTest : public testing::Test { protected: ModuleDatabaseTest() : dll1_(kDll1), dll2_(kDll2), scoped_testing_local_state_(TestingBrowserProcess::GetGlobal()), module_database_(base::SequencedTaskRunnerHandle::Get()) {} const ModuleDatabase::ModuleMap& modules() { return module_database_.modules_; } ModuleDatabase* module_database() { return &module_database_; } static uint32_t ProcessTypeToBit(content::ProcessType process_type) { return ModuleDatabase::ProcessTypeToBit(process_type); } void RunSchedulerUntilIdle() { base::TaskScheduler::GetInstance()->FlushForTesting(); mock_time_task_runner_->RunUntilIdle(); } void FastForwardToIdleTimer() { RunSchedulerUntilIdle(); mock_time_task_runner_->FastForwardBy(ModuleDatabase::kIdleTimeout); } const base::FilePath dll1_; const base::FilePath dll2_; private: // Must be before |module_database_|. content::TestBrowserThreadBundle test_browser_thread_bundle_; base::ScopedMockTimeMessageLoopTaskRunner mock_time_task_runner_; ScopedTestingLocalState scoped_testing_local_state_; ModuleDatabase module_database_; DISALLOW_COPY_AND_ASSIGN(ModuleDatabaseTest); }; TEST_F(ModuleDatabaseTest, TasksAreBounced) { // Run a task on the current thread. This should not be bounced, so their // results should be immediately available. module_database()->OnModuleLoad(kProcessType1, dll1_, kSize1, kTime1, kGoodAddress1); EXPECT_EQ(1u, modules().size()); // Run similar tasks on another thread with another module. These should be // bounced. base::PostTask(FROM_HERE, base::Bind(&ModuleDatabase::OnModuleLoad, base::Unretained(module_database()), kProcessType2, dll2_, kSize1, kTime1, kGoodAddress1)); EXPECT_EQ(1u, modules().size()); RunSchedulerUntilIdle(); EXPECT_EQ(2u, modules().size()); } TEST_F(ModuleDatabaseTest, DatabaseIsConsistent) { EXPECT_EQ(0u, modules().size()); // Load a module. module_database()->OnModuleLoad(kProcessType1, dll1_, kSize1, kTime1, kGoodAddress1); EXPECT_EQ(1u, modules().size()); // Ensure that the process and module sets are up to date. auto m1 = modules().begin(); EXPECT_EQ(dll1_, m1->first.module_path); EXPECT_EQ(ProcessTypeToBit(content::PROCESS_TYPE_BROWSER), m1->second.process_types); // Provide a redundant load message for that module. module_database()->OnModuleLoad(kProcessType1, dll1_, kSize1, kTime1, kGoodAddress1); EXPECT_EQ(1u, modules().size()); // Ensure that the process and module sets haven't changed. EXPECT_EQ(dll1_, m1->first.module_path); EXPECT_EQ(ProcessTypeToBit(content::PROCESS_TYPE_BROWSER), m1->second.process_types); // Load a second module into the process. module_database()->OnModuleLoad(kProcessType1, dll2_, kSize2, kTime2, kGoodAddress2); EXPECT_EQ(2u, modules().size()); // Ensure that the process and module sets are up to date. auto m2 = modules().rbegin(); EXPECT_EQ(dll2_, m2->first.module_path); EXPECT_EQ(ProcessTypeToBit(content::PROCESS_TYPE_BROWSER), m2->second.process_types); // Load the dummy.dll in the second process as well. module_database()->OnModuleLoad(kProcessType2, dll1_, kSize1, kTime1, kGoodAddress1); EXPECT_EQ(ProcessTypeToBit(content::PROCESS_TYPE_BROWSER) | ProcessTypeToBit(content::PROCESS_TYPE_RENDERER), m1->second.process_types); } // A dummy observer that only counts how many notifications it receives. class DummyObserver : public ModuleDatabaseObserver { public: DummyObserver() = default; ~DummyObserver() override = default; void OnNewModuleFound(const ModuleInfoKey& module_key, const ModuleInfoData& module_data) override { new_module_count_++; } void OnModuleDatabaseIdle() override { on_module_database_idle_called_ = true; } int new_module_count() { return new_module_count_; } bool on_module_database_idle_called() { return on_module_database_idle_called_; } private: int new_module_count_ = 0; bool on_module_database_idle_called_ = false; DISALLOW_COPY_AND_ASSIGN(DummyObserver); }; TEST_F(ModuleDatabaseTest, Observers) { // Assume there is no shell extensions or IMEs. module_database()->OnShellExtensionEnumerationFinished(); module_database()->OnImeEnumerationFinished(); DummyObserver before_load_observer; EXPECT_EQ(0, before_load_observer.new_module_count()); module_database()->AddObserver(&before_load_observer); EXPECT_EQ(0, before_load_observer.new_module_count()); module_database()->OnModuleLoad(kProcessType1, dll1_, kSize1, kTime1, kGoodAddress1); RunSchedulerUntilIdle(); EXPECT_EQ(1, before_load_observer.new_module_count()); module_database()->RemoveObserver(&before_load_observer); // New observers get notified for past loaded modules. DummyObserver after_load_observer; EXPECT_EQ(0, after_load_observer.new_module_count()); module_database()->AddObserver(&after_load_observer); EXPECT_EQ(1, after_load_observer.new_module_count()); module_database()->RemoveObserver(&after_load_observer); } // Tests the idle cycle of the ModuleDatabase. TEST_F(ModuleDatabaseTest, IsIdle) { // Assume there is no shell extensions or IMEs. module_database()->OnShellExtensionEnumerationFinished(); module_database()->OnImeEnumerationFinished(); // ModuleDatabase starts busy. EXPECT_FALSE(module_database()->IsIdle()); // Can't fast forward to idle because a module load event is needed. FastForwardToIdleTimer(); EXPECT_FALSE(module_database()->IsIdle()); // A load module event starts the timer. module_database()->OnModuleLoad(kProcessType1, dll1_, kSize1, kTime1, kGoodAddress1); EXPECT_FALSE(module_database()->IsIdle()); FastForwardToIdleTimer(); EXPECT_TRUE(module_database()->IsIdle()); // A new shell extension resets the timer. module_database()->OnShellExtensionEnumerated(dll1_, kSize1, kTime1); EXPECT_FALSE(module_database()->IsIdle()); FastForwardToIdleTimer(); EXPECT_TRUE(module_database()->IsIdle()); // Adding an observer while idle immediately calls OnModuleDatabaseIdle(). DummyObserver is_idle_observer; module_database()->AddObserver(&is_idle_observer); EXPECT_TRUE(is_idle_observer.on_module_database_idle_called()); module_database()->RemoveObserver(&is_idle_observer); // Make the ModuleDabatase busy. module_database()->OnModuleLoad(kProcessType2, dll2_, kSize2, kTime2, kGoodAddress2); EXPECT_FALSE(module_database()->IsIdle()); // Adding an observer while busy doesn't. DummyObserver is_busy_observer; module_database()->AddObserver(&is_busy_observer); EXPECT_FALSE(is_busy_observer.on_module_database_idle_called()); // Fast forward will call OnModuleDatabaseIdle(). FastForwardToIdleTimer(); EXPECT_TRUE(module_database()->IsIdle()); EXPECT_TRUE(is_busy_observer.on_module_database_idle_called()); module_database()->RemoveObserver(&is_busy_observer); } // The ModuleDatabase waits until shell extensions and IMEs are enumerated // before notifying observers or going idle. TEST_F(ModuleDatabaseTest, WaitUntilRegisteredModulesEnumerated) { // This observer is added before the first loaded module. DummyObserver before_load_observer; module_database()->AddObserver(&before_load_observer); EXPECT_EQ(0, before_load_observer.new_module_count()); module_database()->OnModuleLoad(kProcessType1, dll1_, kSize1, kTime1, kGoodAddress1); FastForwardToIdleTimer(); // Idle state is prevented. EXPECT_FALSE(module_database()->IsIdle()); EXPECT_EQ(0, before_load_observer.new_module_count()); EXPECT_FALSE(before_load_observer.on_module_database_idle_called()); // This observer is added after the first loaded module. DummyObserver after_load_observer; module_database()->AddObserver(&after_load_observer); EXPECT_EQ(0, after_load_observer.new_module_count()); EXPECT_FALSE(after_load_observer.on_module_database_idle_called()); // Simulate the enumerations ending. module_database()->OnImeEnumerationFinished(); module_database()->OnShellExtensionEnumerationFinished(); EXPECT_EQ(1, before_load_observer.new_module_count()); EXPECT_TRUE(before_load_observer.on_module_database_idle_called()); EXPECT_EQ(1, after_load_observer.new_module_count()); EXPECT_TRUE(after_load_observer.on_module_database_idle_called()); module_database()->RemoveObserver(&after_load_observer); module_database()->RemoveObserver(&before_load_observer); }
3,848
522
package algs.blog.searching.tree; import algs.blog.searching.search.ICollectionSearch; import algs.model.tree.BalancedBinaryNode; import algs.model.tree.BalancedTree; /** * Use a balanced binary tree to store all items. * <p> * In the worst case, the items are inserted into the tree in alphabetic order, which * is what we do in this case. * * @author <NAME> */ public class BalancedTreeSearch implements ICollectionSearch<String> { /** Use balanced binary tree. */ final BalancedTree<String,Boolean> tree; public BalancedTreeSearch() { tree = new BalancedTree<String,Boolean>(); } /** * Insert the string into our collection. * <p> * Note that since there are no duplicates, attempts to insert the same string * multiple times are silently ignored. * * @param s string to insert into the tree. */ public void insert(String s) { tree.insert(s, true); } @Override public boolean exists(String target) { return tree.getEntry(target) != null; } private int totalProbes(BalancedBinaryNode<String,Boolean> node, int p) { if (node == null) { return 0; } return p + totalProbes(node.left(),p+1) + totalProbes(node.right(),p+1); } private int totalProbes() { BalancedBinaryNode<String,Boolean> p = tree.root(); if (p == null) { return 0; } return 1 + totalProbes(p.left(),2) + totalProbes(p.right(),2); } private int depth(BalancedBinaryNode<String,Boolean> node) { if (node == null) { return 0; } return Math.max(1 + depth(node.left()), 1 + depth(node.right())); } private int depth() { BalancedBinaryNode<String,Boolean> p = tree.root(); if (p == null) { return 0; } return Math.max(1 + depth(p.left()), 1 + depth(p.right())); } @Override public String toString() { return "Balanced Tree: Maximum depth:" + depth() + ", Average depth:" + (1.0f*totalProbes())/tree.size(); } }
779
348
{"nom":"Beaujeu-Saint-Vallier-Pierrejux-et-Quitteur","dpt":"Haute-Saône","inscrits":676,"abs":138,"votants":538,"blancs":50,"nuls":18,"exp":470,"res":[{"panneau":"2","voix":277},{"panneau":"1","voix":193}]}
88
5,169
{ "name": "GNCheckView", "version": "0.1.2", "summary": "A UIView subclass that allows animating smoothly between a checked and an unchecked state.", "description": "A UIView subclass that allows animating smoothly between a checked and an unchecked state, meant to provide a sleeker alternative to the UITableViewAccessoryCheckmark or any other of your check marking needs!.\n * Markdown format.\n * Don't worry about the indent, we strip it!", "homepage": "https://github.com/gonzalonunez/GNCheckView", "license": "MIT", "authors": { "gonzalonunez": "<EMAIL>" }, "source": { "git": "https://github.com/gonzalonunez/GNCheckView.git", "tag": "0.1.2" }, "platforms": { "ios": "8.0" }, "requires_arc": true, "source_files": "Pod/Classes/**/*", "module_name": "GNCheckView", "resource_bundles": { "GNCheckView": [ "Pod/Assets/*.png" ] } }
363
1,056
/* * 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.netbeans.modules.javascript2.debug.ui.editor; import java.net.URL; import org.openide.text.Line; import org.openide.util.lookup.Lookups; /** * * @author Martin */ class FutureLine extends Line { private final URL url; private final int lineNumber; public FutureLine(URL url, int lineNumber) { super(Lookups.fixed()); this.url = url; this.lineNumber = lineNumber; } @Override public int getLineNumber() { return lineNumber; } public URL getURL() { return url; } @Override public void show(int kind, int column) { } @Override public void setBreakpoint(boolean b) { } @Override public boolean isBreakpoint() { return false; } @Override public void markError() {} @Override public void unmarkError() {} @Override public void markCurrentLine() {} @Override public void unmarkCurrentLine() {} }
589
486
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2001 <NAME> <<EMAIL>> * * Copyright (C) 2001 <NAME> <<EMAIL>> * * All rights reserved. * * * * License: BSD * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * General interface for nodes in the abstract syntax tree. Contains only the method toString which * is already inherited from Object, so the interface doesn't add any functionality. It only * provides a common super type for all elements in the AST. */ interface AST { public String toString(); // already inherited from Object }
502
2,160
{ "build": { "dockerfile": "Dockerfile" }, "extensions": [ "dbaeumer.vscode-eslint", "ms-vscode.vscode-typescript-tslint-plugin" ], "postCreateCommand": "yarn" }
85
362
<filename>whois-rpsl/src/main/java/net/ripe/db/whois/common/rpsl/attrs/Inet6numStatus.java<gh_stars>100-1000 package net.ripe.db.whois.common.rpsl.attrs; import com.google.common.collect.Sets; import net.ripe.db.whois.common.domain.CIString; import java.util.Arrays; import java.util.EnumMap; import java.util.EnumSet; import java.util.Set; import static net.ripe.db.whois.common.domain.CIString.ciString; import static net.ripe.db.whois.common.rpsl.attrs.OrgType.IANA; import static net.ripe.db.whois.common.rpsl.attrs.OrgType.LIR; import static net.ripe.db.whois.common.rpsl.attrs.OrgType.OTHER; import static net.ripe.db.whois.common.rpsl.attrs.OrgType.RIR; public enum Inet6numStatus implements InetStatus { ALLOCATED_BY_RIR("ALLOCATED-BY-RIR", IANA, RIR, LIR), ALLOCATED_BY_LIR("ALLOCATED-BY-LIR", LIR, OTHER), AGGREGATED_BY_LIR("AGGREGATED-BY-LIR", LIR, OTHER), ASSIGNED("ASSIGNED", LIR, OTHER), ASSIGNED_ANYCAST("ASSIGNED ANYCAST", LIR, OTHER), ASSIGNED_PI("ASSIGNED PI", LIR, OTHER); private static final EnumSet<Inet6numStatus> RS_MNTNER_STATUSES = EnumSet.of(ASSIGNED_PI, ASSIGNED_ANYCAST, ALLOCATED_BY_RIR); private static final EnumSet<Inet6numStatus> ALLOC_MNTNER_STATUSES = EnumSet.of(ALLOCATED_BY_RIR); private static final EnumSet<Inet6numStatus> NEEDS_ORG_REFERENCE = EnumSet.of(ASSIGNED_ANYCAST, ALLOCATED_BY_RIR, ASSIGNED_PI); private static final EnumMap<Inet6numStatus, EnumSet<Inet6numStatus>> PARENT_STATUS; static { PARENT_STATUS = new EnumMap(Inet6numStatus.class); PARENT_STATUS.put(ALLOCATED_BY_RIR, EnumSet.of(ALLOCATED_BY_RIR)); PARENT_STATUS.put(ALLOCATED_BY_LIR, EnumSet.of(ALLOCATED_BY_RIR, ALLOCATED_BY_LIR)); PARENT_STATUS.put(AGGREGATED_BY_LIR, EnumSet.of(ALLOCATED_BY_RIR, ALLOCATED_BY_LIR, AGGREGATED_BY_LIR)); PARENT_STATUS.put(ASSIGNED, EnumSet.of(ALLOCATED_BY_RIR, ALLOCATED_BY_LIR, AGGREGATED_BY_LIR)); PARENT_STATUS.put(ASSIGNED_ANYCAST, EnumSet.of(ALLOCATED_BY_RIR)); PARENT_STATUS.put(ASSIGNED_PI, EnumSet.of(ALLOCATED_BY_RIR)); } private final CIString literalStatus; private final Set<OrgType> allowedOrgTypes; Inet6numStatus(final String literalStatus, final OrgType... orgType) { this.literalStatus = ciString(literalStatus); this.allowedOrgTypes = Sets.immutableEnumSet(Arrays.asList(orgType)); } public static Inet6numStatus getStatusFor(final CIString status) { for (final Inet6numStatus stat : Inet6numStatus.values()) { if (stat.literalStatus.equals(status)) { return stat; } } throw new IllegalArgumentException(status + " is not a valid inet6numstatus"); } public CIString getLiteralStatus() { return literalStatus; } @Override public boolean requiresRsMaintainer() { return RS_MNTNER_STATUSES.contains(this); } @Override public boolean requiresAllocMaintainer() { return ALLOC_MNTNER_STATUSES.contains(this); } @Override public boolean worksWithParentStatus(final InetStatus parent, boolean objectHasRsMaintainer) { return PARENT_STATUS.get(this).contains(parent); } @Override public boolean worksWithParentInHierarchy(final InetStatus parentInHierarchyMaintainedByRs, final boolean parentHasRsMntLower) { return true; } @Override public boolean needsOrgReference() { return NEEDS_ORG_REFERENCE.contains(this); } @Override public Set<OrgType> getAllowedOrgTypes() { return allowedOrgTypes; } @Override public boolean isValidOrgType(final OrgType orgType) { return allowedOrgTypes.contains(orgType); } @Override public String toString() { return literalStatus.toString(); } }
1,621
3,442
<filename>mmdnn/conversion/examples/mxnet/imagenet_test.py<gh_stars>1000+ #---------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. #---------------------------------------------------------------------------------------------- from collections import namedtuple import numpy as np from mmdnn.conversion.examples.imagenet_test import TestKit import mxnet as mx Batch = namedtuple('Batch', ['data']) class TestMXNet(TestKit): def __init__(self): super(TestMXNet, self).__init__() self.truth['tensorflow']['inception_v3'] = [(22, 9.6691055), (24, 4.3524752), (25, 3.5957956), (132, 3.5657482), (23, 3.3462858)] self.truth['keras']['inception_v3'] = [(21, 0.93430501), (23, 0.0028834261), (131, 0.0014781745), (24, 0.0014518937), (22, 0.0014435325)] self.model = self.MainModel.RefactorModel() self.model = self.MainModel.deploy_weight(self.model, self.args.w) def preprocess(self, image_path): self.data = super(TestMXNet, self).preprocess(image_path) self.data = np.swapaxes(self.data, 0, 2) self.data = np.swapaxes(self.data, 1, 2) self.data = np.expand_dims(self.data, 0) def print_result(self): self.model.forward(Batch([mx.nd.array(self.data)])) prob = self.model.get_outputs()[0].asnumpy() super(TestMXNet, self).print_result(prob) def inference(self, image_path): self.preprocess(image_path) # self.print_intermediate_result('pooling0', False) self.print_result() self.test_truth() def print_intermediate_result(self, layer_name, if_transpose = False): internals = self.model.symbol.get_internals() intermediate_output = internals[layer_name + "_output"] test_model = mx.mod.Module(symbol=intermediate_output, context=mx.cpu(), data_names=['data']) if self.args.preprocess == 'vgg19' or self.args.preprocess == 'inception_v1': test_model.bind(for_training=False, data_shapes = [('data', (1, 3, 224, 224))]) elif 'resnet' in self.args.preprocess or self.args.preprocess == 'inception_v3': test_model.bind(for_training=False, data_shapes = [('data', (1, 3, 299, 299))]) else: assert False arg_params, aux_params = self.model.get_params() test_model.set_params(arg_params = arg_params, aux_params = aux_params, allow_missing = True, allow_extra = True) test_model.forward(Batch([mx.nd.array(self.data)])) intermediate_output = test_model.get_outputs()[0].asnumpy() super(TestMXNet, self).print_intermediate_result(intermediate_output, if_transpose) def dump(self, path = None): if path is None: path = self.args.dump self.model.save_checkpoint(path, 0) print ('MXNet checkpoint file is saved with prefix [{}] and iteration 0, generated by [{}.py] and [{}].'.format( path, self.args.n, self.args.w)) if __name__ == '__main__': tester = TestMXNet() if tester.args.dump: tester.dump() else: tester.inference(tester.args.image)
1,316
386
#pragma once #include <QTableWidget> class CEasyTableWidget : public QTableWidget { public: CEasyTableWidget(QWidget * parent = Q_NULLPTR); ~CEasyTableWidget(); void reset(); QTableWidgetItem* setCellText(int row, int column, const QString& text); QTableWidgetItem* setCellText(int row, int column, const QStringRef& text) { return setCellText(row, column, text.toString()); } };
133
190,993
<gh_stars>1000+ /* Copyright 2015 The TensorFlow Authors. All Rights Reserved. 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. ==============================================================================*/ #include "tensorflow/core/util/saved_tensor_slice_util.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/protobuf.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace checkpoint { namespace { // Testing serialization of tensor name and tensor slice in the ordered code // format. TEST(TensorShapeUtilTest, TensorNameSliceToOrderedCode) { { TensorSlice s = TensorSlice::ParseOrDie("-:-:1,3:4,5"); string buffer = EncodeTensorNameSlice("foo", s); string name; s.Clear(); TF_CHECK_OK(DecodeTensorNameSlice(buffer, &name, &s)); EXPECT_EQ("foo", name); EXPECT_EQ("-:-:1,3:4,5", s.DebugString()); } } } // namespace } // namespace checkpoint } // namespace tensorflow
483
432
<filename>debugger/src/cpu_sysc_plugin/riverlib/cache/cache_top.h /* * Copyright 2019 <NAME>, <EMAIL> * * 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. */ #ifndef __DEBUGGER_RIVERLIB_CACHE_TOP_H__ #define __DEBUGGER_RIVERLIB_CACHE_TOP_H__ #include <systemc.h> #include "../river_cfg.h" #include "icache_lru.h" #include "dcache_lru.h" #include "mpu.h" #include "../core/queue.h" namespace debugger { SC_MODULE(CacheTop) { sc_in<bool> i_clk; // CPU clock sc_in<bool> i_nrst; // Reset active LOW // Control path: sc_in<bool> i_req_ctrl_valid; // Control request from CPU Core is valid sc_in<sc_uint<CFG_CPU_ADDR_BITS>> i_req_ctrl_addr; // Control request address sc_out<bool> o_req_ctrl_ready; // Control request from CPU Core is accepted sc_out<bool> o_resp_ctrl_valid; // ICache response is valid and can be accepted sc_out<sc_uint<CFG_CPU_ADDR_BITS>> o_resp_ctrl_addr; // ICache response address sc_out<sc_uint<32>> o_resp_ctrl_data; // ICache read data sc_out<bool> o_resp_ctrl_load_fault; // Bus response ERRSLV or ERRDEC on read sc_out<bool> o_resp_ctrl_executable; // MPU flag: executable sc_in<bool> i_resp_ctrl_ready; // CPU Core is ready to accept ICache response // Data path: sc_in<bool> i_req_data_valid; // Data path request from CPU Core is valid sc_in<sc_uint<MemopType_Total>> i_req_data_type; // Data write memopy operation flag sc_in<sc_uint<CFG_CPU_ADDR_BITS>> i_req_data_addr; // Memory operation address sc_in<sc_uint<64>> i_req_data_wdata; // Memory operation write value sc_in<sc_uint<8>> i_req_data_wstrb; // 8-bytes aligned strob sc_in<sc_uint<2>> i_req_data_size; sc_out<bool> o_req_data_ready; // Memory operation request accepted by DCache sc_out<bool> o_resp_data_valid; // DCache response is ready sc_out<sc_uint<CFG_CPU_ADDR_BITS>> o_resp_data_addr; // DCache response address sc_out<sc_uint<64>> o_resp_data_data; // DCache response read data sc_out<sc_uint<CFG_CPU_ADDR_BITS>> o_resp_data_fault_addr; // AXI B-channel error sc_out<bool> o_resp_data_load_fault; // Bus response ERRSLV or ERRDEC on read sc_out<bool> o_resp_data_store_fault; // Bus response ERRSLV or ERRDEC on write sc_out<bool> o_resp_data_er_mpu_load; sc_out<bool> o_resp_data_er_mpu_store; sc_in<bool> i_resp_data_ready; // CPU Core is ready to accept DCache repsonse // Memory interface: sc_in<bool> i_req_mem_ready; // System Bus (AXI) is available sc_out<bool> o_req_mem_path; // 0=ctrl; 1=data path sc_out<bool> o_req_mem_valid; // Memory operation to system bus is valid sc_out<sc_uint<REQ_MEM_TYPE_BITS>> o_req_mem_type; // Memory operation type sc_out<sc_uint<3>> o_req_mem_size; sc_out<sc_uint<CFG_CPU_ADDR_BITS>> o_req_mem_addr; // Requesting address sc_out<sc_uint<L1CACHE_BYTES_PER_LINE>> o_req_mem_strob; // Writing strob 1 bit per 1 byte (AXI compliance) sc_out<sc_biguint<L1CACHE_LINE_BITS>> o_req_mem_data; // Writing value sc_in<bool> i_resp_mem_valid; // Memory operation from system bus is completed sc_in<bool> i_resp_mem_path; // 0=ctrl; 1=data path sc_in<sc_biguint<L1CACHE_LINE_BITS>> i_resp_mem_data; // Read value sc_in<bool> i_resp_mem_load_fault; // Bus response with SLVERR or DECERR on read sc_in<bool> i_resp_mem_store_fault; // Bus response with SLVERR or DECERR on write // MPU interface sc_in<bool> i_mpu_region_we; sc_in<sc_uint<CFG_MPU_TBL_WIDTH>> i_mpu_region_idx; sc_in<sc_uint<CFG_CPU_ADDR_BITS>> i_mpu_region_addr; sc_in<sc_uint<CFG_CPU_ADDR_BITS>> i_mpu_region_mask; sc_in<sc_uint<CFG_MPU_FL_TOTAL>> i_mpu_region_flags; // {ena, cachable, r, w, x} // D$ Snoop interface sc_in<bool> i_req_snoop_valid; sc_in<sc_uint<SNOOP_REQ_TYPE_BITS>> i_req_snoop_type; sc_out<bool> o_req_snoop_ready; sc_out<sc_uint<CFG_CPU_ADDR_BITS>> i_req_snoop_addr; sc_in<bool> i_resp_snoop_ready; sc_out<bool> o_resp_snoop_valid; sc_out<sc_biguint<L1CACHE_LINE_BITS>> o_resp_snoop_data; sc_out<sc_uint<DTAG_FL_TOTAL>> o_resp_snoop_flags; // Debug signals: sc_in<sc_uint<CFG_CPU_ADDR_BITS>> i_flush_address; // clear ICache address from debug interface sc_in<bool> i_flush_valid; // address to clear icache is valid sc_in<sc_uint<CFG_CPU_ADDR_BITS>> i_data_flush_address; sc_in<bool> i_data_flush_valid; sc_out<bool> o_data_flush_end; void comb(); SC_HAS_PROCESS(CacheTop); CacheTop(sc_module_name name_, bool async_reset, bool coherence_ena); virtual ~CacheTop(); void generateVCD(sc_trace_file *i_vcd, sc_trace_file *o_vcd); private: static const int DATA_PATH = 0; static const int CTRL_PATH = 1; static const int QUEUE_WIDTH = CFG_CPU_ADDR_BITS // addr + REQ_MEM_TYPE_BITS // req_type + 3 // req_size + 1 // 0=instruction; 1=data ; struct CacheOutputType { sc_signal<bool> req_mem_valid; sc_signal<sc_uint<REQ_MEM_TYPE_BITS>> req_mem_type; sc_signal<sc_uint<3>> req_mem_size; sc_signal<sc_uint<CFG_CPU_ADDR_BITS>> req_mem_addr; sc_signal<sc_uint<DCACHE_BYTES_PER_LINE>> req_mem_strob; sc_signal<sc_biguint<DCACHE_LINE_BITS>> req_mem_wdata; sc_signal<sc_uint<CFG_CPU_ADDR_BITS>> mpu_addr; }; CacheOutputType i, d; // Memory Control interface: sc_signal<bool> w_ctrl_resp_mem_data_valid; sc_signal<sc_biguint<ICACHE_LINE_BITS>> wb_ctrl_resp_mem_data; sc_signal<bool> w_ctrl_resp_mem_load_fault; sc_signal<bool> w_resp_ctrl_writable_unused; sc_signal<bool> w_resp_ctrl_readable_unused; sc_signal<bool> w_ctrl_req_ready; // Memory Data interface: sc_signal<bool> w_data_resp_mem_data_valid; sc_signal<sc_biguint<DCACHE_LINE_BITS>> wb_data_resp_mem_data; sc_signal<bool> w_data_resp_mem_load_fault; sc_signal<bool> w_data_req_ready; sc_signal<sc_uint<CFG_MPU_FL_TOTAL>> wb_mpu_iflags; sc_signal<sc_uint<CFG_MPU_FL_TOTAL>> wb_mpu_dflags; sc_signal<bool> queue_re_i; sc_signal<bool> queue_we_i; sc_signal<sc_biguint<QUEUE_WIDTH>> queue_wdata_i; sc_signal<sc_biguint<QUEUE_WIDTH>> queue_rdata_o; sc_signal<bool> queue_full_o; sc_signal<bool> queue_nempty_o; ICacheLru *i1; DCacheLru *d0; MPU *mpu0; Queue<2, QUEUE_WIDTH> *queue0; #ifdef DBG_ICACHE_TB ICache_tb *i0_tb; #endif bool async_reset_; }; } // namespace debugger #endif // __DEBUGGER_RIVERLIB_CACHE_TOP_H__
3,702
534
package mekanism.common.inventory.container; import javax.annotation.Nonnull; import javax.annotation.Nullable; import mekanism.api.text.ILangEntry; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.IContainerProvider; import net.minecraft.inventory.container.INamedContainerProvider; import net.minecraft.util.text.ITextComponent; public class ContainerProvider implements INamedContainerProvider { private final ITextComponent displayName; private final IContainerProvider provider; public ContainerProvider(ILangEntry translationHelper, IContainerProvider provider) { this(translationHelper.translate(), provider); } public ContainerProvider(ITextComponent displayName, IContainerProvider provider) { this.displayName = displayName; this.provider = provider; } @Nullable @Override public Container createMenu(int i, @Nonnull PlayerInventory inv, @Nonnull PlayerEntity player) { return provider.createMenu(i, inv, player); } @Nonnull @Override public ITextComponent getDisplayName() { return displayName; } }
378
1,061
package city.thesixsectorteam.wheelworld.plague.dao; import city.thesixsectorteam.wheelworld.plague.domain.Plague; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; /** * 类/方法名称:PlagueDao * 类/方法描述: * 创建人:mango * 创建时间: 2019/12/28 * 修改备注: */ @Repository public interface PlagueDao extends BaseMapper<Plague> { /** * 查找所有的 */ List<Plague> findAll(); /** * 根据 PLAGUE_ID 查找单个 */ Plague findById(@Param("plagueId") Long plagueId); /** * 根据 plague 进行更新 */ void updateByPlagueEntity(@Param("plague") Plague plague); /** * 新增 PLAGUE */ void addPlague(@Param("plague") Plague plague); /** * 通过PLAGUE_ID删除单个 plague */ void deleteByPlague(@Param("plagueId") Long plagueId); /** * 通过PLAGUE_ID 批量删除 */ void deleteByPlagues(@Param("list") List list); }
524
3,084
<filename>network/wlan/WDI/COMMON/SecurityGen.c<gh_stars>1000+ #include "Mp_Precomp.h" #if WPP_SOFTWARE_TRACE #include "SecurityGen.tmh" #endif //===========Define Local Function Protype=================== BOOLEAN SecCheckMIC( PADAPTER Adapter, PRT_RFD pRfd ) { OCTET_STRING frame; u1Byte DestAddr[6]; RT_ENC_ALG EncAlgorithm; PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; BOOLEAN bResult = TRUE; FillOctetString(frame, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); //2004/07/12, kcwu, //Check if the packet is encrypted if(!Frame_WEP(frame)) { return bResult; } //2004/07/12, kcwu //Find the algorithm that should be used PlatformMoveMemory(DestAddr, Frame_Addr1(frame), ETHERNET_ADDRESS_LENGTH); EncAlgorithm = (MacAddr_isMulticast(DestAddr)?pSec->GroupEncAlgorithm:pSec->PairwiseEncAlgorithm); switch(EncAlgorithm){ case RT_ENC_ALG_TKIP: bResult = SecCheckTKIPMIC(Adapter, pRfd); break; case RT_ENC_ALG_AESCCMP: //2004/07/12, kcwu //Check AES MIC break; default: bResult = TRUE; } return bResult; } // // Description: // Figure out TKIP MIC from packet content and compare it to // MIC of packet received. // // 2004.10.08, by rcnjko. // BOOLEAN SecCheckTKIPMIC( PADAPTER Adapter, PRT_RFD pRfd ) { u1Byte DestAddr[6]; u1Byte SrcAddr[6]; u1Byte Keyidx = 0; u1Byte Qos[4]; MicData micdata; u1Byte mic_for_check[8], mic_from_packet[8]; OCTET_STRING frame = {0}; PMGNT_INFO pMgntInfo = &Adapter->MgntInfo; PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; PRT_RFD pPrevRfd = NULL; PRT_RFD pCurrRfd = NULL; pu1Byte pCurrBuffer = NULL; int CurrBufferLen = 0; PRT_WLAN_STA pEntry =NULL; u1Byte IVOffset; // Added by Annie, 2005-12-23. u1Byte IVKeyIdOffset; // <RJ_TODO> This is just a workaround for HCT 12.1, 2005.07.11, by rcnjko. if(pMgntInfo->mIbss) { return TRUE; } // <RJ_TODO> This is just a workaround for WiFi 5.2.2.4 S2 might failed // in unknown condition. For example, we think the packets received is TKIP MIC error // during this test and finally trigger counter measure. 2005.09.06, by rcnjko. // Prefast warning C28182: Dereferencing NULL pointer. 'pRfd' contains NULL. if(pRfd != NULL && pRfd->nTotalFrag > 1) { return TRUE; } // Initialize first buffer of the packet to as header. // Prefast warning C6011: Dereferencing NULL pointer 'pRfd'. if (pRfd != NULL) { FillOctetString(frame, pRfd->Buffer.VirtualAddress, (u2Byte)pRfd->FragLength); } //PRINT_DATA("Recieved Packet==>", pRfd->Buffer.VirtualAddress, pRfd->FragLength); // Get offset. Added by Annie, 2005-12-22. if(pRfd != NULL && pRfd->Status.bIsQosData ) { IVOffset = sMacHdrLng + sQoSCtlLng; } else { IVOffset = sMacHdrLng; } // Prefast warning C6011: Dereferencing NULL pointer 'pRfd'. if(pRfd != NULL && pRfd->Status.bContainHTC) IVOffset += sHTCLng; IVKeyIdOffset = IVOffset + KEYID_POS_IN_IV; // Packet length check. if(pRfd != NULL && pRfd->PacketLength < IVOffset ) { RT_TRACE(COMP_DBG, DBG_LOUD, ("SecCheckTKIPMIC(): pRfd->PacketLength < IVOffset\n")); return FALSE; // Drop the packet. } // Prefast warning C6011: Dereferencing NULL pointer 'frame.Octet'. if (frame.Octet != NULL) { // Get DestAddr from header. //Modified by Jay 0713 PlatformMoveMemory(DestAddr, Frame_pDaddr(frame), ETHERNET_ADDRESS_LENGTH); // Get SrcAddr from header. PlatformMoveMemory(SrcAddr, Frame_pSaddr(frame), ETHERNET_ADDRESS_LENGTH); } // Step 1. Set key. // Prefast warning C6011: Dereferencing NULL pointer 'frame.Octet' if(ACTING_AS_AP(Adapter) && frame.Octet != NULL) //Added by Jay for SwAP 0708 { // AP Mode. pEntry = AsocEntry_GetEntry(pMgntInfo, Frame_pSaddr(frame)); if(pEntry == NULL) return FALSE; if(pEntry->perSTAKeyInfo.RxMICKey == NULL) return FALSE; SecMICSetKey(&micdata, pEntry->perSTAKeyInfo.RxMICKey); } else if(pRfd != NULL && pRfd->bTDLPacket) { pEntry = AsocEntry_GetEntry(pMgntInfo, Frame_pSaddr(frame)); if(pEntry == NULL) return FALSE; if(pEntry->perSTAKeyInfo.TxMICKey == NULL) return FALSE; SecMICSetKey(&micdata, pEntry->perSTAKeyInfo.TxMICKey); } else { // STA Mode. // Get key index. // Prefast warning C6011: Dereferencing NULL pointer 'frame.Octet' if(frame.Octet != NULL) Keyidx = SecGetRxKeyIdx( Adapter, DestAddr, ((frame.Octet[IVKeyIdOffset]>>6)&0x03) ); // Changed by Annie, 2005-12-22. //RT_TRACE(COMP_DBG, DBG_LOUD, ("SecCheckTKIPMIC(): Keyidx: %d\n", Keyidx)); if(Keyidx > 4) { RT_TRACE(COMP_SEC, DBG_LOUD, ("SecCheckTKIPMIC(): Keyidx: %d > 4\n", Keyidx)); return FALSE; // Drop the packet. } SecMICSetKey(&micdata, pSec->KeyBuf[Keyidx]+TKIP_MICKEYTX_POS); } // Step 2. Append DestAddr and SrcAddr into micdata. SecMICAppend(&micdata, DestAddr, ETHERNET_ADDRESS_LENGTH); SecMICAppend(&micdata, SrcAddr, ETHERNET_ADDRESS_LENGTH); // Step 3. Append Qos into micdata. PlatformZeroMemory(Qos, 4); if(pRfd != NULL && pRfd->Status.bIsQosData ) { // Parsing priority to calculate TKIP MIC. Annie, 2005-12-22. Qos[0] = GET_QOS_CTRL_WMM_UP(frame.Octet); } SecMICAppend(&micdata, Qos, 4); // Step 4. Append each buffers of the packet into micdata. pCurrRfd = pRfd; pPrevRfd = pRfd; // 2010/04/30 MH Prevent BSOD when copy mem from NULL ptr at below case. //Exclude header of first buffer of the packet. // Prefast warning C28182: Dereferencing NULL pointer. 'pCurrRfd' contains NULL if (pCurrRfd != NULL) { pCurrBuffer = pCurrRfd->Buffer.VirtualAddress + (IVOffset + pSec->EncryptionHeadOverhead); CurrBufferLen = (int)(pCurrRfd->FragLength) - ((int)(IVOffset)+(int)(pSec->EncryptionHeadOverhead)); } while(pCurrRfd != NULL) { // Get MIC of the Last buffer and exclude MIC from it. if(pCurrRfd->NextRfd == NULL) { if(CurrBufferLen >= TKIP_MIC_LEN) { // MIC is not fragmented. // Get MIC. PlatformMoveMemory( mic_from_packet, pCurrBuffer + CurrBufferLen - TKIP_MIC_LEN, TKIP_MIC_LEN); // Adjust size to append into micdata. CurrBufferLen -= TKIP_MIC_LEN; } else { // MIC is fragmented into two part. int cbMicInPrev = TKIP_MIC_LEN - CurrBufferLen; RT_ASSERT(pPrevRfd != NULL, ("SecCheckTKIPMIC(): pRevRfd should not be NULL in this case.\n")); // Get MIC. PlatformMoveMemory( mic_from_packet, pPrevRfd->Buffer.VirtualAddress + pPrevRfd->FragLength - cbMicInPrev, cbMicInPrev); PlatformMoveMemory( mic_from_packet + cbMicInPrev, pCurrBuffer, CurrBufferLen); // Adjust size to append into micdata. CurrBufferLen = 0; } } else if(pCurrRfd->NextRfd->NextRfd == NULL) { // In case if MIC is fragmented, we must take care about the last two fragment. if(pCurrRfd->NextRfd->FragLength < TKIP_MIC_LEN) { // MIC is fragmented. int cbMicInPrev = TKIP_MIC_LEN - pCurrRfd->NextRfd->FragLength; RT_ASSERT(CurrBufferLen >= TKIP_MIC_LEN, ("SecCheckTKIPMIC(): the length of last two buffer: %d\n", CurrBufferLen)); // Adjust size to append into micdata. CurrBufferLen -= cbMicInPrev; } } // Append this buffer into micdata. if(CurrBufferLen > 0) { SecMICAppend(&micdata, pCurrBuffer, CurrBufferLen); } // Next one. pPrevRfd = pCurrRfd; pCurrRfd = pCurrRfd->NextRfd; if(pCurrRfd != NULL) { pCurrBuffer = pCurrRfd->Buffer.VirtualAddress + pCurrRfd->FragOffset; CurrBufferLen = pCurrRfd->FragLength; } else { pCurrBuffer = NULL; CurrBufferLen = 0; } } // Figure out MIC from micdata. SecMICGetMIC(&micdata, mic_for_check); // PRINT_DATA((const void*)"mic_for_check===>", (const void*)mic_for_check, TKIP_MIC_LEN); // PRINT_DATA((const void*)"mic_from_packet===>", (const void*)mic_from_packet, TKIP_MIC_LEN); // Compare two MICs. if(PlatformCompareMemory(mic_for_check, mic_from_packet,TKIP_MIC_LEN)) { // Different! BOOLEAN bMcstDest = MacAddr_isMulticast(DestAddr); // Prefast warning 6011: Dereferencing NULL pointer 'pRfd'. if (pRfd != NULL) { RT_TRACE(COMP_SEC, DBG_WARNING, ("Rx:TKIP_MIC Error, Decrypted: %x, bMcstDest: %d\n", pRfd->Status.Decrypted, bMcstDest)); RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "SecCheckTKIPMIC(): TKIP_MIC Error packet", pRfd->Buffer.VirtualAddress, pRfd->FragLength); } if (frame.Octet != NULL) { if (IsDataFrame(frame.Octet)) CountRxTKIPLocalMICFailuresStatistics(Adapter, pRfd); else if (IsMgntFrame(frame.Octet)) CountRxMgntTKIPLocalMICFailuresStatistics(Adapter, pRfd); } // Handle TKIP MIC error. if(ACTING_AS_AP(Adapter)) //Added by Jay 0708. { // AP Mode. //Enter integrity failure state... Authenticator_StateINTEGRITYFAILURE(Adapter, pEntry); } else if(pRfd != NULL && pRfd->bTDLPacket) { Authenticator_StateINTEGRITYFAILURE(Adapter, pEntry); } else { // STA Mode. // We don't indication MIC ERROR in MFP Packet !! // Prefast warning C28182: Dereferencing NULL pointer. 'pRfd' contains the same NULL value as 'pCurrRfd' did. if(pRfd != NULL && !pRfd->Status.bRxMFPPacket ) PlatformHandleTKIPMICError(Adapter, bMcstDest, Keyidx, SrcAddr); } return FALSE; } else { // The same. RT_TRACE(COMP_DBG, DBG_LOUD, ("Rx:TKIP_MIC Ok\n")); return TRUE; } } u1Byte SecGetRxKeyIdx( PADAPTER Adapter, pu1Byte pDestAddr, u1Byte IVKeyIdx ) { u1Byte keyidx = PAIRWISE_KEYIDX; PMGNT_INFO pMgntInfo = &Adapter->MgntInfo; PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; //pairwise keyidx in our driver is 4 if(MacAddr_isMulticast(pDestAddr)) { //2004/07/07, kcwu, if it is a multicast packet //keyidx = ((pSec->KeyLen[pSec->GroupTransmitKeyIdx]==0)?5:pSec->GroupTransmitKeyIdx); // Use IV's Key ID for group key. // 2004.10.06, by rcnjko. if(pSec->KeyLen[IVKeyIdx] == 0) { keyidx = 5; } else { keyidx = IVKeyIdx; } } else { //2004/07/07, kcwu, if it is a unicast packet if(pSec->KeyLen[PAIRWISE_KEYIDX] == 0) { //2004/07/07, kcwu, if there is no pairwise key keyidx = ((pMgntInfo->mIbss&&pSec->KeyLen[pSec->GroupTransmitKeyIdx]!=0)?pSec->GroupTransmitKeyIdx:5); } } return keyidx; } /*2004/06/28, kcwu We don't fill security header of all fragment here, the for statement should in the outside function, not in this function. So just simply provide the start of packet. */ VOID SecHeaderFillIV( PADAPTER Adapter, pu1Byte PacketStart ) { PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; OCTET_STRING oFrame = {0,0}; RT_ENC_ALG SelectEncAlgorithm = pSec->PairwiseEncAlgorithm; BOOLEAN show = FALSE; //Address 1 is always receiver's address pu1Byte pRA = PacketStart+4; pu1Byte pSecHeader = PacketStart + sMacHdrLng; if(pMgntInfo->SafeModeEnabled) return; if( IsQoSDataFrame(PacketStart) ) { pSecHeader += sQoSCtlLng; } // Check address 4 valiaddr , add for BT // Note : AP WDS mode need to do .... oFrame.Octet = PacketStart; if( Frame_ValidAddr4( oFrame ) ) { RT_TRACE( COMP_SEC , DBG_LOUD, ("===>SecHeaderFillIV() : 4 address data \n") ); SelectEncAlgorithm = RT_ENC_ALG_AESCCMP; pSecHeader += 6; show = TRUE; } switch(SelectEncAlgorithm){ case RT_ENC_ALG_WEP104: case RT_ENC_ALG_WEP40: { // CKIP should also go into this case. pSecHeader[0] = EF1Byte( (u1Byte) (((pSec->TxIV&0x00000000ffffffff) >>16) & 0xff) ); pSecHeader[1] = EF1Byte( (u1Byte) (((pSec->TxIV&0x00000000ffffffff) >>8) & 0xff) ); pSecHeader[2] = EF1Byte( (u1Byte) (((pSec->TxIV&0x00000000ffffffff) >>0) & 0xff) ); pSec->TxIV = (pSec->TxIV == 0xffffff)?0:pSec->TxIV+1; //Default Key ID pSecHeader[3] = EF1Byte( (u1Byte)((pSec->DefaultTransmitKeyIdx<<6)&0xc0) ); } break; case RT_ENC_ALG_TKIP: { if(!ACTING_AS_AP(Adapter)) { // STA. u2Byte u2IV16 = (u2Byte)(pSec->TxIV& UINT64_C(0x000000000000ffff) ); u4Byte u4IV32 = (u4Byte)(((pSec->TxIV& UINT64_C(0x0000ffffffff0000) ) >> 16)& UINT64_C(0x00000000ffffffff) ); pSec->TxIV++; //keyid is always 0 for STA TKIP_TSC_DECIMAL2ARRAY(u2IV16, u4IV32, 0, pSecHeader); } else { // AP. if(!MacAddr_isMulticast(pRA)) { // Unicast. PMGNT_INFO pMgntInfo = &Adapter->MgntInfo; PRT_WLAN_STA pEntry; u2Byte u2IV16; u4Byte u4IV32; pEntry = AsocEntry_GetEntry(pMgntInfo, pRA); // Annie for debug, 2005-07-25. RT_ASSERT( pEntry!=NULL, ("SecHeaderFillIV(): pEntry is NULL!\n")); if( pEntry==NULL ) return; u2IV16 = (u2Byte)(pEntry->perSTAKeyInfo.TxIV & UINT64_C(0x000000000000ffff) ); u4IV32 = (u4Byte)(((pEntry->perSTAKeyInfo.TxIV& UINT64_C(0x0000ffffffff0000) ) >> 16)& UINT64_C(0x00000000ffffffff) ); pEntry->perSTAKeyInfo.TxIV++; //keyid is always 0 for STA TKIP_TSC_DECIMAL2ARRAY(u2IV16, u4IV32, 0, pSecHeader); } else { // Mcst/Bcst u2Byte u2IV16 = (u2Byte)(pSec->TxIV& UINT64_C(0x000000000000ffff) ); u4Byte u4IV32 = (u4Byte)(((pSec->TxIV& UINT64_C( 0x0000ffffffff0000) ) >> 16)& UINT64_C(0x00000000ffffffff)); pSec->TxIV++; // <TODO> This is just a workaround, we assume group keyid=1. TKIP_TSC_DECIMAL2ARRAY(u2IV16, u4IV32, 1, pSecHeader); } } } break; case RT_ENC_ALG_AESCCMP: if(!pMgntInfo->bRSNAPSKMode && !ACTING_AS_AP(Adapter) ) { if(show) { RT_TRACE( COMP_SEC , DBG_LOUD , ("===>ccw Ok \n") ); } PN_DECIMAL2ARRAY((pSec->TxIV& UINT64_C(0xffffffff00000000) ), (pSec->TxIV& UINT64_C(0x00000000ffffffff)), PAIRWISE_KEYIDX, //keyid = 0 for pairwise packet pSecHeader); pSec->TxIV++; } else if( ACTING_AS_AP(Adapter) ) { if(!MacAddr_isMulticast(pRA)) { // Pairwise traffic. PMGNT_INFO pMgntInfo = &Adapter->MgntInfo; PRT_WLAN_STA pEntry; pEntry = AsocEntry_GetEntry(pMgntInfo, pRA); if( pEntry==NULL ) return; PN_DECIMAL2ARRAY((pEntry->perSTAKeyInfo.TxIV& UINT64_C(0xffffffff00000000)), (pEntry->perSTAKeyInfo.TxIV& UINT64_C(0x00000000ffffffff)), 0, //keyid = 0 for pairwise packet pSecHeader); pEntry->perSTAKeyInfo.TxIV++; } else { // Group traffic. PN_DECIMAL2ARRAY((pSec->TxIV& UINT64_C(0xffffffff00000000)), (pSec->TxIV& UINT64_C(0x00000000ffffffff)), pSec->GroupTransmitKeyIdx,// 0, pSecHeader); pSec->TxIV++; } } else { if(!MacAddr_isMulticast(pRA)) { // Pairwise traffic. PN_DECIMAL2ARRAY((pSec->TxIV& UINT64_C(0xffffffff00000000) ), (pSec->TxIV&0x00000000ffffffff), PAIRWISE_KEYIDX, //keyid = 0 for pairwise packet pSecHeader); } else { // Group traffic. PN_DECIMAL2ARRAY((pSec->TxIV& UINT64_C(0xffffffff00000000) ), (pSec->TxIV& UINT64_C(0x00000000ffffffff) ), pSec->DefaultTransmitKeyIdx, pSecHeader); } pSec->TxIV++; } break; case RT_ENC_ALG_SMS4: WAPI_SecFuncHandler(WAPI_SECHEADERFILLIV, Adapter, (PVOID)pRA,(PVOID)pSecHeader,WAPI_END); break; case RT_ENC_ALG_NO_CIPHER: default: return; } } // //Note : SecInit() need to Used after SecClearAllKeys(); // Because Clear CAM Key will check SecInfo Key Buffer Length // If Length = 0, CAM entey will "NO" Clear .... VOID SecInit( PADAPTER Adapter ) { PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; s1Byte i = 0; pSec->PairwiseEncAlgorithm = pSec->GroupEncAlgorithm = RT_ENC_ALG_AESCCMP; pSec->DefaultTransmitKeyIdx = 0; pSec->GroupTransmitKeyIdx = 0; SecSetSwEncryptionDecryption(Adapter, FALSE, FALSE); pSec->SWRxAESMICFlag = FALSE; pSec->bGroupKeyFixed = FALSE; pSec->AuthMode = RT_802_11AuthModeWPA2; pSec->EncryptionStatus = RT802_11EncryptionDisabled; pSec->TxIV = DEFAULT_INIT_TX_IV; // 2007.08.08 We must initialize this value, otherwise, software decryption // without initilization of AES mode cause Assertion in Vista. By Lanhsin pSec->AESCCMPMicLen = 8; PlatformZeroMemory(pSec->RSNIEBuf, MAXRSNIELEN); pSec->RSNIE.Length = 0; FillOctetString(pSec->RSNIE, pSec->RSNIEBuf, pSec->RSNIE.Length); pSec->SecLvl = RT_SEC_LVL_WPA2; //2004/09/07, kcwu, initialize key buffer for(i = 0;i<KEY_BUF_SIZE; i++){ PlatformZeroMemory(pSec->AESKeyBuf[i], MAX_KEY_LEN); PlatformZeroMemory(pSec->KeyBuf[i], MAX_KEY_LEN); pSec->KeyLen[i] = 0; } //kcwu_todo: Clear key buffer //Point Pairwise key to appropriate index pSec->PairwiseKey = pSec->KeyBuf[PAIRWISE_KEYIDX]; pSec->UseDefaultKey = FALSE; // WPA2 Pre-Authentication related. Added by Annie, 2006-05-07. pSec->EnablePreAuthentication = pSec->RegEnablePreAuth; // Added by Annie, 2005-02-15. PlatformZeroMemory(pSec->PMKIDList, sizeof(RT_PMKID_LIST)*NUM_PMKID_CACHE); for( i=0; i<NUM_PMKID_CACHE; i++ ) { FillOctetString( pSec->PMKIDList[i].Ssid, pSec->PMKIDList[i].SsidBuf, 0 ); } PlatformZeroMemory(pSec->szCapability, 256); init_crc32(); // Initialize TKIP MIC error related, 2004.10.06, by rcnjko. pSec->LastPairewiseTKIPMICErrorTime = 0; pSec->bToDisassocAfterMICFailureReportSend = FALSE; for(i = 0; i < MAX_DENY_BSSID_LIST_CNT; i++) { pSec->DenyBssidList[i].bUsed = FALSE; } } /* IN PADAPTER Adapter, IN u4Byte KeyIndex, IN pu1Byte pMacAddr, IN BOOLEAN IsGroup, IN u1Byte EncAlgo, IN BOOLEAN IsWEPKey//if OID = OID_802_11_WEP */ // //Note : SecClearAllKeys() need to Used before SecInit(); // Because Clear CAM Key will check SecInfo Key Buffer Length // If Length = 0, CAM entey will "NO" Clear .... VOID SecClearAllKeys( PADAPTER Adapter ) { int i; PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; PlatformZeroMemory(pSec->TxMICKey, TKIP_MIC_KEY_LEN); PlatformZeroMemory(pSec->RxMICKey, TKIP_MIC_KEY_LEN); pSec->DefaultTransmitKeyIdx = 0; Adapter->HalFunc.SetKeyHandler(Adapter, 0, 0, 0, 0, 0, TRUE); // // Clear keys used for RSNA IBSS. // for(i = 0; i < MAX_NUM_PER_STA_KEY; i++) { PlatformZeroMemory( &(pSec->PerStaDefKeyTable[i]), sizeof(PER_STA_DEFAULT_KEY_ENTRY) ); PlatformZeroMemory( &(pSec->MAPKEYTable[i]), sizeof(PER_STA_MPAKEY_ENTRY) ); } } VOID SecClearGroupKeyByIdx( PADAPTER Adapter, u1Byte paraIndex ){ PlatformZeroMemory(Adapter->MgntInfo.SecurityInfo.KeyBuf[paraIndex], MAX_KEY_LEN); Adapter->MgntInfo.SecurityInfo.KeyLen[paraIndex] = 0; Adapter->HalFunc.SetKeyHandler(Adapter, paraIndex, 0, TRUE, Adapter->MgntInfo.SecurityInfo.GroupEncAlgorithm, FALSE, FALSE); } VOID SecClearWEPKeyByIdx( PADAPTER Adapter, u1Byte paraIndex ) { PlatformZeroMemory(Adapter->MgntInfo.SecurityInfo.KeyBuf[paraIndex], MAX_KEY_LEN); Adapter->MgntInfo.SecurityInfo.KeyLen[paraIndex] = 0; Adapter->HalFunc.SetKeyHandler(Adapter, paraIndex, 0, TRUE, Adapter->MgntInfo.SecurityInfo.GroupEncAlgorithm, FALSE, FALSE); } //for AP mode VOID SecClearPairwiseKeyByMacAddr( PADAPTER Adapter, pu1Byte paraMacAddr ) { //2004/09/15, kcwu PlatformZeroMemory(Adapter->MgntInfo.SecurityInfo.PairwiseKey, MAX_KEY_LEN); Adapter->MgntInfo.SecurityInfo.KeyLen[PAIRWISE_KEYIDX] = 0; //2004/09/07, kcwu, disable the key entry in cam Adapter->HalFunc.SetKeyHandler(Adapter, PAIRWISE_KEYIDX, paraMacAddr, FALSE, Adapter->MgntInfo.SecurityInfo.PairwiseEncAlgorithm, FALSE, FALSE); } // // Description: // Select one AKM suite according to the input self AKM suite and the target info. // Arguments: // [in] pAdapter - // The location of target adapter. // [in] AuthMode - // The self AKM suite. // [in] contentType - // The type of pInfoBuf. // [in] pInfoBuf - // This field is determined by contentType and shall be casted to the corresponding type. // pInfoBuf is PRT_WLAN_BSS if contentType is CONTENT_PKT_TYPE_CLIENT. // This field may be NULL according to contentType. // [in] InfoBufLen - // Length in byte of pInfoBuf. // [OUT] pAKM - // Return the selected AKM. // Return: // RT_STATUS_SUCCESS, if the content is appended withour error. // RT_STATUS_INVALID_DATA, if any of pInfoBuf or InfoBufLen is incorrect. // RT_STATUS_INVALID_STATE, if the security parameter is mismatched. // Remark: // If targetAKMSuite is 0, this function ignores the target setting and only reference the self AuthMode to // determine the final AKM_SUITE_TYPE. // By Bruce, 2015-12-16. // RT_STATUS Sec_SelAkmFromAuthMode( IN PADAPTER pAdapter, IN RT_AUTH_MODE AuthMode, IN CONTENT_PKT_TYPE contentType, IN PVOID pInfoBuf, IN u4Byte InfoBufLen, OUT PAKM_SUITE_TYPE pAKM ) { RT_STATUS rtStatus = RT_STATUS_SUCCESS; BOOLEAN bCCX8021xenable = FALSE; BOOLEAN bAPSuportCCKM = FALSE; PRT_WLAN_BSS pTargetBss = NULL; u4Byte ftMDIeLen = 0; AKM_SUITE_TYPE targetAKMSuites = AKM_SUITE_NONE; CHECK_NULL_RETURN_STATUS(pAKM); if(TEST_FLAG(contentType, CONTENT_PKT_TYPE_CLIENT)) { PFT_INFO_ENTRY pEntry = NULL; if(!pInfoBuf || InfoBufLen < sizeof(RT_WLAN_BSS)) { RT_TRACE_F(COMP_SEC, DBG_SERIOUS, ("Invalid input buffer or length, pInfoBuf = %p, InfoBufLen = %d\n", pInfoBuf, InfoBufLen)); return RT_STATUS_INVALID_DATA; } pTargetBss = (PRT_WLAN_BSS)pInfoBuf; targetAKMSuites = pTargetBss->AKMsuit; CCX_QueryCCKMSupport(pAdapter, &bCCX8021xenable, &bAPSuportCCKM); // Check we shall choose Fast Transition as the AKM if(((TEST_FLAG(pTargetBss->AKMsuit, AKM_FT_1X) && TEST_FLAG(pAdapter->MgntInfo.RegCapAKMSuite, AKM_FT_1X)) || (TEST_FLAG(pTargetBss->AKMsuit, AKM_FT_PSK) && TEST_FLAG(pAdapter->MgntInfo.RegCapAKMSuite, AKM_FT_PSK))) && (pEntry = FtGetEntry(pAdapter, pTargetBss->bdBssIdBuf))) { ftMDIeLen = pEntry->MDELen; } } RT_TRACE_F(COMP_SEC, DBG_LOUD, ("AuthMode = %d, RegCapAKMSuite = 0x%08X\n", AuthMode, pAdapter->MgntInfo.RegCapAKMSuite)); switch (AuthMode) { default: rtStatus = RT_STATUS_NOT_RECOGNIZED; break; case RT_802_11AuthModeWPA: if(bCCX8021xenable && bAPSuportCCKM) { *pAKM = AKM_WPA_CCKM; } else { *pAKM = AKM_WPA_1X; } break; case RT_802_11AuthModeWPA2: if(bCCX8021xenable && bAPSuportCCKM) { *pAKM = AKM_WPA2_CCKM; } else if(ftMDIeLen > 0) { *pAKM = AKM_FT_1X; } else if(TEST_FLAG(targetAKMSuites, AKM_RSNA_1X_SHA256) && TEST_FLAG(pAdapter->MgntInfo.RegCapAKMSuite, AKM_RSNA_1X_SHA256)) { *pAKM = AKM_RSNA_1X_SHA256; } else { *pAKM = AKM_WPA2_1X; } break; case RT_802_11AuthModeWPAPSK: *pAKM = AKM_WPA_PSK; break; case RT_802_11AuthModeWPA2PSK: { if(ftMDIeLen > 0) { *pAKM = AKM_FT_PSK; } else if(TEST_FLAG(targetAKMSuites, AKM_RSNA_PSK_SHA256) && TEST_FLAG(pAdapter->MgntInfo.RegCapAKMSuite, AKM_RSNA_PSK_SHA256)) { *pAKM = AKM_RSNA_PSK_SHA256; } else { *pAKM = AKM_WPA2_PSK; } } break; } return rtStatus; } // // Description: // Get the OUI and OUI type from the AKM suite. // Arguments: // [in] AKMSuite - // The AKM suite. // [out] pOUI - // Return the OUI with 3 bytes if returned status is RT_STATUS_SUCCESS. // If AKMSuite is AKM_SUITE_NONE , return all 0 in pOUI. // [out] pOUIType - // Return the OUI type with 1 byte if returned status is RT_STATUS_SUCCESS. // If AKMSuite is AKM_SUITE_NONE , return 0 in pOUIType. // Return: // RT_STATUS_SUCCESS, if the translation succeeds. // RT_STATUS_NOT_RECOGNIZED, if the AKMSuite is not recognized. // RT_STATUS Sec_MapAKMSuiteToOUIType( IN AKM_SUITE_TYPE AKMSuite, OUT pu1Byte pOUI, OUT pu1Byte pOUIType ) { RT_STATUS rtStatus = RT_STATUS_SUCCESS; switch(AKMSuite) { default: rtStatus = RT_STATUS_NOT_RECOGNIZED; break; case AKM_SUITE_NONE: { PlatformZeroMemory(pOUI, SIZE_OUI); PlatformZeroMemory(pOUIType, SIZE_OUI_TYPE); } break; case AKM_WPA_1X: { PlatformMoveMemory(pOUI, WPA_OUI, SIZE_OUI); *pOUIType = AKM_WPA_1X_OUI_TYPE; } break; case AKM_WPA_PSK: { PlatformMoveMemory(pOUI, WPA_OUI, SIZE_OUI); *pOUIType = AKM_WPA_PSK_OUI_TYPE; } break; case AKM_WPA_CCKM: { PlatformMoveMemory(pOUI, CCKM_OUI, SIZE_OUI); *pOUIType = CCKM_OUI_TYPE; } break; case AKM_WPA2_1X: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_AKM_SUITE_OUI_TYPE_RSN_1X; } break; case AKM_WPA2_PSK: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_AKM_SUITE_OUI_TYPE_RSN_PSK; } break; case AKM_WPA2_CCKM: { PlatformMoveMemory(pOUI, CCKM_OUI, SIZE_OUI); *pOUIType = CCKM_OUI_TYPE; } break; case AKM_RSNA_1X_SHA256: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_AKM_SUITE_OUI_TYPE_1X_SHA256; } break; case AKM_RSNA_PSK_SHA256: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_AKM_SUITE_OUI_TYPE_PSK_SHA256; } break; case AKM_FT_1X: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_AKM_SUITE_OUI_TYPE_FT_1X; } break; case AKM_FT_PSK: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_AKM_SUITE_OUI_TYPE_FT_PSK; } break; } return rtStatus; } // // Description: // Get the AKM suite in AKM_SUITE_TYPE from OUI and OUI type. // Arguments: // [out] pOUI - // The OUI with 3 bytes. // If the input is all 0 in pOUI, return AKM_SUITE_NONE. // [out] pOUIType - // The OUI type with 1 byte. // If the input is all 0 in pOUIType, return AKM_SUITE_NONE. // [in] secLevl - // Input the security level related to OUI and OUIType // [in] pAKMSuite - // Return The tcipher suite. // Return: // RT_STATUS_SUCCESS, if the translation succeeds. // RT_STATUS_NOT_RECOGNIZED, if the pOUI/pOUIType is not recognized. // RT_STATUS_INVALID_DATA, if any of pOUI, pOUIType, or secLevl is invalid. // RT_STATUS Sec_MapOUITypeToAKMSuite( IN pu1Byte pOUI, IN pu1Byte pOUIType, IN RT_SECURITY_LEVEL secLevl, OUT PAKM_SUITE_TYPE pAKMSuite ) { RT_STATUS rtStatus = RT_STATUS_SUCCESS; CHECK_NULL_RETURN_STATUS(pOUI); CHECK_NULL_RETURN_STATUS(pOUIType); CHECK_NULL_RETURN_STATUS(pAKMSuite); if(RT_SEC_LVL_NONE == secLevl) { *pAKMSuite = AKM_SUITE_NONE; } else if(RT_SEC_LVL_WPA == secLevl) { if(eqOUI(pOUI, WPA_OUI)) { switch(*pOUIType) { default: rtStatus = RT_STATUS_NOT_RECOGNIZED; break; case AKM_WPA_1X_OUI_TYPE: *pAKMSuite = AKM_WPA_1X; break; case AKM_WPA_PSK_OUI_TYPE: *pAKMSuite = AKM_WPA_PSK; break; } } else if(eqOUI(pOUI, CCKM_OUI) && CCKM_OUI_TYPE == *pOUIType) { *pAKMSuite = AKM_WPA_CCKM; } else { rtStatus = RT_STATUS_NOT_RECOGNIZED; } } else if(RT_SEC_LVL_WPA2 == secLevl) { if(eqOUI(pOUI, RSN_OUI)) { switch(*pOUIType) { default: rtStatus = RT_STATUS_NOT_RECOGNIZED; break; case RSN_AKM_SUITE_OUI_TYPE_RSN_1X: *pAKMSuite = AKM_WPA2_1X; break; case RSN_AKM_SUITE_OUI_TYPE_RSN_PSK: *pAKMSuite = AKM_WPA2_PSK; break; case RSN_AKM_SUITE_OUI_TYPE_FT_1X: *pAKMSuite = AKM_FT_1X; break; case RSN_AKM_SUITE_OUI_TYPE_FT_PSK: *pAKMSuite = AKM_FT_PSK; break; case RSN_AKM_SUITE_OUI_TYPE_1X_SHA256: *pAKMSuite = AKM_RSNA_1X_SHA256; break; case RSN_AKM_SUITE_OUI_TYPE_PSK_SHA256: *pAKMSuite = AKM_RSNA_PSK_SHA256; break; } } else if(eqOUI(pOUI, CCKM_OUI) && CCKM_OUI_TYPE == *pOUIType) { *pAKMSuite = AKM_WPA2_CCKM; } else { rtStatus = RT_STATUS_NOT_RECOGNIZED; } } return RT_STATUS_NOT_SUPPORT; } // // Description: // Get the OUI and OUI type from the cipher suite in RT_ENC_ALG. // Arguments: // [in] cipherSuite - // The cipher suite. // [in] secLevl - // Security level such WPA or WPA2. // [out] pOUI - // Return the OUI with 3 bytes if returned status is RT_STATUS_SUCCESS. // If cipherSuite is RT_ENC_ALG_NO_CIPHER , return all 0 in pOUI. // [out] pOUIType - // Return the OUI type with 1 byte if returned status is RT_STATUS_SUCCESS. // If AKMSuite is RT_ENC_ALG_NO_CIPHER , return 0 in pOUIType. // Return: // RT_STATUS_SUCCESS, if the translation succeeds. // RT_STATUS_NOT_RECOGNIZED, if the cipherSuite is not recognized. // RT_STATUS_INVALID_DATA, if the cipherSuite is invalid. // RT_STATUS Sec_MapCipherSuiteToOUIType( IN RT_ENC_ALG cipherSuite, IN RT_SECURITY_LEVEL secLevl, OUT pu1Byte pOUI, OUT pu1Byte pOUIType ) { RT_STATUS rtStatus = RT_STATUS_SUCCESS; if(RT_SEC_LVL_NONE == secLevl) { PlatformZeroMemory(pOUI, SIZE_OUI); PlatformZeroMemory(pOUIType, SIZE_OUI_TYPE); } else if(RT_SEC_LVL_WPA == secLevl) { switch(cipherSuite) { default: rtStatus = RT_STATUS_NOT_RECOGNIZED; break; case RT_ENC_ALG_NO_CIPHER: { PlatformZeroMemory(pOUI, SIZE_OUI); PlatformZeroMemory(pOUIType, SIZE_OUI_TYPE); } break; case RT_ENC_ALG_TKIP: { PlatformMoveMemory(pOUI, WPA_OUI, SIZE_OUI); *pOUIType = WPA_CIPHER_SUITE_OUI_TYPE_TKIP; } break; case RT_ENC_ALG_AESCCMP: { PlatformMoveMemory(pOUI, WPA_OUI, SIZE_OUI); *pOUIType = WPA_CIPHER_SUITE_OUI_TYPE_CCMP; } break; case RT_ENC_ALG_WEP40: { PlatformMoveMemory(pOUI, WPA_OUI, SIZE_OUI); *pOUIType = WPA_CIPHER_SUITE_OUI_TYPE_WEP40; } break; case RT_ENC_ALG_WEP104: { PlatformMoveMemory(pOUI, WPA_OUI, SIZE_OUI); *pOUIType = WPA_CIPHER_SUITE_OUI_TYPE_WEP104; } break; case RT_ENC_ALG_WEP: { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Invalid Cipher suite RT_ENC_ALG_WEP to map OUI\n")); rtStatus = RT_STATUS_INVALID_DATA; } break; case RT_ENC_ALG_SMS4: { // WAPI does NOT have the cipher suite OUI/Type RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Invalid Cipher suite RT_ENC_ALG_SMS4 to map OUI\n")); rtStatus = RT_STATUS_INVALID_DATA; } break; } } else if(RT_SEC_LVL_WPA2 == secLevl) { switch(cipherSuite) { default: rtStatus = RT_STATUS_NOT_RECOGNIZED; break; case RT_ENC_ALG_NO_CIPHER: { PlatformZeroMemory(pOUI, SIZE_OUI); PlatformZeroMemory(pOUIType, SIZE_OUI_TYPE); } break; case RT_ENC_ALG_USE_GROUP: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_CIPHER_SUITE_OUI_TYPE_USE_GROUP_CIPHER; } break; case RT_ENC_ALG_TKIP: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_CIPHER_SUITE_OUI_TYPE_TKIP; } break; case RT_ENC_ALG_AESCCMP: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_CIPHER_SUITE_OUI_TYPE_CCMP; } break; case RT_ENC_ALG_WEP40: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_CIPHER_SUITE_OUI_TYPE_WEP40; } break; case RT_ENC_ALG_WEP104: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_CIPHER_SUITE_OUI_TYPE_WEP104; } break; case RT_ENC_ALG_WEP: { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Invalid Cipher suite RT_ENC_ALG_WEP to map OUI\n")); rtStatus = RT_STATUS_INVALID_DATA; } break; case RT_ENC_ALG_SMS4: { // WAPI does NOT have the cipher suite OUI/Type RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Invalid Cipher suite RT_ENC_ALG_SMS4 to map OUI\n")); rtStatus = RT_STATUS_INVALID_DATA; } break; case RT_ENC_ALG_BIP: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_CIPHER_SUITE_OUI_TYPE_BIP; } break; case RT_ENC_ALG_GROUP_ADDR_TRAFFIC_DISALLOWED: { PlatformMoveMemory(pOUI, RSN_OUI, SIZE_OUI); *pOUIType = RSN_CIPHER_SUITE_OUI_TYPE_GRP_ADDR_DISALLOWED; } break; } } else { rtStatus = RT_STATUS_NOT_RECOGNIZED; } return rtStatus; } // // Description: // Get the cipher suite in RT_ENC_ALG from OUI and OUI type. // Arguments: // [out] pOUI - // The OUI with 3 bytes. // If the input is all 0 in pOUI, return RT_ENC_ALG_NO_CIPHER. // [out] pOUIType - // The OUI type with 1 byte. // If the input is all 0 in pOUIType, return RT_ENC_ALG_NO_CIPHER. // [in] secLevl - // Input the security level related to OUI and OUIType // [in] pCipherSuite - // Return The tcipher suite. // Return: // RT_STATUS_SUCCESS, if the translation succeeds. // RT_STATUS_NOT_RECOGNIZED, if the pOUI/pOUIType is not recognized. // RT_STATUS_INVALID_DATA, if any of pOUI, pOUIType, or secLevl is invalid. // RT_STATUS Sec_MapOUITypeToCipherSuite( IN pu1Byte pOUI, IN pu1Byte pOUIType, IN RT_SECURITY_LEVEL secLevl, OUT PRT_ENC_ALG pCipherSuite ) { RT_STATUS rtStatus = RT_STATUS_SUCCESS; CHECK_NULL_RETURN_STATUS(pOUI); CHECK_NULL_RETURN_STATUS(pOUIType); CHECK_NULL_RETURN_STATUS(pCipherSuite); if(RT_SEC_LVL_NONE == secLevl) { *pCipherSuite = RT_ENC_ALG_NO_CIPHER; } else if(RT_SEC_LVL_WPA == secLevl) { if(eqOUI(pOUI, WPA_OUI)) { switch(*pOUIType) { default: rtStatus = RT_STATUS_NOT_RECOGNIZED; break; case WPA_CIPHER_SUITE_OUI_TYPE_NONE: *pCipherSuite = RT_ENC_ALG_NO_CIPHER;; break; case WPA_CIPHER_SUITE_OUI_TYPE_WEP40: *pCipherSuite = RT_ENC_ALG_WEP40;; break; case WPA_CIPHER_SUITE_OUI_TYPE_TKIP: *pCipherSuite = RT_ENC_ALG_TKIP;; break; case WPA_CIPHER_SUITE_OUI_TYPE_CCMP: *pCipherSuite = RT_ENC_ALG_AESCCMP;; break; case WPA_CIPHER_SUITE_OUI_TYPE_WEP104: *pCipherSuite = RT_ENC_ALG_WEP104;; break; } } else { rtStatus = RT_STATUS_NOT_RECOGNIZED; } } else if(RT_SEC_LVL_WPA2 == secLevl) { if(eqOUI(pOUI, RSN_OUI)) { switch(*pOUIType) { default: rtStatus = RT_STATUS_NOT_RECOGNIZED; break; case RSN_CIPHER_SUITE_OUI_TYPE_USE_GROUP_CIPHER: *pCipherSuite = RT_ENC_ALG_USE_GROUP;; break; case RSN_CIPHER_SUITE_OUI_TYPE_WEP40: *pCipherSuite = RT_ENC_ALG_WEP40;; break; case RSN_CIPHER_SUITE_OUI_TYPE_TKIP: *pCipherSuite = RT_ENC_ALG_TKIP;; break; case RSN_CIPHER_SUITE_OUI_TYPE_CCMP: *pCipherSuite = RT_ENC_ALG_AESCCMP;; break; case RSN_CIPHER_SUITE_OUI_TYPE_WEP104: *pCipherSuite = RT_ENC_ALG_WEP104;; break; case RSN_CIPHER_SUITE_OUI_TYPE_BIP: *pCipherSuite = RT_ENC_ALG_BIP;; break; case RSN_CIPHER_SUITE_OUI_TYPE_GRP_ADDR_DISALLOWED: *pCipherSuite = RT_ENC_ALG_GROUP_ADDR_TRAFFIC_DISALLOWED;; break; } } else { rtStatus = RT_STATUS_NOT_RECOGNIZED; } } return RT_STATUS_NOT_SUPPORT; } // // Description: // Get the old (deprecated) cipher suite from current RT_ENC_ALGs. // This function is used to translate the old definition such as FW. // Arguments: // [IN] newCipherSuite - // The new cipher suite defined in RT_ENC_ALG. // Return: // The cipher suite defined in RT_ENC_ALG_DEP. // RT_ENC_ALG_DEP Sec_MapNewCipherToDepCipherAlg( IN RT_ENC_ALG newCipherSuite ) { RT_ENC_ALG_DEP depCipher = NO_Encryption; switch(newCipherSuite) { default: { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Unknown newCipherSuite(0x%08X) to map\n", newCipherSuite)); } break; case RT_ENC_ALG_NO_CIPHER: depCipher = NO_Encryption; break; case RT_ENC_ALG_TKIP: depCipher = TKIP_Encryption; break; case RT_ENC_ALG_AESCCMP: depCipher = AESCCMP_Encryption; break; case RT_ENC_ALG_WEP40: depCipher = WEP40_Encryption; break; case RT_ENC_ALG_WEP104: depCipher = WEP104_Encryption; break; case RT_ENC_ALG_WEP: depCipher = WEP_Encryption; break; case RT_ENC_ALG_SMS4: depCipher = SMS4_Encryption; break; } return depCipher; } RT_ENC_ALG SecGetEncryptionOverhead( PADAPTER Adapter, UNALIGNED pu2Byte pMPDUHead, UNALIGNED pu2Byte pMPDUTail, UNALIGNED pu2Byte pMSDUHead, UNALIGNED pu2Byte pMSDUTail, BOOLEAN bByPacket, BOOLEAN bIsBroadcastPkt ) { PMGNT_INFO pMgntInfo = &Adapter->MgntInfo; RT_ENC_ALG ulSwitchCondition = (bByPacket&&bIsBroadcastPkt)? \ pMgntInfo->SecurityInfo.GroupEncAlgorithm:pMgntInfo->SecurityInfo.PairwiseEncAlgorithm; // Decide EncryptionOverhead according to Encryption algorithm switch( ulSwitchCondition ) { case RT_ENC_ALG_NO_CIPHER: if(pMPDUHead){ *pMPDUHead=0; } if(pMPDUTail){ *pMPDUTail=0; } if(pMSDUHead){ *pMSDUHead=0; } if(pMSDUTail){ *pMSDUTail=0; } break; case RT_ENC_ALG_WEP40: case RT_ENC_ALG_WEP104: // CKIP should also go into this case. if(pMPDUHead){ *pMPDUHead=4; } if(pMPDUTail){ *pMPDUTail=4; } if(pMSDUHead){ *pMSDUHead=0; } if(pMSDUTail){ *pMSDUTail=0; } break; case RT_ENC_ALG_TKIP: if(pMPDUHead){ *pMPDUHead=8; } if(pMPDUTail){ *pMPDUTail=4; } if(pMSDUHead){ *pMSDUHead=0; } if(pMSDUTail){ *pMSDUTail=8; } break; case RT_ENC_ALG_AESCCMP: if(pMPDUHead){ *pMPDUHead=8; } if(pMPDUTail){ *pMPDUTail=8; } if(pMSDUHead){ *pMSDUHead=0; } if(pMSDUTail){ *pMSDUTail=0; } break; case RT_ENC_ALG_SMS4: if(pMPDUHead){ *pMPDUHead=18; } if(pMPDUTail){ *pMPDUTail=16; } if(pMSDUHead){ *pMSDUHead=0; } if(pMSDUTail){ *pMSDUTail=0; } break; default: break; } return ulSwitchCondition; } VOID SecGetGroupCipherFromBeacon( PADAPTER Adapter, PRT_WLAN_BSS pbssDesc) { PRT_SECURITY_T pSecInfo = &(Adapter->MgntInfo.SecurityInfo); pSecInfo->GroupEncAlgorithm = pbssDesc->GroupCipherSuite; RT_TRACE( COMP_SEC, DBG_LOUD, ("SecGetGroupCipherFromBeacon(): GroupEncAlgorithm = %d\n", pSecInfo->GroupEncAlgorithm) ); SecConstructRSNIE(Adapter); } VOID SecConstructRSNIE( PADAPTER Adapter ) { //kcwu: NOTICE===> //The frame format of WPA/WPA2 are different PMGNT_INFO pMgntInfo = &Adapter->MgntInfo; PRT_SECURITY_T pSecInfo = &Adapter->MgntInfo.SecurityInfo; BOOLEAN bCCX8021xenable = FALSE; BOOLEAN bAPSuportCCKM = FALSE; pu1Byte pIeHead = Adapter->MgntInfo.SecurityInfo.RSNIEBuf; u2Byte IeLen = 0; u1Byte tmpOUI[SIZE_OUI] = {0}; u1Byte tmpOUIType = 0; u2Byte AddSize; AKM_SUITE_TYPE selAKM = AKM_SUITE_NONE; Adapter->MgntInfo.SecurityInfo.RSNIE.Length = 0; // Select the AKM Sec_SelAkmFromAuthMode( Adapter, pSecInfo->AuthMode, CONTENT_PKT_TYPE_AP, NULL, 0, &selAKM); if(pSecInfo->SecLvl == RT_SEC_LVL_WPA) { // WPA OUI and Type SET_WPA_IE_OUI_AND_TYPE(pIeHead); IeLen += 4; // WPA Version SET_WPA_IE_VERSION(pIeHead, WPA_VER1); IeLen += 2; // // 2. Group Cipher Suite. // Sec_MapCipherSuiteToOUIType(pSecInfo->GroupEncAlgorithm, RT_SEC_LVL_WPA, tmpOUI, &tmpOUIType); SET_WPA_IE_GROUP_CIPHER_SUITE_OUI_W_TYPE(pIeHead, tmpOUI, tmpOUIType); IeLen += 4; // Pairwise cipher suite OUI/Type Sec_MapCipherSuiteToOUIType(pSecInfo->PairwiseEncAlgorithm, RT_SEC_LVL_WPA, tmpOUI, &tmpOUIType); // Initialize Pairwise Suite count SET_WPA_IE_PAIRWISE_CIPHER_SUITE_CNT(pIeHead, 0); IeLen += 2; // Pairwise cipher suite. We may add more pairwise cipher suites here for AP mode. ADD_WPA_IE_PAIRWISE_CIPHER_SUITE_OUI_W_TYPE(pIeHead, tmpOUI, tmpOUIType); IeLen += 4; // Intialize AKM suite count SET_WPA_IE_AKM_SUITE_CNT(pIeHead, 0); IeLen += 2; // AKM suite list Sec_MapAKMSuiteToOUIType(selAKM, tmpOUI, &tmpOUIType); ADD_WPA_IE_AKM_SUITE_OUI_W_TYPE(pIeHead, tmpOUI, tmpOUIType); IeLen += 4; // Capabilities SET_WPA_IE_CAP_PTKSA_REPLAY_COUNTER(pIeHead, 0); SET_WPA_IE_CAP_GTKSA_REPLAY_COUNTER(pIeHead, 0); IeLen += 2; } else { // Default: WPA2. Changed from WPA by Annie, 2006-04-26. SET_RSN_IE_VERSION(pIeHead, RSN_VER1); IeLen += 2; // Group cipher suite OUI/Type Sec_MapCipherSuiteToOUIType(pSecInfo->GroupEncAlgorithm, RT_SEC_LVL_WPA2, tmpOUI, &tmpOUIType); SET_RSN_IE_GROUP_CIPHER_SUITE_OUI_W_TYPE(pIeHead, tmpOUI, tmpOUIType); IeLen += 4; // Pairwise cipher suite OUI/Type Sec_MapCipherSuiteToOUIType(pSecInfo->PairwiseEncAlgorithm, RT_SEC_LVL_WPA2, tmpOUI, &tmpOUIType); // RT_TRACE_F(COMP_SEC, DBG_LOUD, ("PairwiseEncAlgorithm = 0x%08X, OUI = %02X-%02X-%02X-%02X\n", pSecInfo->PairwiseEncAlgorithm, tmpOUI[0], tmpOUI[1], tmpOUI[2], tmpOUIType)); // Intialize pairwise count SET_RSN_IE_PAIRWISE_CIPHER_SUITE_CNT(pIeHead, 0); IeLen += 2; // We may add more pairwise cipher suites here for AP mode. ADD_RSN_IE_PAIRWISE_CIPHER_SUITE_OUI_W_TYPE(pIeHead, tmpOUI, tmpOUIType); IeLen += 4; // Intialize AKM suite count SET_RSN_IE_AKM_SUITE_CNT(pIeHead, 0); IeLen += 2; Sec_MapAKMSuiteToOUIType(selAKM, tmpOUI, &tmpOUIType); ADD_RSN_IE_AKM_SUITE_OUI_W_TYPE(pIeHead, tmpOUI, tmpOUIType); IeLen += 4; // //3 // RSN Capabilities. // // (1) Pre-Authentication (bit0) // WPA: Reserver. // WPA2: "A non-AP STA sets the Pre-authentication subfield to zero", in 802.11iD10.0, 172.16.58.3.3 RSN Capabilities, page34. Added by Annie, 2006-05-08. SET_RSN_IE_CAP_PREAUTH(pIeHead, 0); // (2) PairwiseAsDefaultKey (bit1) //No Pairwise = false SET_RSN_IE_CAP_NO_PAIRWISE(pIeHead, 0); //Replay Counter //kcwu?: Should we implement multiple replay counters? // (3) NumOfPTKSAReplayCounter (bit2,3) SET_RSN_IE_CAP_PTKSA_REPLAY_COUNTER(pIeHead, 0); // (4) NumOfGTKSAReplayCounter (bit4,5) SET_RSN_IE_CAP_GTKSA_REPLAY_COUNTER(pIeHead, 0); IeLen += 2; } Adapter->MgntInfo.SecurityInfo.RSNIE.Length = IeLen; RT_PRINT_DATA( COMP_SEC, DBG_LOUD, ("SecConstructRSNIE(): RSNIE:\n"), pSecInfo->RSNIE.Octet, pSecInfo->RSNIE.Length); } // // Description: // Append security IEs to this authentication packet. // Arguments: // [in] pAdapter - // The location of target adapter. // [in] contentType - // The type of content to append this WPA IE. This field also indicates which type of posOutContent. // CONTENT_PKT_TYPE_xxx - // [in] pInfoBuf - // This field is determined by contentType and shall be casted to the corresponding type. // pInfoBuf is PRT_WLAN_BSS if contentType is CONTENT_PKT_TYPE_CLIENT. // [in] InfoBufLen - // Length in byte of pInfoBuf. // [in] maxBufLen - // The max length of posOutContent buffer in byte. // [out] posOutContent - // The OCTECT_STRING structure for the content buffer and length. // posOutContent is a 802.11 packet if contentType is CONTENT_PKT_TYPE_802_11. // Return: // RT_STATUS_SUCCESS, if the content is appended withour error. // RT_STATUS_BUFFER_TOO_SHORT, if the max length of buffer is not long enough. // RT_STATUS_INVALID_STATE, if the security parameter is mismatched. // Remark: // To determine the RSN content to append to the output content, the pTargetBss, contentType, and posOutContent // shall be filled when calling this function. If RSN IE will be appended to an association request frame in posOutContent, // the 802.11 packet type and MAC header shall be filled in posOutContent before calling this function. // By Bruce, 2015-09-22. // RT_STATUS Sec_AppendWPAIE( IN PADAPTER pAdapter, IN CONTENT_PKT_TYPE contentType, IN PVOID pInfoBuf, IN u4Byte InfoBufLen, IN u4Byte maxBufLen, OUT POCTET_STRING posOutContent ) { RT_STATUS rtStatus = RT_STATUS_SUCCESS; PMGNT_INFO pMgntInfo = &pAdapter->MgntInfo; PRT_SECURITY_T pSecInfo = &pAdapter->MgntInfo.SecurityInfo; u1Byte rsnBuf[MAX_IE_LEN - SIZE_EID_AND_LEN] = {0}; OCTET_STRING osRsn; u1Byte pktType = 0xFF; AKM_SUITE_TYPE akmSuite = AKM_SUITE_NONE; u1Byte tmpOUI[SIZE_OUI] = {0}; u1Byte tmpOUIType = 0; PRT_WLAN_BSS pBssDesc = NULL; AKM_SUITE_TYPE selAKM = AKM_SUITE_NONE; FillOctetString(osRsn, rsnBuf, 0); do { if(TEST_FLAG(contentType, CONTENT_PKT_TYPE_CLIENT | CONTENT_PKT_TYPE_AP | CONTENT_PKT_TYPE_IBSS)) { if(RT_SEC_LVL_WPA != pSecInfo->SecLvl) { RT_TRACE_F(COMP_SEC, DBG_TRACE, ("SecLvl (%d) != RT_SEC_LVL_WPA\n", pSecInfo->SecLvl)); rtStatus = RT_STATUS_INVALID_STATE; break; } } if(TEST_FLAG(contentType, CONTENT_PKT_TYPE_802_11)) { pktType = PacketGetType(*posOutContent); } if(TEST_FLAG(contentType, CONTENT_PKT_TYPE_CLIENT)) { if(NULL == pInfoBuf || InfoBufLen < sizeof(RT_WLAN_BSS)) { // Prefast warning C6328: Size mismatch ignore #pragma warning (disable: 6328) RT_TRACE_F(COMP_SEC, DBG_WARNING, ("pInfoBuf (%p) = NULL or InfoBufLen < required of sizeof(RT_WLAN_BSS) = %d\n", pInfoBuf, sizeof(RT_WLAN_BSS))); rtStatus = RT_STATUS_INVALID_DATA; break; } pBssDesc = (PRT_WLAN_BSS)pInfoBuf; if(RT_STATUS_SUCCESS != (rtStatus = Sec_SelAkmFromAuthMode( pAdapter, pSecInfo->AuthMode, CONTENT_PKT_TYPE_CLIENT, pBssDesc, sizeof(RT_WLAN_BSS), &selAKM))) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Failed (0x%08X) from Sec_SelAkmFromAuthMode(), pSecInfo->AuthMode = %d, pBssDesc->AKMsuit = 0x%08X\n", rtStatus, pSecInfo->AuthMode, pBssDesc->AKMsuit)); break; } RT_TRACE_F(COMP_SEC, DBG_LOUD, ("selAKM = 0x%08X\n", selAKM)); // Do not append RSN IE in default. rtStatus = RT_STATUS_INVALID_DATA; switch(pktType) { default: rtStatus = RT_STATUS_INVALID_DATA; break; case Type_Asoc_Req: case Type_Reasoc_Req: rtStatus = RT_STATUS_SUCCESS; break; } if(RT_STATUS_SUCCESS != rtStatus) { // No need to append RSN IE RT_TRACE_F(COMP_SEC, DBG_TRACE, ("pktType = 0x%02X, no need to append RSN IE\n", pktType)); break; } } // OUI + type SET_WPA_IE_OUI_AND_TYPE(osRsn.Octet); osRsn.Length += 4; // WPA version SET_WPA_IE_VERSION(osRsn.Octet, WPA_VER1); osRsn.Length += 2; // Group cipher suite if(RT_STATUS_SUCCESS != ( rtStatus = Sec_MapCipherSuiteToOUIType(pSecInfo->GroupEncAlgorithm, RT_SEC_LVL_WPA, tmpOUI, &tmpOUIType))) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Fail (0x%08X) to get OUI/Type from group EncAlg(0x%08X)\n", rtStatus, pSecInfo->GroupEncAlgorithm)); break; } SET_WPA_IE_GROUP_CIPHER_SUITE_OUI_W_TYPE(osRsn.Octet, tmpOUI, tmpOUIType); osRsn.Length += 4; // Pairwise cipher suite OUI/Type if(RT_STATUS_SUCCESS != (rtStatus = Sec_MapCipherSuiteToOUIType(pSecInfo->PairwiseEncAlgorithm, RT_SEC_LVL_WPA, tmpOUI, &tmpOUIType))) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Fail (0x%08X) to get OUI/Type from pairwise EncAlg(0x%08X)\n", rtStatus, pSecInfo->PairwiseEncAlgorithm)); break; } // Initialize Pairwise Suite count SET_WPA_IE_PAIRWISE_CIPHER_SUITE_CNT(osRsn.Octet, 0); osRsn.Length += 2; // Pairwise cipher suite. We may add more pairwise cipher suites here for AP mode. ADD_WPA_IE_PAIRWISE_CIPHER_SUITE_OUI_W_TYPE(osRsn.Octet, tmpOUI, tmpOUIType); osRsn.Length += 4; // Intialize AKM suite count SET_WPA_IE_AKM_SUITE_CNT(osRsn.Octet, 0); osRsn.Length += 2; // AKM suite list if(TEST_FLAG(contentType, CONTENT_PKT_TYPE_CLIENT)) { if(RT_STATUS_SUCCESS != (rtStatus = Sec_MapAKMSuiteToOUIType(selAKM, tmpOUI, &tmpOUIType))) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Failed (0x%08X) from Sec_MapAKMSuiteToOUIType() for selAKM = 0x%08X, AuthMode = %d, targetAKMSuite = 0x%08X\n", rtStatus, selAKM, pSecInfo->AuthMode, pMgntInfo->targetAKMSuite)); break; } ADD_WPA_IE_AKM_SUITE_OUI_W_TYPE(osRsn.Octet, tmpOUI, tmpOUIType); osRsn.Length += 4; } else { // ToDo rtStatus = RT_STATUS_NOT_SUPPORT; break; } // Capabilities SET_WPA_IE_CAP_PTKSA_REPLAY_COUNTER(osRsn.Octet, 0); SET_WPA_IE_CAP_GTKSA_REPLAY_COUNTER(osRsn.Octet, 0); osRsn.Length += 2; }while(FALSE); if(RT_STATUS_SUCCESS == rtStatus) { if((maxBufLen - posOutContent->Length) < osRsn.Length) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("maxBufLen (%d) - posOutContent.Length (%d) < osRsn.Length(%d)\n", maxBufLen, posOutContent->Length, osRsn.Length)); rtStatus = RT_STATUS_BUFFER_TOO_SHORT; } else { RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "Append IE data:\n", osRsn.Octet, osRsn.Length); PacketMakeElement(posOutContent, EID_Vendor, osRsn); } } return rtStatus; } // // Description: // Append RSN IE to this packet or content. // Arguments: // [in] pAdapter - // The location of target adapter. // [in] contentType - // The type of content to append this RSN IE. This field also indicates which type of posOutContent. // CONTENT_PKT_TYPE_xxx - // [in] pInfoBuf - // This field is determined by contentType and shall be casted to the corresponding type. // pInfoBuf is PRT_WLAN_BSS if contentType is CONTENT_PKT_TYPE_CLIENT. // [in] InfoBufLen - // Length in byte of pInfoBuf. // [in] maxBufLen - // The max length of posOutContent buffer in byte. // [out] posOutContent - // The OCTECT_STRING structure for the content buffer and length. // posOutContent is a 802.11 packet if contentType is CONTENT_PKT_TYPE_802_11. // Return: // RT_STATUS_SUCCESS, if the content is appended withour error. // RT_STATUS_BUFFER_TOO_SHORT, if the max length of buffer is not long enough. // RT_STATUS_INVALID_STATE, if the security parameter is mismatched. // Remark: // To determine the RSN content to append to the output content, the pTargetBss, contentType, and posOutContent // shall be filled when calling this function. If RSN IE will be appended to an association request frame in posOutContent, // the 802.11 packet type and MAC header shall be filled in posOutContent before calling this function. // By Bruce, 2015-09-22. // RT_STATUS Sec_AppendRSNIE( IN PADAPTER pAdapter, IN CONTENT_PKT_TYPE contentType, IN PVOID pInfoBuf, IN u4Byte InfoBufLen, IN u4Byte maxBufLen, OUT POCTET_STRING posOutContent ) { RT_STATUS rtStatus = RT_STATUS_SUCCESS; PMGNT_INFO pMgntInfo = &pAdapter->MgntInfo; PRT_SECURITY_T pSecInfo = &pAdapter->MgntInfo.SecurityInfo; u1Byte rsnBuf[MAX_IE_LEN - SIZE_EID_AND_LEN] = {0}; OCTET_STRING osRsn; u1Byte pktType = 0xFF; AKM_SUITE_TYPE akmSuite = AKM_SUITE_NONE; u1Byte tmpOUI[SIZE_OUI] = {0}; u1Byte tmpOUIType = 0; PRT_WLAN_BSS pBssDesc = NULL; AKM_SUITE_TYPE selAKM = AKM_SUITE_NONE; PFT_INFO_ENTRY pFtEntry = NULL; CHECK_NULL_RETURN_STATUS(posOutContent); FillOctetString(osRsn, rsnBuf, 0); do { if(TEST_FLAG(contentType, CONTENT_PKT_TYPE_CLIENT | CONTENT_PKT_TYPE_AP | CONTENT_PKT_TYPE_IBSS)) { if(RT_SEC_LVL_WPA2 != pSecInfo->SecLvl) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("SecLvl (%d) != RT_SEC_LVL_WPA2\n", pSecInfo->SecLvl)); rtStatus = RT_STATUS_INVALID_STATE; break; } } if(TEST_FLAG(contentType, CONTENT_PKT_TYPE_802_11)) { pktType = PacketGetType(*posOutContent); } if(TEST_FLAG(contentType, CONTENT_PKT_TYPE_CLIENT)) { BOOLEAN bFtIeFromEntry = FALSE; if(NULL == pInfoBuf || InfoBufLen < sizeof(RT_WLAN_BSS)) { // Prefast warning C6328: Size mismatch ignore #pragma warning (disable: 6328) RT_TRACE_F(COMP_SEC, DBG_WARNING, ("pInfoBuf (%p) = NULL or InfoBufLen < required of sizeof(RT_WLAN_BSS) = %d\n", pInfoBuf, sizeof(RT_WLAN_BSS))); rtStatus = RT_STATUS_INVALID_DATA; break; } pBssDesc = (PRT_WLAN_BSS)pInfoBuf; if(RT_STATUS_SUCCESS != (rtStatus = Sec_SelAkmFromAuthMode( pAdapter, pSecInfo->AuthMode, CONTENT_PKT_TYPE_CLIENT, pBssDesc, sizeof(RT_WLAN_BSS), &selAKM))) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Failed (0x%08X) from Sec_SelAkmFromAuthMode(), pSecInfo->AuthMode = %d, pBssDesc->AKMsuit = 0x%08X\n", rtStatus, pSecInfo->AuthMode, pBssDesc->AKMsuit)); break; } RT_TRACE_F(COMP_SEC, DBG_LOUD, ("selAKM = 0x%08X\n", selAKM)); // Check if the entry has PMKID if(AKM_FT_1X == selAKM || AKM_FT_PSK == selAKM) { pFtEntry = FtGetEntry(pAdapter, pBssDesc->bdBssIdBuf); } // Do not append RSN IE in default. rtStatus = RT_STATUS_INVALID_DATA; switch(pktType) { default: rtStatus = RT_STATUS_INVALID_DATA; break; case Type_Auth: { if(FtIsFtAuthReady(pAdapter, pBssDesc->bdBssIdBuf)) { rtStatus = RT_STATUS_SUCCESS; } } break; case Type_Asoc_Req: case Type_Reasoc_Req: { if(FtIsFtAssocReqReady(pAdapter, pBssDesc->bdBssIdBuf)) { // Prefast warning C6011: Dereferencing NULL pointer 'pFtEntry'. if(pFtEntry != NULL && pFtEntry->RSNELen > SIZE_EID_AND_LEN) { FillOctetString(osRsn, pFtEntry->RSNE + SIZE_EID_AND_LEN, (pFtEntry->RSNELen - SIZE_EID_AND_LEN)); bFtIeFromEntry = TRUE; RT_TRACE_F(COMP_SEC, DBG_LOUD, ("RSN IE content from FT entry\n")); } } rtStatus = RT_STATUS_SUCCESS; } break; } if(RT_STATUS_SUCCESS != rtStatus) { // No need to append RSN IE RT_TRACE_F(COMP_SEC, DBG_TRACE, ("pktType = 0x%02X, no need to append RSN IE\n", pktType)); break; } // The content has been filled. if(bFtIeFromEntry) break; } SET_RSN_IE_VERSION(osRsn.Octet, RSN_VER1); osRsn.Length += 2; // Group cipher suite OUI/Type if(RT_STATUS_SUCCESS != (rtStatus = Sec_MapCipherSuiteToOUIType(pSecInfo->GroupEncAlgorithm, RT_SEC_LVL_WPA2, tmpOUI, &tmpOUIType))) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Fail (0x%08X) to get OUI/Type from group EncAlg(0x%08X)\n", rtStatus, pSecInfo->GroupEncAlgorithm)); break; } SET_RSN_IE_GROUP_CIPHER_SUITE_OUI_W_TYPE(osRsn.Octet, tmpOUI, tmpOUIType); osRsn.Length += 4; // Pairwise cipher suite OUI/Type if(RT_STATUS_SUCCESS != (rtStatus = Sec_MapCipherSuiteToOUIType(pSecInfo->PairwiseEncAlgorithm, RT_SEC_LVL_WPA2, tmpOUI, &tmpOUIType))) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Fail (0x%08X) to get OUI/Type from pairwise EncAlg(0x%08X)\n", rtStatus, pSecInfo->PairwiseEncAlgorithm)); break; } // RT_TRACE_F(COMP_SEC, DBG_LOUD, ("PairwiseEncAlgorithm = 0x%08X, OUI = %02X-%02X-%02X-%02X\n", pSecInfo->PairwiseEncAlgorithm, tmpOUI[0], tmpOUI[1], tmpOUI[2], tmpOUIType)); // Intialize pairwise count SET_RSN_IE_PAIRWISE_CIPHER_SUITE_CNT(osRsn.Octet, 0); osRsn.Length += 2; // We may add more pairwise cipher suites here for AP mode. ADD_RSN_IE_PAIRWISE_CIPHER_SUITE_OUI_W_TYPE(osRsn.Octet, tmpOUI, tmpOUIType); osRsn.Length += 4; // Intialize AKM suite count SET_RSN_IE_AKM_SUITE_CNT(osRsn.Octet, 0); osRsn.Length += 2; if(TEST_FLAG(contentType, CONTENT_PKT_TYPE_CLIENT)) { if(RT_STATUS_SUCCESS != (rtStatus = Sec_MapAKMSuiteToOUIType(selAKM, tmpOUI, &tmpOUIType))) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("Failed (0x%08X) from Sec_MapAKMSuiteToOUIType() for selAKM = 0x%08X, AuthMode = %d, targetAKMSuite = 0x%08X\n", rtStatus, selAKM, pSecInfo->AuthMode, pMgntInfo->targetAKMSuite)); break; } ADD_RSN_IE_AKM_SUITE_OUI_W_TYPE(osRsn.Octet, tmpOUI, tmpOUIType); osRsn.Length += 4; } else { // ToDo rtStatus = RT_STATUS_NOT_SUPPORT; break; } // //3 // RSN Capabilities. // // (1) Pre-Authentication (bit0) // WPA: Reserver. // WPA2: "A non-AP STA sets the Pre-authentication subfield to zero", in 802.11iD10.0, 7.3.2.25.3 RSN Capabilities, page34. Added by Annie, 2006-05-08. SET_RSN_IE_CAP_PREAUTH(osRsn.Octet, 0); // (2) PairwiseAsDefaultKey (bit1) //No Pairwise = false SET_RSN_IE_CAP_NO_PAIRWISE(osRsn.Octet, 0); //Replay Counter //kcwu?: Should we implement multiple replay counters? // (3) NumOfPTKSAReplayCounter (bit2,3) SET_RSN_IE_CAP_PTKSA_REPLAY_COUNTER(osRsn.Octet, 0); // (4) NumOfGTKSAReplayCounter (bit4,5) SET_RSN_IE_CAP_GTKSA_REPLAY_COUNTER(osRsn.Octet, 0); osRsn.Length += 2; if(TEST_FLAG(contentType, CONTENT_PKT_TYPE_CLIENT)) { pu1Byte pPmkIdBuf = NULL; int pmkIdx = -1; BOOLEAN bGroupMgntCipher = FALSE; // Append PMKID if(pFtEntry) { // FT PMKID if(pFtEntry->PMKR0NameLen > 0) { pPmkIdBuf = pFtEntry->PMKR0Name; } } else if((pmkIdx = SecIsInPMKIDList(pAdapter, pBssDesc->bdBssIdBuf)) >= 0) { pPmkIdBuf = pSecInfo->PMKIDList[pmkIdx].PMKID; } // Group Management Cipher Suite (Protected Management Frame Protocol) if(pBssDesc->bMFPC && pMgntInfo->bInBIPMFPMode) { SET_RSN_IE_CAP_MFP_CAPABLE(osRsn.Octet, 1); if(RT_STATUS_SUCCESS == Sec_MapCipherSuiteToOUIType(RT_ENC_ALG_BIP, RT_SEC_LVL_WPA2, tmpOUI, &tmpOUIType)) { bGroupMgntCipher = TRUE; } } // Intialize PMKID count if there is any more content to avoid IOT issue if(pPmkIdBuf || bGroupMgntCipher) { SET_RSN_IE_PMKID_CNT(osRsn.Octet, 0); osRsn.Length += 2; } if(pPmkIdBuf) { ADD_RSN_IE_PMKID(osRsn.Octet, pPmkIdBuf); osRsn.Length += PMKID_LEN; } if(bGroupMgntCipher) { SET_RSN_IE_GROUP_MGNT_CIPHER_SUITE_OUI_W_TYPE(osRsn.Octet, tmpOUI, tmpOUIType); osRsn.Length += 4; } } }while(FALSE); if(RT_STATUS_SUCCESS == rtStatus) { if((maxBufLen - posOutContent->Length) < osRsn.Length) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("maxBufLen (%d) - posOutContent.Length (%d) < osRsn.Length(%d)\n", maxBufLen, posOutContent->Length, osRsn.Length)); rtStatus = RT_STATUS_BUFFER_TOO_SHORT; } else { RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "Append IE data:\n", osRsn.Octet, osRsn.Length); PacketMakeElement(posOutContent, EID_WPA2, osRsn); } } return rtStatus; } u1Byte SecGetTxKeyIdx( PADAPTER Adapter, pu1Byte pMacAddr // Not used now... ) { //pairwise keyidx in our driver is 0 (in WPA-PSK or WPA2-PSK.) PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; u1Byte keyidx = PAIRWISE_KEYIDX; //2004/06/29, kcwu, //check if pairwise key exists if(pSec->KeyLen[keyidx] == 0) { if(Adapter->MgntInfo.mIbss) { // Ad Hoc Mode. return (pSec->KeyLen[pSec->GroupTransmitKeyIdx]==0)?5:pSec->GroupTransmitKeyIdx; } else { // Infrastructure Mode. return 5; } } else { return keyidx; } } VOID SecCalculateMIC( PADAPTER Adapter, PRT_TCB pTcb ) { PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); PRT_SECURITY_T pSec = &(pMgntInfo->SecurityInfo); switch(pSec->PairwiseEncAlgorithm) { case RT_ENC_ALG_WEP40: case RT_ENC_ALG_WEP104: if( pSec->pCkipPara->bIsMIC ) { // CKIP MIC case. SecCalculateCKIPMIC(Adapter, pTcb); } break; case RT_ENC_ALG_TKIP: SecCalculateTKIPMIC(Adapter, pTcb); break; case RT_ENC_ALG_AESCCMP: break; default: break; } } // // Descriptin: // Append TKIP MIC of given tx packet to send. // // Note: // 1. TKIP MIC input: DA(6) + SA(6) + Priority(1) + Zero(3) + Data(n) // where Data field shall conform 802.2 LLC and 802.1 bridging. // For example, Data is begined with LLC/SNAP. // // Assumption: // 1. The tx packet repsented by RT_TCB here is an 802.11 MPDU // translated from an MSDU before doing fragmentation. // // Revision History: // 061028, rcnjko: // Generalize the way to retrive MSDU payload. // VOID SecCalculateTKIPMIC( PADAPTER Adapter, PRT_TCB pTcb ) { PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); PRT_SECURITY_T pSec = &(pMgntInfo->SecurityInfo); u4Byte idx = 0; u1Byte keyidx = SecGetTxKeyIdx(Adapter, pTcb->DestinationAddress); MicData micdata; u1Byte Qos[4]; PRT_WLAN_STA pEntry = NULL; pu1Byte pHeader = pTcb->BufferList[0].VirtualAddress; u4Byte FrameHdrLng = sMacHdrLng + pSec->EncryptionHeadOverhead; u4Byte OffsetToByPass = 0; // // MIC Key. // if(ACTING_AS_AP(Adapter)) { if(MacAddr_isMulticast(pTcb->DestinationAddress)) { //Check if set GTK was completed if(pMgntInfo->globalKeyInfo.GTK[0] == 0) return; //Set Tx Group Key SecMICSetKey(&micdata, &pMgntInfo->globalKeyInfo.GTK[16]); } else { //Check if STA within associated lsit table pEntry = AsocEntry_GetEntry(pMgntInfo, pTcb->DestinationAddress); if(pEntry == NULL) return; //Check if set PTK was completed if(pEntry->perSTAKeyInfo.TxMICKey == NULL) return; //Set Tx Pairwise Key by destination Address SecMICSetKey(&micdata, pEntry->perSTAKeyInfo.TxMICKey); } } else if(pTcb->bTDLPacket) { //Check if STA within associated lsit table pEntry = AsocEntry_GetEntry(pMgntInfo, pTcb->DestinationAddress); if(pEntry == NULL) return; //Check if set PTK was completed if(pEntry->perSTAKeyInfo.TxMICKey == NULL) return; //Set Tx Pairwise Key by destination Address SecMICSetKey(&micdata, pEntry->perSTAKeyInfo.TxMICKey); } else { if(pSec->PairwiseEncAlgorithm != RT_ENC_ALG_TKIP) { RT_TRACE(COMP_SEC, DBG_LOUD, ("PairwiseEncAlg=%d\n", pSec->PairwiseEncAlgorithm) ); return; } if(pMgntInfo->mAssoc) { SecMICSetKey(&micdata, pSec->KeyBuf[keyidx]+TKIP_MICKEYRX_POS); } else { SecMICSetKey(&micdata, pSec->KeyBuf[keyidx]+TKIP_MICKEYTX_POS); } } // // DA, SA. // SecMICAppend(&micdata, pTcb->DestinationAddress, ETHERNET_ADDRESS_LENGTH); SecMICAppend(&micdata, pTcb->SourceAddress, ETHERNET_ADDRESS_LENGTH); // // Qos // PlatformZeroMemory(Qos, 4); if(IsQoSDataFrame(pHeader)) Qos[0] = pTcb->priority; // Added by Annie, 2005-12-21. SecMICAppend(&micdata, Qos, 4); if(IsQoSDataFrame(pHeader)) FrameHdrLng += sQoSCtlLng; // // Data. // OffsetToByPass = FrameHdrLng; for(idx = 0;idx < pTcb->BufferCount; idx++) { if(pTcb->BufferList[idx].Length <= OffsetToByPass) { OffsetToByPass -= pTcb->BufferList[idx].Length; continue; } else { SecMICAppend( &micdata, pTcb->BufferList[idx].VirtualAddress + OffsetToByPass, pTcb->BufferList[idx].Length - OffsetToByPass); } } // // Append MIC to tail. // SecMICGetMIC(&micdata, pTcb->Tailer.VirtualAddress); pTcb->Tailer.Length = TKIP_MIC_LEN; pTcb->BufferList[pTcb->BufferCount] = pTcb->Tailer; pTcb->BufferCount++; pTcb->PacketLength += TKIP_MIC_LEN; //PRINT_DATA("TX_MIC======>", pTcb->Tailer.VirtualAddress, 8); } // // Calculate CKIP MIC. // Ported from CKIP code, Annie, 2006-08-11. // VOID SecCalculateCKIPMIC( PADAPTER Adapter, PRT_TCB pTcb ) { PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; u1Byte keyidx = pSec->DefaultTransmitKeyIdx; u4Byte idx = 0; pu1Byte pucMIC; // u1Byte MICdata[2000] = {0}; pu1Byte MICdata; int datalen = 0; PRT_GEN_TEMP_BUFFER pGenBufMICdata; RT_TRACE( COMP_CKIP, DBG_TRACE, ("==> SecCalculateCKIPMIC()\n") ); if( !pSec->pCkipPara->bIsMIC) // if not support MIC retun , added by CCW return; pGenBufMICdata = GetGenTempBuffer (Adapter, 2000); MICdata = (pu1Byte)pGenBufMICdata->Buffer.Ptr; //ckip_miccalc(Adapter, key, pDA, pSA, dcr, dcrlen, calcmic, mickeyid); // key = wep key , dcr = payload ( | LLC | SNAP |MIC |SEQ |eth-payload |) for(idx=1;idx<pTcb->BufferCount;idx++){ // Only check first nonzero buffer if(pTcb->BufferList[idx].Length==0) continue; PlatformMoveMemory( MICdata + datalen, pTcb->BufferList[idx].VirtualAddress, pTcb->BufferList[idx].Length ); datalen += pTcb->BufferList[idx].Length; } pucMIC = pTcb->BufferList[1].VirtualAddress + 8 ; // Set MIC file point ckip_miccalc( Adapter , pSec->pCkipPara->CKIPKeyBuf[keyidx] , pTcb->DestinationAddress ,pTcb->SourceAddress , MICdata ,datalen , pucMIC , keyidx ); ReturnGenTempBuffer (Adapter, pGenBufMICdata); RT_TRACE( COMP_CKIP, DBG_TRACE, ("<== SecCalculateCKIPMIC()\n") ); } VOID SecSoftwareEncryption( PADAPTER Adapter, PRT_TCB pTcb ) { RT_ENC_ALG SelectEncAlgorithm; PMGNT_INFO pMgntInfo = &Adapter->MgntInfo; if(pMgntInfo->SafeModeEnabled) { RT_TRACE_F(COMP_SEND, DBG_LOUD, ("Do not use software encrypt when safemode enable\n")); return; } if( pTcb->bBTTxPacket ) { if(pTcb->EncInfo.IsEncByHW) { RT_TRACE( COMP_SEC , DBG_LOUD , (" ===> BT used HW encrypt !!No enter Sw encrypt !!\n") ); return; } else SelectEncAlgorithm = RT_ENC_ALG_AESCCMP; } else SelectEncAlgorithm = Adapter->MgntInfo.SecurityInfo.PairwiseEncAlgorithm; switch(SelectEncAlgorithm) { case RT_ENC_ALG_WEP40: case RT_ENC_ALG_WEP104: if( !Adapter->MgntInfo.SecurityInfo.pCkipPara->bIsKP ) { // WEP case. SecSWWEPEncryption(Adapter, pTcb); } else { // CKIP case. SecSWCKIPEncryption(Adapter, pTcb); } break; case RT_ENC_ALG_TKIP: SecSWTKIPEncryption(Adapter, pTcb); break; case RT_ENC_ALG_AESCCMP: SecSWAESEncryption(Adapter, pTcb); break; case RT_ENC_ALG_SMS4: WAPI_SecFuncHandler(WAPI_SECSWSMS4ENCRYPTION, Adapter, (PVOID)pTcb, WAPI_END); break; default: break; } } // From kcwu 2004/09/24. VOID SecSWTKIPEncryption( PADAPTER Adapter, PRT_TCB pTcb ) { u4Byte FragIndex = 0; u4Byte BufferIndex = 0; u2Byte FragBufferCount = 0; PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; //u1Byte SecBuffer[2000]; u4Byte SpecificHeadOverhead = 0; u4Byte SecBufLen = 0; u4Byte SecBytesCopied = 0; u4Byte SecBufIndex = 0; u4Byte FragBufferIndexStart = 0; pu1Byte SecPtr = 0; u4Byte SecLenForCopy = 0; pu1Byte pHeader = pTcb->BufferList[0].VirtualAddress; u1Byte key[16]; u2Byte u2IV16; u4Byte u4IV32; PMGNT_INFO pMgntInfo=&Adapter->MgntInfo; PRT_WLAN_STA pEntry = NULL;// = AsocEntry_GetEntry(pMgntInfo, pTcb->DestinationAddress); u1Byte IVOffset; // Added by Annie, 2005-12-23. u1Byte DataOffset; // Added by Annie, 2005-12-23. SpecificHeadOverhead = Adapter->TXPacketShiftBytes; pHeader += SpecificHeadOverhead; // AP mode: get key. if(ACTING_AS_AP(Adapter)) { // AP mode. if(MacAddr_isMulticast(pTcb->DestinationAddress)) { // [AnnieNote] Current GTK is 12345678...12345678, so it's OK. // It's better to modify it by GTK length if we use PRF-X to generate GTK later. 2005-12-23. // //Check if set GTK was completed if(Adapter->MgntInfo.globalKeyInfo.GTK[0] == 0) return; } else { //Check if STA within associated lsit table pEntry = AsocEntry_GetEntry(pMgntInfo, pTcb->DestinationAddress); if(pEntry == NULL) return; //Check if set PTK was completed if(pEntry->perSTAKeyInfo.TempEncKey == NULL) return; } } // Get offset. Annie, 2005-12-23. if( IsQoSDataFrame(pHeader) ) { IVOffset = sMacHdrLng + sQoSCtlLng; } else { IVOffset = sMacHdrLng; } DataOffset = IVOffset + EXT_IV_LEN; // Get u2IV16 and u4IV32. u2IV16 = ((u2Byte)(*(pHeader+IVOffset + 0)) << 8) + \ ((u2Byte)(*(pHeader+IVOffset + 2)) << 0); u4IV32 = ((u4Byte) (*(pHeader+IVOffset + 4)) << 0) + \ ((u4Byte) (*(pHeader+IVOffset + 5)) << 8) + \ ((u4Byte) (*(pHeader+IVOffset + 6)) << 16) + \ ((u4Byte) (*(pHeader+IVOffset + 7)) << 24); if(ACTING_AS_AP(Adapter)) { // AP mode. if(MacAddr_isMulticast(pTcb->DestinationAddress)) { TKIPGenerateKey(key, u4IV32, u2IV16, pMgntInfo->Bssid, &Adapter->MgntInfo.globalKeyInfo.GTK[0]); } else { if(pEntry != NULL) TKIPGenerateKey(key, u4IV32, u2IV16, pMgntInfo->Bssid, pEntry->perSTAKeyInfo.TempEncKey); } } else { // STA mode. TKIPGenerateKey(key, u4IV32, u2IV16, pTcb->SourceAddress, pSec->KeyBuf[SecGetTxKeyIdx(Adapter, pTcb->DestinationAddress)]); } //TKIP_TSC_DECIMAL2ARRAY(pSec->SWTKIPu2IV16, pSec->SWTKIPu4IV32, ulKeyIndex, pucIV); for(FragIndex = 0; FragIndex < pTcb->FragCount; FragIndex++) { FragBufferIndexStart = BufferIndex; SecBufLen = 0; //2004/09/14, kcwu, clear the Security Coalesce Buffer PlatformZeroMemory(pSec->SecBuffer, SW_ENCRYPT_BUF_SIZE); //2004/09/14, kcwu, to show how many buffers are there used by this fragment FragBufferCount = pTcb->FragBufCount[FragIndex]; //2004/09/14, kcwu, data to be encrypted start at the second buffer if(!TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { BufferIndex = FragBufferIndexStart+1; FragBufferCount--; // 2005.11.04, by rcnjko. } // Concatenate buffers to be encrypted into the buffer, SecBuffer. // SecBuffer for TKIP does not include 802.11 header and IV. while(FragBufferCount-- > 0) { if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { if(pTcb->BufferList[BufferIndex].Length > (SpecificHeadOverhead+DataOffset)) { SecPtr = pTcb->BufferList[BufferIndex].VirtualAddress + (SpecificHeadOverhead+DataOffset); SecLenForCopy = pTcb->BufferList[BufferIndex].Length - (SpecificHeadOverhead+DataOffset); } } else { SecPtr = pTcb->BufferList[BufferIndex].VirtualAddress; SecLenForCopy = pTcb->BufferList[BufferIndex].Length; } // 20110819 Joseph: Prevent from buffer overflow. if((SecBufLen + SecLenForCopy)>SW_ENCRYPT_BUF_SIZE) { SecLenForCopy = SW_ENCRYPT_BUF_SIZE - SecBufLen; FragBufferCount = 0; RT_TRACE( COMP_SEC, DBG_SERIOUS, ("SecSWTKIPEncryption(): Packet is too large. Truncate!!\n") ); } PlatformMoveMemory( pSec->SecBuffer + SecBufLen, // 2005.11.04, by rcnjko. SecPtr, SecLenForCopy); SecBufLen += SecLenForCopy; BufferIndex++; //DbgPrint("FragBufferCount = %d, SecBufLen = %d, BufferIndex = %d\n", // FragBufferCount, SecBufLen, BufferIndex); } if(SecBufLen <= 0) { continue; } //PRINT_DATA("SecSWWEPEncryption_before_encrypted==>", SecBuffer, SecBufLen); EncodeWEP(key, 16, pSec->SecBuffer, SecBufLen, pSec->SecBuffer); //PRINT_DATA("SecSWWEPEncryption_after_encrypted==>", SecBuffer, SecBufLen+4); // For WEP ICV. SecBufLen += 4; SecBytesCopied = 0; // 2005.11.04, by rcnjko. if(!TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { SecBufIndex = FragBufferIndexStart+1; FragBufferCount = 1; } else { SecBufIndex = FragBufferIndexStart; FragBufferCount = 0; } // //2004/09/14, then copy SecBuffer back to the buffer // 2005.11.04, by rcnjko. if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { PlatformMoveMemory( pTcb->BufferList[SecBufIndex].VirtualAddress+(SpecificHeadOverhead+DataOffset), pSec->SecBuffer+SecBytesCopied, pTcb->BufferList[SecBufIndex].Length-(SpecificHeadOverhead+DataOffset) ); SecBytesCopied += pTcb->BufferList[SecBufIndex].Length-(SpecificHeadOverhead+DataOffset); SecBufIndex++; FragBufferCount++; } // while(FragBufferCount < pTcb->FragBufCount[FragIndex]){ PlatformMoveMemory( pTcb->BufferList[SecBufIndex].VirtualAddress, pSec->SecBuffer+SecBytesCopied, pTcb->BufferList[SecBufIndex].Length ); SecBytesCopied += pTcb->BufferList[SecBufIndex].Length; SecBufIndex++; FragBufferCount++; } // Copy WEP ICV. // 2005.11.04, by rcnjko. if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER) || pTcb->FragCount == 1) { PlatformMoveMemory( pTcb->BufferList[SecBufIndex-1].VirtualAddress+pTcb->BufferList[SecBufIndex-1].Length, pSec->SecBuffer+SecBytesCopied, pSec->EncryptionTailOverhead ); pTcb->BufferList[SecBufIndex-1].Length += pSec->EncryptionTailOverhead; //4; //Fix MPE SUT System Hang,120715, by YJ. SecBytesCopied += pSec->EncryptionTailOverhead; pTcb->FragLength[FragIndex] += pSec->EncryptionTailOverhead; pTcb->PacketLength += pSec->EncryptionTailOverhead; } else { // TODO: non-coalesce and fragmneted case. } } } // From kcwu 2004/09/24. VOID SecSWWEPEncryption( PADAPTER Adapter, PRT_TCB pTcb ) { u4Byte FragIndex = 0; u4Byte BufferIndex = 0; u2Byte FragBufferCount = 0; u1Byte key[16]; u4Byte wepIV=0; PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; //u1Byte SecBuffer[2000]; // 3000 -> 2000 to prevent stack overflow problem in Win98, 2005.03.15, by rcnjko. u4Byte SpecificHeadOverhead = 0; u4Byte SecBufLen = 0; u4Byte SecBytesCopied = 0; u4Byte SecBufIndex = 0; u4Byte FragBufferIndexStart = 0; pu1Byte SecPtr = 0; u4Byte SecLenForCopy = 0; pu1Byte pHeader; u1Byte IVOffset; // Added by Annie, 2005-12-23. u1Byte DataOffset; // Added by Annie, 2005-12-23. pHeader = pTcb->BufferList[FragBufferIndexStart].VirtualAddress; SpecificHeadOverhead = Adapter->TXPacketShiftBytes; pHeader += SpecificHeadOverhead; // Get offset. Annie, 2005-12-23. if( IsQoSDataFrame(pHeader) ) { IVOffset = sMacHdrLng + sQoSCtlLng; } else { IVOffset = sMacHdrLng; } DataOffset = IVOffset + WEP_IV_LEN; //2004/09/14, kcwu, the IV has been calculate, just get from current IV //wepIV.ul = (u4Byte) ((pSec->TxIV == 0)?0x00fffffe:((pSec->TxIV-1)&0x00ffffff)); SET_WEP_IV_INITVECTOR(&wepIV, *(UNALIGNED pu4Byte)(pHeader+IVOffset)); SET_WEP_IV_KEYID(& wepIV, pSec->DefaultTransmitKeyIdx); //PRINT_DATA("SecSWWEPEncryption==>", (pu1Byte)&wepIV, 4); PlatformMoveMemory(key, (pHeader+IVOffset), 3); PlatformMoveMemory(key+3, pSec->KeyBuf[pSec->DefaultTransmitKeyIdx], (pSec->PairwiseEncAlgorithm==RT_ENC_ALG_WEP104)?13:5); for(FragIndex = 0; FragIndex < pTcb->FragCount; FragIndex++) { FragBufferIndexStart = BufferIndex; SecBufLen = 0; //2004/09/14, kcwu, clear the Security Coalesce Buffer PlatformZeroMemory(pSec->SecBuffer, SW_ENCRYPT_BUF_SIZE); // 3000 -> 2000 to prevent stack overflow problem in Win98, 2005.03.15, by rcnjko. //2004/09/14, kcwu, to show how many buffers are there used by this fragment FragBufferCount = pTcb->FragBufCount[FragIndex]; // For non-coalesce case, data to be encrypted start at the second buffer. if(!TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { BufferIndex = FragBufferIndexStart+1; FragBufferCount--; // 2005.11.07, by rcnjko. } // Concatenate buffers to be encrypted into the buffer, SecBuffer. // SecBuffer for WEP does not include 802.11 header and IV. while(FragBufferCount-- > 0) { if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { if(pTcb->BufferList[BufferIndex].Length > (SpecificHeadOverhead+DataOffset)) { SecPtr = pTcb->BufferList[BufferIndex].VirtualAddress + (SpecificHeadOverhead+DataOffset); SecLenForCopy = pTcb->BufferList[BufferIndex].Length - (SpecificHeadOverhead+DataOffset); } } else { SecPtr = pTcb->BufferList[BufferIndex].VirtualAddress; SecLenForCopy = pTcb->BufferList[BufferIndex].Length; } // 20110819 Joseph: Prevent from buffer overflow. if((SecBufLen + SecLenForCopy)>SW_ENCRYPT_BUF_SIZE) { SecLenForCopy = SW_ENCRYPT_BUF_SIZE - SecBufLen; FragBufferCount = 0; RT_TRACE( COMP_SEC, DBG_SERIOUS, ("SecSWWEPEncryption(): Packet is too large. Truncate!!\n") ); } PlatformMoveMemory( pSec->SecBuffer + SecBufLen, // 2005.11.07, by rcnjko. SecPtr, SecLenForCopy); SecBufLen += SecLenForCopy; BufferIndex++; //DbgPrint("FragBufferCount = %d, SecBufLen = %d, BufferIndex = %d\n", // FragBufferCount, SecBufLen, BufferIndex); } if(SecBufLen <= 0) { continue; } //PRINT_DATA("SecSWWEPEncryption_before_encrypted==>", pSec->SecBuffer, SecBufLen); EncodeWEP(key, (pSec->PairwiseEncAlgorithm==RT_ENC_ALG_WEP104)?16:8, pSec->SecBuffer, SecBufLen, pSec->SecBuffer); //PRINT_DATA("SecSWWEPEncryption_after_encrypted==>", pSec->SecBuffer, SecBufLen+4); // For WEP ICV. SecBufLen += 4; SecBytesCopied = 0; // 2005.11.07, by rcnjko. if(!TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { SecBufIndex = FragBufferIndexStart+1; FragBufferCount = 1; } else { SecBufIndex = FragBufferIndexStart; FragBufferCount = 0; } // //2004/09/14, then copy SecBuffer back to the buffer // 2005.11.04, by rcnjko. if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { PlatformMoveMemory( pTcb->BufferList[SecBufIndex].VirtualAddress+(SpecificHeadOverhead+DataOffset), pSec->SecBuffer+SecBytesCopied, pTcb->BufferList[SecBufIndex].Length-(SpecificHeadOverhead+DataOffset) ); SecBytesCopied += pTcb->BufferList[SecBufIndex].Length-(SpecificHeadOverhead+DataOffset); SecBufIndex++; FragBufferCount++; } // while(FragBufferCount < pTcb->FragBufCount[FragIndex]) { PlatformMoveMemory( pTcb->BufferList[SecBufIndex].VirtualAddress, pSec->SecBuffer+SecBytesCopied, pTcb->BufferList[SecBufIndex].Length ); SecBytesCopied += pTcb->BufferList[SecBufIndex].Length; SecBufIndex++; FragBufferCount++; } // Copy WEP ICV. // 2005.11.07, by rcnjko. if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { PlatformMoveMemory( pTcb->BufferList[SecBufIndex-1].VirtualAddress+pTcb->BufferList[SecBufIndex-1].Length, pSec->SecBuffer+SecBytesCopied, pSec->EncryptionTailOverhead ); pTcb->BufferList[SecBufIndex-1].Length += pSec->EncryptionTailOverhead; // 4; //Fix MPE SUT System Hang,120715, by YJ. SecBytesCopied += pSec->EncryptionTailOverhead; pTcb->FragLength[FragIndex] += pSec->EncryptionTailOverhead; pTcb->PacketLength += pSec->EncryptionTailOverhead; } else { // For non-coalesce case, the WEP ICV cannot append to last buffer of the fragment directly, // because the buffer might belong to upper layer and we are NOT allow to change its length. if(pTcb->FragCount == 1) { PlatformMoveMemory( pTcb->Tailer.VirtualAddress, pSec->SecBuffer+SecBytesCopied, pSec->EncryptionTailOverhead ); pTcb->Tailer.Length = pSec->EncryptionTailOverhead; pTcb->BufferList[pTcb->BufferCount] = pTcb->Tailer; pTcb->BufferCount++; pTcb->FragLength[FragIndex] += pSec->EncryptionTailOverhead; pTcb->FragBufCount[FragIndex]++; pTcb->PacketLength += pSec->EncryptionTailOverhead; SecBytesCopied += pSec->EncryptionTailOverhead; } else { // TODO: non-coalesce and fragmneted case. } } // } } VOID SecSWAESEncryption( PADAPTER Adapter, PRT_TCB pTcb ) { u4Byte keyidx=0; u4Byte FragIndex = 0; u4Byte BufferIndex = 0; u2Byte FragBufferCount = 0; PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; //u1Byte SecBuffer[2000]; u4Byte SpecificHeadOverhead = 0; u4Byte SecBufLen = 0; u4Byte SecBytesCopied = 0; u4Byte SecBufIndex = 0; u4Byte FragBufferIndexStart = 0; pu1Byte SecPtr = 0; u4Byte SecLenForCopy = 0; pu1Byte pHeader = pTcb->BufferList[0].VirtualAddress; u1Byte IVOffset; // Added by Annie, 2005-12-23. u1Byte DataOffset; // Added by Annie, 2005-12-23. PRT_WLAN_STA pEntry; PMGNT_INFO pMgntInfo=&Adapter->MgntInfo; OCTET_STRING frame; SpecificHeadOverhead = Adapter->TXPacketShiftBytes; pHeader += SpecificHeadOverhead; FillOctetString(frame, pHeader, (u2Byte)pTcb->PacketLength); // Get offset. Annie, 2005-12-23. if( IsQoSDataFrame(pHeader) ) { IVOffset = sMacHdrLng + sQoSCtlLng; } else { IVOffset = sMacHdrLng; } // check address 4 if( Frame_ValidAddr4(frame) ) { RT_TRACE( COMP_SEC , DBG_LOUD , ("====>ccw BT data SecSWAESEncryption \n") ); IVOffset += ETHERNET_ADDRESS_LENGTH; } DataOffset = IVOffset + EXT_IV_LEN; if(ACTING_AS_AP(Adapter)) { if(MacAddr_isMulticast(pTcb->DestinationAddress)) { // TODO: //keyidx = } else { // TODO: //keyidx = } } else { keyidx = SecGetTxKeyIdx(Adapter, pTcb->DestinationAddress); } for(FragIndex = 0; FragIndex < pTcb->FragCount; FragIndex++) { FragBufferIndexStart = BufferIndex; SecBufLen = 0; //2004/09/14, kcwu, clear the Security Coalesce Buffer PlatformZeroMemory(pSec->SecBuffer, SW_ENCRYPT_BUF_SIZE); //2004/09/14, kcwu, to show how many buffers are there used by this fragment FragBufferCount = pTcb->FragBufCount[FragIndex]; // Concatenate buffers to be encrypted into the buffer, SecBuffer. // SecBuffer for AES contains 802.11 header and IV information to encrypt data. while(FragBufferCount-- > 0) { if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { if(pTcb->BufferList[BufferIndex].Length > SpecificHeadOverhead) { SecPtr = pTcb->BufferList[BufferIndex].VirtualAddress + SpecificHeadOverhead; SecLenForCopy = pTcb->BufferList[BufferIndex].Length - SpecificHeadOverhead; } } else { SecPtr = pTcb->BufferList[BufferIndex].VirtualAddress; SecLenForCopy = pTcb->BufferList[BufferIndex].Length; } // 20110819 Joseph: Prevent from buffer overflow. if((SecBufLen + SecLenForCopy)>SW_ENCRYPT_BUF_SIZE) { SecLenForCopy = SW_ENCRYPT_BUF_SIZE - SecBufLen; FragBufferCount = 0; RT_TRACE( COMP_SEC, DBG_SERIOUS, ("SecSWAESEncryption(): Packet is too large. Truncate!!\n") ); } PlatformMoveMemory( pSec->SecBuffer + SecBufLen, // 2005.11.07, by rcnjko. SecPtr, SecLenForCopy); SecBufLen += SecLenForCopy; BufferIndex++; //DbgPrint("FragBufferCount = %d, SecBufLen = %d, BufferIndex = %d\n", // FragBufferCount, SecBufLen, BufferIndex); } if(SecBufLen <= 0) { continue; } #ifdef SW_TXENCRYPTION_DBG RT_TRACE(COMP_SEC, DBG_LOUD, ("\n\nKeyIndex = %d\n", SecGetTxKeyIdx(Adapter, pTcb->DestinationAddress))); PRINT_DATA("AESKeyBuf===>", pSec->AESKeyBuf[SecGetTxKeyIdx(Adapter, pTcb->DestinationAddress)], 16); PRINT_DATA("SecBuffer_before ====>", pSec->SecBuffer, SecBufLen); #endif if(pTcb->bTDLPacket) { pEntry = AsocEntry_GetEntry(pMgntInfo, pTcb->DestinationAddress); if(pEntry == NULL) return; //Check if set PTK was completed if(pEntry->perSTAKeyInfo.AESKeyBuf[0] == 0) return; SecRSNAEncodeAESCCM( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)pEntry->perSTAKeyInfo.AESKeyBuf, 0, pSec->SecBuffer, IVOffset, SecBufLen ); } else if( !Adapter->MgntInfo.bRSNAPSKMode && !ACTING_AS_AP(Adapter) ) { // NO RSNA-PSK and AP-mode if(pTcb->EncInfo.bMFPPacket && pMgntInfo->bInBIPMFPMode) { SecMFPEncodeAESCCM_1W( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)Adapter->MgntInfo.SecurityInfo.AESKeyBuf[0], keyidx, pSec->SecBuffer, IVOffset, SecBufLen ); //RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "BIP AES EncData:\n", pHeader, pTcb->PacketLength); } else { SecEncodeAESCCM( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)Adapter->MgntInfo.SecurityInfo.AESKeyBuf[keyidx], pSec->SecBuffer, IVOffset, SecBufLen ); } } //AP WPA AES, CCW else if( ACTING_AS_AP(Adapter) ) { // AP mode if(MacAddr_isMulticast(pTcb->DestinationAddress)) {// Multicase packet , used AESGTK //RT_TRACE(COMP_WPAAES, DBG_LOUD, ("<===== AP WPA AES Multicase\n")); //Check if set GTK was completed if(Adapter->MgntInfo.globalKeyInfo.AESGTK[0] == 0) return; SecRSNAEncodeAESCCM( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)Adapter->MgntInfo.globalKeyInfo.AESGTK, pSec->GroupTransmitKeyIdx, pSec->SecBuffer, IVOffset, SecBufLen ); //RT_TRACE(COMP_WPAAES, DBG_LOUD, ("=====> AP WPA AES Multicase\n")); } else { // unitcase packet , used Entry Pairwise key //RT_TRACE(COMP_WPAAES, DBG_LOUD, ("<===== AP WPA AES unitcase\n")); //Check if STA within associated lsit table pEntry = AsocEntry_GetEntry(pMgntInfo, pTcb->DestinationAddress); if(pEntry == NULL) return; //Check if set PTK was completed if(pEntry->perSTAKeyInfo.AESKeyBuf[0] == 0) return; SecRSNAEncodeAESCCM( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)pEntry->perSTAKeyInfo.AESKeyBuf, 0, pSec->SecBuffer, IVOffset, SecBufLen ); //RT_TRACE(COMP_WPAAES, DBG_LOUD, ("=====> AP WPA AES unitcase\n")); } } else { // RSNA-PSK mode OCTET_STRING pduOS; pu1Byte pRA; pu1Byte pTA; u4Byte index; FillOctetString(pduOS, pHeader, IVOffset); pRA = Frame_Addr1(pduOS); pTA = Frame_Addr2(pduOS); RT_TRACE(COMP_RSNA, DBG_LOUD,( "=====>RSNA IBSS Send Encrypt packet \n")); RT_PRINT_ADDR(COMP_RSNA, DBG_LOUD, "RSNA RA : ", pRA); RT_PRINT_ADDR(COMP_RSNA, DBG_LOUD, "RSNA TA : ", pTA); if(MacAddr_isMulticast(pRA)) { PPER_STA_DEFAULT_KEY_ENTRY pDefKey; // Add by CCW // // TODO: remvoe our group key from PerStaDefKeyTable[] // //Multicast packet //Find out Default KEY Entry pDefKey = pSec->PerStaDefKeyTable; for( index = 0 ; index < MAX_NUM_PER_STA_KEY ; index++, pDefKey++) { if( pDefKey->Valid && (PlatformCompareMemory(pDefKey->MACAdrss , pTA, 6)==0)) break; } if(index != MAX_NUM_PER_STA_KEY) { RT_TRACE(COMP_RSNA, DBG_LOUD, ("DefaultTransmitKeyIdx: %d\n", pSec->DefaultTransmitKeyIdx)); RT_PRINT_DATA(COMP_RSNA, DBG_LOUD, " Multicase Default key : ", pDefKey->DefKeyBuf[pSec->DefaultTransmitKeyIdx], 16); SecRSNAEncodeAESCCM( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)pDefKey->DefKeyBuf[pSec->DefaultTransmitKeyIdx], pSec->DefaultTransmitKeyIdx, pSec->SecBuffer, IVOffset, SecBufLen ); } else { // no key found! RT_PRINT_ADDR(COMP_RSNA, DBG_WARNING, ("SecSWAESEncryption(): No group key found for pTA: \n"), pTA); } } else { PPER_STA_MPAKEY_ENTRY pMAPkey; // Add by CCW //unicast packet //Find out MAPPING Key Entry. pMAPkey = pSec->MAPKEYTable; for( index = 0 ; index < MAX_NUM_PER_STA_KEY ; index++, pMAPkey++) { if( pMAPkey->Valid && (PlatformCompareMemory(pMAPkey->MACAdrss , pRA, 6)==0)) break; } if(index != MAX_NUM_PER_STA_KEY) { RT_PRINT_DATA(COMP_RSNA, DBG_LOUD, " Unicase Key Mapping key : ", pMAPkey->MapKeyBuf , 16); SecRSNAEncodeAESCCM( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)pMAPkey->MapKeyBuf, 0, // default = 0. pSec->SecBuffer, IVOffset, SecBufLen ); } else { // no key found! RT_PRINT_ADDR(COMP_RSNA, DBG_WARNING, ("SecSWAESEncryption(): No pairwse key found for pRA: \n"), pRA); } } } // For AES MIC. SecBufLen += 8; #ifdef SW_TXENCRYPTION_DBG PRINT_DATA("SecBuffer_after ====>", pSec->SecBuffer, SecBufLen); if(SecBufLen == 147) { RT_TRACE(COMP_SEC, DBG_LOUD, ("SecSWAESEncryption:SecBufLen = %d\n", SecBufLen)); } #endif SecBytesCopied = 0; // 2005.11.07, by rcnjko. if(!TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { SecBufIndex = FragBufferIndexStart+1; FragBufferCount = 1; } else { SecBufIndex = FragBufferIndexStart; FragBufferCount = 0; } // //2004/09/14, then copy SecBuffer back to the buffer // 2005.11.07, by rcnjko. if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { PlatformMoveMemory( pTcb->BufferList[SecBufIndex].VirtualAddress + (SpecificHeadOverhead+DataOffset), pSec->SecBuffer+DataOffset+SecBytesCopied, pTcb->BufferList[SecBufIndex].Length - (SpecificHeadOverhead+DataOffset) ); SecBytesCopied += pTcb->BufferList[SecBufIndex].Length - (SpecificHeadOverhead+DataOffset); SecBufIndex++; FragBufferCount++; } // while(FragBufferCount < pTcb->FragBufCount[FragIndex]) { PlatformMoveMemory( pTcb->BufferList[SecBufIndex].VirtualAddress, pSec->SecBuffer+DataOffset+SecBytesCopied, // 2005.11.07, by rcnjko. pTcb->BufferList[SecBufIndex].Length ); SecBytesCopied += pTcb->BufferList[SecBufIndex].Length; SecBufIndex++; FragBufferCount++; } // Copy AES MIC. // 2005.11.07, by rcnjko. if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { PlatformMoveMemory( pTcb->BufferList[SecBufIndex-1].VirtualAddress+pTcb->BufferList[SecBufIndex-1].Length, pSec->SecBuffer+DataOffset+SecBytesCopied, 8//pSec->EncryptionTailOverhead ); pTcb->BufferList[SecBufIndex-1].Length += 8;//pSec->EncryptionTailOverhead; SecBytesCopied += 8;//pSec->EncryptionTailOverhead; pTcb->FragLength[FragIndex] += 8;//pSec->EncryptionTailOverhead; pTcb->PacketLength += 8;//pSec->EncryptionTailOverhead; } else { // For non-coalesce case, the AES MIC cannot append to last buffer of the fragment directly, // because the buffer might belong to upper layer and we are NOT allow to change its length. if(pTcb->FragCount == 1) { PlatformMoveMemory( pTcb->Tailer.VirtualAddress, pSec->SecBuffer+DataOffset+SecBytesCopied, 8//pSec->EncryptionTailOverhead ); pTcb->Tailer.Length = 8;//pSec->EncryptionTailOverhead; pTcb->BufferList[pTcb->BufferCount] = pTcb->Tailer; pTcb->BufferCount++; pTcb->FragLength[FragIndex] += 8;//pSec->EncryptionTailOverhead; pTcb->FragBufCount[FragIndex]++; pTcb->PacketLength += 8;//pSec->EncryptionTailOverhead; SecBytesCopied += 8;//pSec->EncryptionTailOverhead; } else { // TODO: non-coalesce and fragmneted case. } } // } } // // Software encryption for CKIP. // Ported from CKIP code, Annie, 2006-08-11. [AnnieTODO] // VOID SecSWCKIPEncryption( PADAPTER Adapter, PRT_TCB pTcb ) { u4Byte FragIndex = 0; u4Byte BufferIndex = 0; u2Byte FragBufferCount = 0; u4Byte FragBufferIndexStart = 0; u4Byte SecBufLen = 0; u4Byte SecBufIndex = 0; pu1Byte SecPtr = 0; u4Byte SecLenForCopy = 0; pu1Byte pucIV =0; PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; ULONG keyidx = pSec->DefaultTransmitKeyIdx; //UCHAR key[16] = {0}; pu1Byte pHeader = pTcb->BufferList[0].VirtualAddress; //u1Byte SecBuffer[2000] = {0}; u4Byte SpecificHeadOverhead = 0; u1Byte IVOffset; u1Byte DataOffset; u4Byte SecBytesCopied = 0; RT_TRACE( COMP_CKIP, DBG_TRACE, ("==> SecSWCKIPEncryption()\n") ); SpecificHeadOverhead = Adapter->TXPacketShiftBytes; pHeader += SpecificHeadOverhead; if( !pSec->pCkipPara->bIsKP ) { //Pure WEP RT_TRACE( COMP_CKIP, DBG_LOUD, ("SecSWCKIPEncryption(): Use pure WEP encryption.\n") ); SecSWWEPEncryption(Adapter,pTcb); } else { // Do Key Permutation RT_TRACE( COMP_CKIP, DBG_TRACE, ("SecSWCKIPEncryption(): CKIP case: Do Key Permutation.\n") ); for(FragIndex = 0; FragIndex < pTcb->FragCount; FragIndex++) { FragBufferIndexStart = BufferIndex; SecBufLen = 0; if( IsQoSDataFrame(pHeader) ) { IVOffset = sMacHdrLng + sQoSCtlLng; } else { IVOffset = sMacHdrLng; } DataOffset = IVOffset + WEP_IV_LEN; PlatformZeroMemory(pSec->SecBuffer, SW_ENCRYPT_BUF_SIZE); FragBufferCount = pTcb->FragBufCount[FragIndex]; //2004/09/14, kcwu, data to be encrypted start at the second buffer if(!TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { BufferIndex = FragBufferIndexStart+1; FragBufferCount--; // 2005.11.04, by rcnjko. } // Concatenate buffers to be encrypted into the buffer, SecBuffer. // SecBuffer for TKIP does not include 802.11 header and IV. while(FragBufferCount-- > 0) { if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { if(pTcb->BufferList[BufferIndex].Length > (SpecificHeadOverhead+DataOffset)) { SecPtr = pTcb->BufferList[BufferIndex].VirtualAddress + (SpecificHeadOverhead+DataOffset); SecLenForCopy = pTcb->BufferList[BufferIndex].Length - (SpecificHeadOverhead+DataOffset); // to get IV , by CCW pucIV = pTcb->BufferList[BufferIndex].VirtualAddress + (SpecificHeadOverhead+IVOffset); } } else { SecPtr = pTcb->BufferList[BufferIndex].VirtualAddress; SecLenForCopy = pTcb->BufferList[BufferIndex].Length; } // 20110819 Joseph: Prevent from buffer overflow. if((SecBufLen + SecLenForCopy)>SW_ENCRYPT_BUF_SIZE) { SecLenForCopy = SW_ENCRYPT_BUF_SIZE - SecBufLen; FragBufferCount = 0; RT_TRACE( COMP_SEC, DBG_SERIOUS, ("SecSWCKIPEncryption(): Packet is too large. Truncate!!\n") ); } PlatformMoveMemory( pSec->SecBuffer + SecBufLen, // 2005.11.04, by rcnjko. SecPtr, SecLenForCopy); SecBufLen += SecLenForCopy; BufferIndex++; //DbgPrint("FragBufferCount = %d, SecBufLen = %d, BufferIndex = %d\n", // FragBufferCount, SecBufLen, BufferIndex); } if(SecBufLen <= 0) { continue; } ckip_encrypt( pSec->pCkipPara->CKIPKeyBuf[keyidx] , pucIV , pSec->SecBuffer , SecBufLen ); // For CKIP ICV. SecBufLen += 4; SecBytesCopied = 0; // 2005.11.04, by rcnjko. if(!TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { SecBufIndex = FragBufferIndexStart+1; FragBufferCount = 1; } else { SecBufIndex = FragBufferIndexStart; FragBufferCount = 0; } // //2004/09/14, then copy SecBuffer back to the buffer // 2005.11.04, by rcnjko. if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { PlatformMoveMemory( pTcb->BufferList[SecBufIndex].VirtualAddress+(SpecificHeadOverhead+DataOffset), pSec->SecBuffer+SecBytesCopied, pTcb->BufferList[SecBufIndex].Length-(SpecificHeadOverhead+DataOffset) ); SecBytesCopied += pTcb->BufferList[SecBufIndex].Length-(SpecificHeadOverhead+DataOffset); SecBufIndex++; FragBufferCount++; } // while(FragBufferCount < pTcb->FragBufCount[FragIndex]){ PlatformMoveMemory( pTcb->BufferList[SecBufIndex].VirtualAddress, pSec->SecBuffer+SecBytesCopied, pTcb->BufferList[SecBufIndex].Length ); SecBytesCopied += pTcb->BufferList[SecBufIndex].Length; SecBufIndex++; FragBufferCount++; } // Copy WEP ICV. // 2005.11.07, by rcnjko. if(TEST_FLAG(pTcb->tcbFlags, RT_TCB_FLAG_USE_COALESCE_BUFFER)) { PlatformMoveMemory( pTcb->BufferList[SecBufIndex-1].VirtualAddress+pTcb->BufferList[SecBufIndex-1].Length, pSec->SecBuffer+SecBytesCopied, pSec->EncryptionTailOverhead ); pTcb->BufferList[SecBufIndex-1].Length += 4; SecBytesCopied += pSec->EncryptionTailOverhead; pTcb->FragLength[FragIndex] += pSec->EncryptionTailOverhead; pTcb->PacketLength += pSec->EncryptionTailOverhead; } else { // For non-coalesce case, the WEP ICV cannot append to last buffer of the fragment directly, // because the buffer might belong to upper layer and we are NOT allow to change its length. if(pTcb->FragCount == 1) { PlatformMoveMemory( pTcb->Tailer.VirtualAddress, pSec->SecBuffer+SecBytesCopied, pSec->EncryptionTailOverhead ); pTcb->Tailer.Length = pSec->EncryptionTailOverhead; pTcb->BufferList[pTcb->BufferCount] = pTcb->Tailer; pTcb->BufferCount++; pTcb->FragLength[FragIndex] += pSec->EncryptionTailOverhead; pTcb->FragBufCount[FragIndex]++; pTcb->PacketLength += pSec->EncryptionTailOverhead; SecBytesCopied += pSec->EncryptionTailOverhead; } else { // TODO: non-coalesce and fragmneted case. } } } } RT_TRACE( COMP_CKIP, DBG_TRACE, ("<== SecSWCKIPEncryption()\n") ); } // // Check IV increase // // In Encrypt mode , IV is not increase ,and return FALSE. // RT_SEC_STATUS SecRxCheckIV( IN PADAPTER Adapter, IN PRT_RFD pRfd ) { RT_ENC_ALG DecryptAlgorithm; RT_SEC_STATUS secStatus = RT_SEC_STATUS_SUCCESS; pu1Byte DestAddr; OCTET_STRING Mpdu; BOOLEAN bMulticastDest; u2Byte EncryptionMPDUHeadOverhead, EncryptionMPDUTailOverhead; u2Byte EncryptionMSDUHeadOverhead, EncryptionMSDUTailOverhead; u2Byte MinEncPktSize; u1Byte IVOffset; // Added by Annie, 2005-12-23. PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; FillOctetString(Mpdu, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); DestAddr = Frame_pDaddr(Mpdu); bMulticastDest = MacAddr_isMulticast(DestAddr); if(!Frame_WEP(Mpdu)) { // Skip the non-encrypted frame, 2005.06.28, by rcnjko. return RT_SEC_STATUS_SUCCESS; } if(ACTING_AS_AP(Adapter)) return RT_SEC_STATUS_SUCCESS; SecGetEncryptionOverhead( Adapter, &EncryptionMPDUHeadOverhead, &EncryptionMPDUTailOverhead, &EncryptionMSDUHeadOverhead, &EncryptionMSDUTailOverhead, TRUE, bMulticastDest); MinEncPktSize = Frame_FrameHdrLng(Mpdu) + EncryptionMPDUHeadOverhead + EncryptionMSDUHeadOverhead + EncryptionMSDUTailOverhead + EncryptionMPDUTailOverhead; if(Mpdu.Length < MinEncPktSize) { // 061214, rcnjo: Discard invalid length frame to prevent memory access violation. return RT_SEC_STATUS_INVALID_PKT_LEN; } if(bMulticastDest) { DecryptAlgorithm = Adapter->MgntInfo.SecurityInfo.GroupEncAlgorithm; } else { DecryptAlgorithm = Adapter->MgntInfo.SecurityInfo.PairwiseEncAlgorithm; } // Get offset. Annie, 2005-12-23. if( pRfd->Status.bIsQosData ) { IVOffset = sMacHdrLng + sQoSCtlLng; } else { IVOffset = sMacHdrLng; } if(pRfd->Status.bContainHTC) IVOffset += sHTCLng; switch(DecryptAlgorithm) { case RT_ENC_ALG_WEP104: case RT_ENC_ALG_WEP40: { u4Byte TempIV = 0; // Get IV TempIV = (((u4Byte)( Mpdu.Octet[IVOffset] )) << 16 ) + (((u4Byte)( Mpdu.Octet[IVOffset+1] )) << 8 ) + (((u4Byte)( Mpdu.Octet[IVOffset+2] )) << 0 ); // Check IV // The 2 situations are not IV replay: (1) current IV of Pkt is greater than the rx IV (2) the current pkt is retry and IV is the same if(TempIV > pSec->RXUntiIV || (Frame_Retry(Mpdu) && pSec->RXUntiIV == TempIV)) pSec->RXUntiIV = TempIV; else secStatus = RT_SEC_STATUS_DATA_UNICAST_IV_REPLAY; } break; case RT_ENC_ALG_TKIP: case RT_ENC_ALG_AESCCMP: { u2Byte u2IV16; u4Byte u4IV32; u8Byte TempIV; // Get u2IV16 and u4IV32. u2IV16 = ((u2Byte)(*(Mpdu.Octet+IVOffset + 0)) << 8)+ \ ((u2Byte)(*(Mpdu.Octet+IVOffset + 2)) << 0); u4IV32 = ((u4Byte) (*(Mpdu.Octet+IVOffset + 4)) << 0)+ \ ((u4Byte) (*(Mpdu.Octet+IVOffset + 5)) << 8)+ \ ((u4Byte) (*(Mpdu.Octet+IVOffset + 6)) << 16)+ \ ((u4Byte) (*(Mpdu.Octet+IVOffset + 7)) << 24); // Get IV TempIV = u2IV16 + ((u8Byte)u4IV32 << 16 ); if( bMulticastDest ) { // The 2 situations are not IV replay: (1) current IV of Pkt is greater than the rx IV (2) the current pkt is retry and IV is the same if( TempIV > pSec->RXMutiIV || (Frame_Retry(Mpdu) && pSec->RXMutiIV == TempIV)) pSec->RXMutiIV = TempIV; else secStatus = RT_SEC_STATUS_DATA_MULTICAST_IV_REPLAY; } else { // The 2 situations are not IV replay: (1) current IV of Pkt is greater than the rx IV (2) the current pkt is retry and IV is the same if( TempIV > pSec->RXUntiIV || (Frame_Retry(Mpdu) && pSec->RXUntiIV == TempIV)) pSec->RXUntiIV = TempIV; else secStatus = RT_SEC_STATUS_DATA_UNICAST_IV_REPLAY; } } break; default: break; } if(secStatus != RT_SEC_STATUS_SUCCESS) { // Count Relay statistics if(IsDataFrame(Mpdu.Octet)) { switch(DecryptAlgorithm) { case RT_ENC_ALG_TKIP: CountRxTKIPRelpayStatistics(Adapter, pRfd); break; case RT_ENC_ALG_AESCCMP: CountRxCCMPRelpayStatistics(Adapter, pRfd); break; default: //for MacOSX Compiler warning. break; } } else if(IsMgntFrame(Mpdu.Octet)) { secStatus = RT_SEC_STATUS_MGNT_IV_REPLAY; switch(DecryptAlgorithm) { case RT_ENC_ALG_TKIP: CountRxMgntTKIPRelpayStatistics(Adapter, pRfd); break; case RT_ENC_ALG_AESCCMP: CountRxMgntCCMPRelpayStatistics(Adapter, pRfd); break; default: //for MacOSX Compiler warning. break; } } } return secStatus; } RT_SEC_STATUS SecSoftwareDecryption( PADAPTER Adapter, PRT_RFD pRfd ) { RT_ENC_ALG DecryptAlgorithm; RT_SEC_STATUS secStatus = RT_SEC_STATUS_SUCCESS; BOOLEAN bResult= TRUE; pu1Byte DestAddr; OCTET_STRING Mpdu; BOOLEAN bMulticastDest; u2Byte EncryptionMPDUHeadOverhead, EncryptionMPDUTailOverhead; u2Byte EncryptionMSDUHeadOverhead, EncryptionMSDUTailOverhead; u2Byte MinEncPktSize; FillOctetString(Mpdu, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); DestAddr = Frame_pDaddr(Mpdu); bMulticastDest = MacAddr_isMulticast(DestAddr); do { if(!Frame_WEP(Mpdu)) { // Skip the non-encrypted frame, 2005.06.28, by rcnjko. secStatus = RT_SEC_STATUS_SUCCESS; break; } if(!pRfd->bRxBTdata) { if(!eqMacAddr(Frame_pBssid(Mpdu), Adapter->MgntInfo.Bssid)) { // RT_PRINT_ADDR(COMP_SEC, DBG_WARNING, "Mismatched BSSID (RT_SEC_STATUS_UNKNOWN_TA):\nFrame_pBssid: ", Frame_pBssid(Mpdu)); // RT_PRINT_ADDR(COMP_SEC, DBG_WARNING, "MgntInfo.Bssid: ", Adapter->MgntInfo.Bssid); secStatus = RT_SEC_STATUS_UNKNOWN_TA; break; } } SecGetEncryptionOverhead( Adapter, &EncryptionMPDUHeadOverhead, &EncryptionMPDUTailOverhead, &EncryptionMSDUHeadOverhead, &EncryptionMSDUTailOverhead, TRUE, bMulticastDest); MinEncPktSize = Frame_FrameHdrLng(Mpdu) + EncryptionMPDUHeadOverhead + EncryptionMSDUHeadOverhead + EncryptionMSDUTailOverhead + EncryptionMPDUTailOverhead; if(Mpdu.Length < MinEncPktSize) { // 061214, rcnjo: Discard invalid length frame to prevent memory access violation. RT_TRACE_F(COMP_SEC, DBG_WARNING, ("RT_SEC_STATUS_INVALID_PKT_LEN, mpduLength(%d) < MinEncPktSize(%d)\n", Mpdu.Length, MinEncPktSize)); secStatus = RT_SEC_STATUS_INVALID_PKT_LEN; break; } if(bMulticastDest) { DecryptAlgorithm = Adapter->MgntInfo.SecurityInfo.GroupEncAlgorithm; } else { DecryptAlgorithm = Adapter->MgntInfo.SecurityInfo.PairwiseEncAlgorithm; } if(pRfd->bRxBTdata) { DecryptAlgorithm = RT_ENC_ALG_AESCCMP; } switch(DecryptAlgorithm) { case RT_ENC_ALG_WEP104: case RT_ENC_ALG_WEP40: if( !Adapter->MgntInfo.SecurityInfo.pCkipPara->bIsKP ) { // WEP decryption bResult = SecSWWEPDecryption(Adapter, pRfd); } else { // CKIP decryption bResult = SecSWCKIPDecryption(Adapter, pRfd); } break; case RT_ENC_ALG_TKIP: bResult = SecSWTKIPDecryption(Adapter, pRfd); break; case RT_ENC_ALG_AESCCMP: bResult = SecSWAESDecryption(Adapter, pRfd); break; case RT_ENC_ALG_SMS4: if(RT_STATUS_SUCCESS == WAPI_SecFuncHandler(WAPI_SECSWSMS4DECRYPTION, Adapter, (PVOID)pRfd, WAPI_END)) bResult = TRUE; break; default: break; } if(!bResult) { secStatus = RT_SEC_STATUS_ICV_ERROR; RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "SecSoftwareDecryption:() RT_SEC_STATUS_ICV_ERROR:\n", Mpdu.Octet, Mpdu.Length); if(Adapter->MgntInfo.uLastDecryptedErrorSeqNum == Frame_SeqNum(Mpdu)) { break; } RT_TRACE(COMP_RECV, DBG_TRACE, ("SecSoftwareDecryption:() CountRxDecryptErrorStatistics\n")); CountRxDecryptErrorStatistics(Adapter, pRfd); switch(DecryptAlgorithm) { case RT_ENC_ALG_WEP104: case RT_ENC_ALG_WEP40: if( !Adapter->MgntInfo.SecurityInfo.pCkipPara->bIsKP ) { // WEP decryption CountWEPUndecryptableStatistics(Adapter, pRfd); CountWEPICVErrorStatistics(Adapter, pRfd); } break; case RT_ENC_ALG_TKIP: CountTKIPICVErrorStatistics(Adapter, pRfd); break; case RT_ENC_ALG_AESCCMP: CountRxCCMPDecryptErrorsStatistics(Adapter, pRfd); break; default: break; } Adapter->MgntInfo.uLastDecryptedErrorSeqNum = Frame_SeqNum(Mpdu); break; } else CountRxDecryptSuccessStatistics(Adapter, pRfd); if(RT_SEC_STATUS_SUCCESS != secStatus) break; //3 // Check IV Replay // // In fact, we should discard this packet because of IV replay. // However, some packets may still be transmitted in disorder because the IV counter is filled by // driver but not HW. So these packets are indicated to the upper layer. // By Bruce, 2009-10-14. // secStatus = SecRxCheckIV(Adapter, pRfd); switch(secStatus) { case RT_SEC_STATUS_MGNT_IV_REPLAY: { RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "RT_SEC_STATUS_MGNT_IV_REPLAY:\n", Mpdu.Octet, Mpdu.Length); } break; default: // Skip normal case no matter if it is data IV replay. secStatus = RT_SEC_STATUS_SUCCESS; break; } }while(FALSE); return secStatus; } BOOLEAN SecSWAESDecryption( PADAPTER Adapter, PRT_RFD pRfd ) { u1Byte keyidx; u4Byte micOK; u1Byte IVOffset; // Added by Annie, 2005-12-23. u1Byte IVKeyIdOffset; // Added by Annie, 2005-12-23. PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; // Add by CCW PRT_WLAN_STA pEntry; PMGNT_INFO pMgntInfo=&Adapter->MgntInfo; OCTET_STRING frame; FillOctetString(frame, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); IVOffset = sMacHdrLng; if( pRfd->Status.bIsQosData ) { IVOffset += sQoSCtlLng; } if( pRfd->Status.bContainHTC) IVOffset += sHTCLng; // check address 4 if( Frame_ValidAddr4(frame) ) { IVOffset += ETHERNET_ADDRESS_LENGTH; } IVKeyIdOffset = IVOffset + 3; keyidx = SecGetRxKeyIdx( Adapter, pRfd->Buffer.VirtualAddress+4, ((pRfd->Buffer.VirtualAddress[IVKeyIdOffset]>>6)&0x03) ); if(pRfd->bTDLPacket) { pu1Byte pTA; OCTET_STRING pduOS; FillOctetString(pduOS, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); pTA = Frame_Addr2(pduOS); pEntry = AsocEntry_GetEntry(pMgntInfo, pTA); if(pEntry == NULL) return FALSE; //Check if set PTK was completed if(pEntry->perSTAKeyInfo.AESKeyBuf[0] == 0) return FALSE; micOK = SecDecodeAESCCM( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)pEntry->perSTAKeyInfo.AESKeyBuf, pRfd->Buffer.VirtualAddress, IVOffset, pRfd->PacketLength ); } else if( !Adapter->MgntInfo.bRSNAPSKMode && !ACTING_AS_AP(Adapter)) { if ( pMgntInfo->bInBIPMFPMode && pRfd->Status.bRxMFPPacket ) { //RT_TRACE_F(COMP_SEC, DBG_LOUD, ("Decrypt Rx Mgnt Frame\n")); micOK = SecMFPDecodeAESCCM_1W( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)Adapter->MgntInfo.SecurityInfo.AESKeyBuf[0], // 802.11 MFP used Pawise key to encrypt !! pRfd->Buffer.VirtualAddress, IVOffset, pRfd->PacketLength ); if(!micOK) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("[WARNING] Decryption failed, keyIdx = %d\n", keyidx)); } } else { micOK = SecDecodeAESCCM( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)Adapter->MgntInfo.SecurityInfo.AESKeyBuf[keyidx], pRfd->Buffer.VirtualAddress, IVOffset, pRfd->PacketLength ); } } else if( ACTING_AS_AP(Adapter) ) { pu1Byte pTA; OCTET_STRING pduOS; FillOctetString(pduOS, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); pTA = Frame_Addr2(pduOS); pEntry = AsocEntry_GetEntry(pMgntInfo, pTA); if(pEntry == NULL) return FALSE; //Check if set PTK was completed if(pEntry->perSTAKeyInfo.AESKeyBuf[0] == 0) return FALSE; micOK = SecDecodeAESCCM( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)pEntry->perSTAKeyInfo.AESKeyBuf, pRfd->Buffer.VirtualAddress, IVOffset, pRfd->PacketLength ); } else { OCTET_STRING pduOS; pu1Byte pRA; pu1Byte pTA; u4Byte index; FillOctetString(pduOS, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); pRA = Frame_Addr1(pduOS); pTA = Frame_Addr2(pduOS); RT_TRACE(COMP_RSNA , DBG_LOUD , (" =====> RSNA IBSS Recive Encrypt Packet\n")); keyidx = ((pRfd->Buffer.VirtualAddress[IVKeyIdOffset]>>6)&0x03); RT_PRINT_ADDR(COMP_RSNA, DBG_LOUD, "RSNA RA : ", pRA); RT_PRINT_ADDR(COMP_RSNA, DBG_LOUD, "RSNA TA : ", pTA); RT_TRACE(COMP_RSNA , DBG_LOUD , (" KEY ID : %02x \n" ,keyidx )); if(MacAddr_isMulticast(pRA)) { PPER_STA_DEFAULT_KEY_ENTRY pDefKey; // Add by CCW //Multicast packet //Find out Default KEY Entry pDefKey = pSec->PerStaDefKeyTable; for( index = 0 ; index < MAX_NUM_PER_STA_KEY ; index++, pDefKey++) { if( pDefKey->Valid && (PlatformCompareMemory(pDefKey->MACAdrss , pTA, 6)==0)) break; } if(index == MAX_NUM_PER_STA_KEY) { // no key found! RT_PRINT_ADDR(COMP_RSNA, DBG_WARNING, ("SecSWAESDecryption(): No group key found for pTA: \n"), pTA); return FALSE; } RT_PRINT_DATA(COMP_RSNA, DBG_LOUD, "Multicase Per-station key : ", pDefKey->DefKeyBuf[keyidx], 16); RT_TRACE(COMP_RSNA , DBG_LOUD , (" KEY Valid : %x \n" ,pDefKey->Valid )); micOK = SecDecodeAESCCM( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)pDefKey->DefKeyBuf[keyidx], pRfd->Buffer.VirtualAddress, IVOffset, pRfd->PacketLength ); //micOK = TRUE; } else { PPER_STA_MPAKEY_ENTRY pMAPkey; // Add by CCW //unicast packet //Find out MAPPING Key Entry. pMAPkey = pSec->MAPKEYTable; for( index = 0 ; index < MAX_NUM_PER_STA_KEY; index++, pMAPkey++) { if( pMAPkey->Valid && (PlatformCompareMemory(pMAPkey->MACAdrss , pTA, 6)==0)) break; } if(index != MAX_NUM_PER_STA_KEY) { RT_PRINT_DATA(COMP_RSNA, DBG_LOUD, "Unicase Key-Mapping key : ", pMAPkey->MapKeyBuf, 16); micOK = SecDecodeAESCCM( &Adapter->MgntInfo.SecurityInfo, (u4Byte *)pMAPkey->MapKeyBuf, pRfd->Buffer.VirtualAddress, IVOffset, pRfd->PacketLength ); } else { // no key found! RT_PRINT_ADDR(COMP_RSNA, DBG_WARNING, ("SecSWAESDecryption(): No pairwise key found for pTA: \n"), pTA); return FALSE; } } RT_TRACE(COMP_RSNA, DBG_LOUD, (" micOK : %x\n", micOK)); } return micOK?TRUE:FALSE; } BOOLEAN SecSWTKIPDecryption( PADAPTER Adapter, PRT_RFD pRfd ) { u1Byte keyidx; u1Byte SrcAddr[6]; PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; u2Byte u2IV16 = (u2Byte)((pSec->TxIV-1)& UINT64_C(0x000000000000ffff)); u4Byte u4IV32 = (u4Byte)((((pSec->TxIV-1)& UINT64_C(0x0000ffffffff0000)) >> 16)& UINT64_C(0x00000000ffffffff)); u1Byte key[16]; pu1Byte data; u4Byte datalen; PMGNT_INFO pMgntInfo=&Adapter->MgntInfo; PRT_WLAN_STA pEntry = NULL;// = AsocEntry_GetEntry(pMgntInfo, pTcb->DestinationAddress); u1Byte IVOffset; // Added by Annie, 2005-12-23. u1Byte IVKeyIdOffset; pu1Byte pHeader = pRfd->Buffer.VirtualAddress; // Get offset. Annie, 2005-12-23. if( pRfd->Status.bIsQosData ) { IVOffset = sMacHdrLng + sQoSCtlLng; } else { IVOffset = sMacHdrLng; } if(pRfd->Status.bContainHTC) IVOffset += sHTCLng; IVKeyIdOffset = IVOffset + KEYID_POS_IN_IV; // Get Key Index. keyidx = SecGetRxKeyIdx(Adapter, pHeader+4, ((pHeader[IVKeyIdOffset]>>6)&0x03) ); PlatformMoveMemory(SrcAddr, pHeader+10, ETHERNET_ADDRESS_LENGTH); if(ACTING_AS_AP(Adapter)) { if(MacAddr_isMulticast(SrcAddr)) { // [AnnieNote] Current GTK is 12345678...12345678, so it's OK. // It's better to modify it by GTK length if we use PRF-X to generate GTK later. 2005-12-23. // //Check if set GTK was completed if(Adapter->MgntInfo.globalKeyInfo.GTK[0] == 0) { //RT_TRACE( COMP_AP, DBG_LOUD, ("SecSWTKIPDecryption(): GTK[0] == 0\n") ); return FALSE; } } else { //Check if STA within associated lsit table pEntry = AsocEntry_GetEntry(pMgntInfo, SrcAddr); if(pEntry == NULL) return FALSE; //Check if set PTK was completed if(pEntry->perSTAKeyInfo.TempEncKey == NULL) return FALSE; } } else if(pRfd->bTDLPacket) { //Check if STA within associated lsit table pEntry = AsocEntry_GetEntry(pMgntInfo, SrcAddr); if(pEntry == NULL) return FALSE; //Check if set PTK was completed if(pEntry->perSTAKeyInfo.TempEncKey == NULL) return FALSE; } // Get u2IV16 and u4IV32. u2IV16 = ((u2Byte)(*(pHeader+IVOffset + 0)) << 8)+ \ ((u2Byte)(*(pHeader+IVOffset + 2)) << 0); u4IV32 = ((u4Byte) (*(pHeader+IVOffset + 4)) << 0)+ \ ((u4Byte) (*(pHeader+IVOffset + 5)) << 8)+ \ ((u4Byte) (*(pHeader+IVOffset + 6)) << 16)+ \ ((u4Byte) (*(pHeader+IVOffset + 7)) << 24); #if 1 //Added by Jay 0712 for security IV if( ACTING_AS_AP(Adapter) ) // Added by Annie. We should not enter here when STA mode. 2005-07-21. { u8Byte tempIV = 0; tempIV |= ((u8Byte)u4IV32) << 16; tempIV |= (u8Byte)u2IV16; // Prefast warning C6011: Dereferencing NULL pointer 'pEntry' if(pEntry != NULL && (tempIV - pEntry->perSTAKeyInfo.RxIV) >= 1000000) { //RT_TRACE(COMP_SEC, DBG_LOUD, ("Error: tempIV = 0x%16"i64fmt"x\n", tempIV)); //RT_TRACE(COMP_SEC, DBG_LOUD, ("Error: pEntry->perSTAKeyInfo.RxIV = 0x%16"i64fmt"x\n", pEntry->perSTAKeyInfo.RxIV)); //Process IV Error... } else { // Prefast warning C6011: Dereferencing NULL pointer 'pEntry'. if (pEntry != NULL) { if (tempIV - pEntry->perSTAKeyInfo.RxIV != 1) { //RT_TRACE(COMP_SEC, DBG_LOUD, ("minor issue: tempIV = 0x%16"i64fmt"x\n", tempIV)); //RT_TRACE(COMP_SEC, DBG_LOUD, ("minor issue: pEntry->perSTAKeyInfo.RxIV = 0x%16"i64fmt"x\n", pEntry->perSTAKeyInfo.RxIV)); } pEntry->perSTAKeyInfo.RxIV = tempIV; pEntry->perSTAKeyInfo.RxIV &= UINT64_C(0x0000ffffffffffff); } } } else if(pRfd->bTDLPacket) { u8Byte tempIV = 0; tempIV |= ((u8Byte)u4IV32) << 16; tempIV |= (u8Byte)u2IV16; // Prefast warning C6011: Dereferencing NULL pointer 'pEntry'. if (pEntry != NULL) { if (tempIV - pEntry->perSTAKeyInfo.RxIV >= 1000000) { //RT_TRACE(COMP_SEC, DBG_LOUD, ("Error: tempIV = 0x%16"i64fmt"x\n", tempIV)); //RT_TRACE(COMP_SEC, DBG_LOUD, ("Error: pEntry->perSTAKeyInfo.RxIV = 0x%16"i64fmt"x\n", pEntry->perSTAKeyInfo.RxIV)); //Process IV Error... } else { if (tempIV - pEntry->perSTAKeyInfo.RxIV != 1) { //RT_TRACE(COMP_SEC, DBG_LOUD, ("minor issue: tempIV = 0x%16"i64fmt"x\n", tempIV)); //RT_TRACE(COMP_SEC, DBG_LOUD, ("minor issue: pEntry->perSTAKeyInfo.RxIV = 0x%16"i64fmt"x\n", pEntry->perSTAKeyInfo.RxIV)); } pEntry->perSTAKeyInfo.RxIV = tempIV; pEntry->perSTAKeyInfo.RxIV &= UINT64_C(0x0000ffffffffffff); } } } #endif if(ACTING_AS_AP(Adapter)) { // AP Mode. if(MacAddr_isMulticast(SrcAddr)) { TKIPGenerateKey(key, u4IV32, u2IV16, SrcAddr, &Adapter->MgntInfo.globalKeyInfo.GTK[0]); } else { if(pEntry != NULL) TKIPGenerateKey(key, u4IV32, u2IV16, SrcAddr, pEntry->perSTAKeyInfo.TempEncKey); } } else if(pRfd->bTDLPacket) { // Prefast warning C6011: Dereferencing NULL pointer 'pEntry' if(pEntry != NULL) TKIPGenerateKey(key, u4IV32, u2IV16, SrcAddr, pEntry->perSTAKeyInfo.TempEncKey); } else { // STA Mode. TKIPGenerateKey(key,u4IV32,u2IV16,SrcAddr,pSec->KeyBuf[keyidx]); } data = pHeader + IVOffset + pSec->EncryptionHeadOverhead; datalen = pRfd->PacketLength - (IVOffset + pSec->EncryptionHeadOverhead); //PRINT_DATA((const void*)"Decode: Cichpertext==>", data, datalen); if(!DecodeWEP(key,16,data,datalen,data)) { // PRINT_DATA((const void*)"Decode: plaintext==>", data, datalen); RT_TRACE(COMP_SEC, DBG_LOUD,("Rx:TKIP Error\n")); if( ACTING_AS_AP(Adapter) ) { if (pEntry != NULL) { pEntry->perSTAKeyInfo.WEPErrorCnt++; RT_TRACE(COMP_AUTHENTICATOR, DBG_LOUD, ("Rx:TKIP Error: %d\n", pEntry->perSTAKeyInfo.WEPErrorCnt)); } } else if(pRfd->bTDLPacket) { if (pEntry != NULL) { pEntry->perSTAKeyInfo.WEPErrorCnt++; RT_TRACE(COMP_AUTHENTICATOR, DBG_LOUD, ("Rx:TKIP Error: %d\n", pEntry->perSTAKeyInfo.WEPErrorCnt)); } } return FALSE; } RT_TRACE(COMP_SEC, DBG_LOUD,("Rx:TKIP OK\n")); return TRUE; } BOOLEAN SecSWWEPDecryption( PADAPTER Adapter, PRT_RFD pRfd ) { PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; u1Byte keyidx; u1Byte key[16]; s4Byte keysize; pu1Byte data; u4Byte datalen; u1Byte IVOffset; // Added by Annie, 2005-12-23. pu1Byte pHeader = pRfd->Buffer.VirtualAddress; //Fix SW WEP descryption multicase fail. 2009,12,08 u2Byte EncryptionMPDUHeadOverhead, EncryptionMPDUTailOverhead; u2Byte EncryptionMSDUHeadOverhead, EncryptionMSDUTailOverhead; pu1Byte DestAddr; OCTET_STRING Mpdu; BOOLEAN bMulticastDest; RT_ENC_ALG TempALg; FillOctetString(Mpdu, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); DestAddr = Frame_pDaddr(Mpdu); bMulticastDest = MacAddr_isMulticast(DestAddr); if( pSec->SecLvl == RT_SEC_LVL_NONE ) bMulticastDest = FALSE; SecGetEncryptionOverhead( Adapter, &EncryptionMPDUHeadOverhead, &EncryptionMPDUTailOverhead, &EncryptionMSDUHeadOverhead, &EncryptionMSDUTailOverhead, TRUE, bMulticastDest ); if( !bMulticastDest ) TempALg = pSec->PairwiseEncAlgorithm; else TempALg = pSec->GroupEncAlgorithm; // Get offset. Annie, 2005-12-23. if( pRfd->Status.bIsQosData ) { IVOffset = sMacHdrLng + sQoSCtlLng; } else { IVOffset = sMacHdrLng; } if(pRfd->Status.bContainHTC) IVOffset += sHTCLng; // Get IV. (Because 802.11 and key both are little endian) PlatformMoveMemory(key, pHeader+IVOffset , 3); // Prepare Key. keyidx = GET_WEP_IV_KEYID(pHeader+IVOffset); keysize = (TempALg==RT_ENC_ALG_WEP104) ? 16 : 8; PlatformMoveMemory(key+3, pSec->KeyBuf[keyidx], keysize-3); // Set up input data. data = pHeader + IVOffset + 4;//pSec->EncryptionHeadOverhead; datalen = pRfd->PacketLength - (IVOffset +4);// pSec->EncryptionHeadOverhead); //RT_PRINT_DATA( COMP_SEC, DBG_LOUD, "Decode: Ciphertext==>", data, datalen); if( !DecodeWEP( key, keysize, data, datalen, data ) ) { RT_TRACE( COMP_SEC, DBG_LOUD, ("SecSWWEPDecryption(): WEP software decrypted Fail!!! (datalen=%d)\n", datalen) ); RT_PRINT_DATA( COMP_SEC, DBG_TRACE, "WEP decoded packet", data, datalen ); return FALSE; } return TRUE; } // // Software decryption for CKIP. // Ported from CKIP code, Annie, 2006-08-11. [AnnieTODO] // BOOLEAN SecSWCKIPDecryption( PADAPTER Adapter, PRT_RFD pRfd ) { pu1Byte pHeader = pRfd->Buffer.VirtualAddress; u1Byte keyidx; u1Byte IVOffset; int DEcok = 0; PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; // Get offset. Annie, 2005-12-23. if( pRfd->Status.bIsQosData ) { IVOffset = sMacHdrLng + sQoSCtlLng; } else { IVOffset = sMacHdrLng; } if(pRfd->Status.bContainHTC) IVOffset += sHTCLng; //Get IV keyidx= GET_WEP_IV_KEYID( pHeader+IVOffset); DEcok = DecodeCKIP( Adapter , (UCHAR *)pHeader , pRfd->PacketLength , pSec->pCkipPara->CKIPKeyBuf[keyidx] , keyidx ); RT_TRACE( COMP_CKIP, DBG_LOUD, ("SecSWCKIPDecryption(): DEcok=0x%X\n", DEcok) ); return ( (DEcok==1)? TRUE : FALSE ); } // // Desription: // Used for deny link to MIC failure AP in 60 seconds. // 2004.10.06, by rcnjo. // BOOLEAN SecInsertDenyBssidList ( PRT_SECURITY_T pSec, u1Byte BssidToDeny[6], u8Byte DenyStartTime ) { PRT_DENY_BSSID pBssidToDeny = NULL; u8Byte EarlyestStartTime = PlatformGetCurrentTime(); int EarlyestIdx = 0; int i; for(i = 0; i < MAX_DENY_BSSID_LIST_CNT; i++) { if(pSec->DenyBssidList[i].bUsed) { if(pSec->DenyBssidList[i].StartTime < EarlyestStartTime) { EarlyestStartTime = pSec->DenyBssidList[i].StartTime; EarlyestIdx = i; } } else { pBssidToDeny = pSec->DenyBssidList + i; break; } } if(pBssidToDeny == NULL) { // Use the oldest one. pBssidToDeny = pSec->DenyBssidList + EarlyestIdx; } PlatformMoveMemory(pBssidToDeny->Bssid, BssidToDeny, 6); pBssidToDeny->StartTime = DenyStartTime; pBssidToDeny->bUsed = TRUE; return TRUE; } // // Desription: // Used for deny link to MIC failure AP in 60 seconds. // 2004.10.06, by rcnjo. // BOOLEAN SecIsInDenyBssidList ( PRT_SECURITY_T pSec, u1Byte BssidToCheck[6] ) { BOOLEAN bToDeny = FALSE; PRT_DENY_BSSID pBssidToDeny; u8Byte CurrTime = PlatformGetCurrentTime(); int i; for(i = 0; i < MAX_DENY_BSSID_LIST_CNT; i++) { pBssidToDeny = pSec->DenyBssidList + i; if(pBssidToDeny->bUsed) { // Check StartTime. if((CurrTime - pBssidToDeny->StartTime) < MIC_CHECK_TIME) // Diff < 60 seconds. { // Check BSSID. if( PlatformCompareMemory(pBssidToDeny->Bssid, BssidToCheck, 6) == 0 ) { // The same BSSID. bToDeny = TRUE; break; } } else { // Clear the entry if it is overdue. pBssidToDeny->bUsed = FALSE; continue; } } } return bToDeny; } // // Desription: // Fill up WEP bit and IV of each fragment in the TCB if necessary. // Output: // 1. Return TRUE if this packet has to be encrypted. // 2. Set up pTcb->EncInfo. // 2005.06.27, by rcnjo. // BOOLEAN SecFillHeader( PADAPTER Adapter, PRT_TCB pTcb) { PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); PRT_SECURITY_T pSecInfo = &(pMgntInfo->SecurityInfo); int i; int FragIndex = 0; int FragBufferIndex = 0; BOOLEAN bEncrypt; PSTA_ENC_INFO_T pEncInfo = &pTcb->EncInfo; bEncrypt = MgntGetEncryptionInfo( Adapter, pTcb, pEncInfo,TRUE); if(WAPI_QuerySetVariable(Adapter, WAPI_QUERY, WAPI_VAR_NOTSETENCMACHEADER, 0)) return FALSE; if(!bEncrypt) { RT_TRACE( COMP_CKIP, DBG_TRACE, ("SecFillHeader(): !bEncrypt => return FALSE!\n")); return FALSE; } for(i = 0;i < pTcb->BufferCount; i++) { // Fill WEP bit, IV. if(FragBufferIndex == 0) { pu1Byte pFrame; pFrame = (pu1Byte)&pTcb->BufferList[i].VirtualAddress[Adapter->TXPacketShiftBytes]; // WEP bit. SET_80211_HDR_WEP(pFrame, 1); // IV. SecHeaderFillIV(Adapter, pFrame); } FragBufferIndex++; if(FragBufferIndex == pTcb->FragBufCount[FragIndex]) { FragIndex++; FragBufferIndex = 0; } } RT_TRACE( COMP_CKIP, DBG_TRACE, ("SecFillHeader(): retrun TRUE\n")); return TRUE; } // // Return: Is the content of pPduOS an EAPOL frame or not. (88-8e) // Added by Annie, 2005-12-25. // BOOLEAN SecIsEAPOLPacket( IN PADAPTER Adapter, IN POCTET_STRING pPduOS ) { BOOLEAN IsEAPOLPkt = FALSE; u1Byte Offset_TypeEAPOL = sMacHdrLng + LLC_HEADER_SIZE; // 30 if( IsQoSDataFrame(pPduOS->Octet) ) { Offset_TypeEAPOL += sQoSCtlLng; // +2 } if( Frame_WEP(*pPduOS)) { Offset_TypeEAPOL += Adapter->MgntInfo.SecurityInfo.EncryptionHeadOverhead; // 4 or 8 } // Length Check if( pPduOS->Length < (Offset_TypeEAPOL+1) ) { RT_TRACE( COMP_SEC, DBG_TRACE, ("SecIsEAPOLPacket(): invalid length(%d)\n", pPduOS->Length ) ); return FALSE; } // 888e? if( (pPduOS->Octet[Offset_TypeEAPOL]==0x88) && (pPduOS->Octet[Offset_TypeEAPOL+1]==0x8e) ) { IsEAPOLPkt = TRUE; } //RT_TRACE( COMP_SEC, DBG_LOUD, ("SecIsEAPOLPacket(): Recvd EAPOL frame. IsEAPOLPkt(%d)\n", IsEAPOLPkt )); return IsEAPOLPkt; } // // Return: Is the content of pPduOS an EAPOL frame or not. (88-8e) // Added by Annie, 2005-12-25. // BOOLEAN SecIsEAPOLKEYPacket( IN PADAPTER Adapter, IN POCTET_STRING pPduOS ) { BOOLEAN IsEAPOLKeyPkt = FALSE; u1Byte Offset_TypeEAPOL = sMacHdrLng + LLC_HEADER_SIZE; // 30 if( IsQoSDataFrame(pPduOS->Octet) ) { Offset_TypeEAPOL += sQoSCtlLng; // +2 } if( Frame_WEP(*pPduOS)) { Offset_TypeEAPOL += Adapter->MgntInfo.SecurityInfo.EncryptionHeadOverhead; // 4 or 8 } // Length Check if( pPduOS->Length < (Offset_TypeEAPOL+1) ) { RT_TRACE( COMP_SEC, DBG_TRACE, ("SecIsEAPOLKEYPacket(): invalid length(%d)\n", pPduOS->Length ) ); return FALSE; } // 888e && Type is Key if( (pPduOS->Octet[Offset_TypeEAPOL]==0x88) && (pPduOS->Octet[Offset_TypeEAPOL+1]==0x8e) && (pPduOS->Octet[Offset_TypeEAPOL+3]==0x03) ) { IsEAPOLKeyPkt = TRUE; } RT_TRACE( COMP_SEC, DBG_TRACE, ("SecIsEAPOLKEYPacket(): Recvd EAPOL frame. IsEAPOLPkt(%d)\n", IsEAPOLKeyPkt )); //Here is for Verify 2008/03/20 //RT_TRACE( COMP_SEC, DBG_LOUD, ("==m==>SecIsEAPOLKEYPacket(): Recvd EAPOL frame. IsEAPOLPkt(%d)<==m==\n", IsEAPOLKeyPkt )); return IsEAPOLKeyPkt; } // // Ported from 8185: WMacSetPMKID(). // Added by Annie, 2006-05-07. // VOID SecSetPMKID( IN PADAPTER Adapter, IN PN5_802_11_PMKID pPMKid ) { PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); PRT_SECURITY_T pSecInfo = &(pMgntInfo->SecurityInfo); PN5_BSSID_INFO pBssidInfo = (PN5_BSSID_INFO)(pPMKid->BSSIDInfo); u4Byte ulIndex, i, j; BOOLEAN blInserted = FALSE; u1Byte NullMacadress[6] = {0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 }; RT_TRACE( COMP_SEC, DBG_LOUD, ("SecSetPMKID(): Number Of PMKID on list = %d\n", pPMKid->BSSIDInfoCount) ); // // Clear all entry , when PMK-count = 1 and MAC address all zero !! // if( (pPMKid->BSSIDInfoCount == 1 )&& (PlatformCompareMemory(pBssidInfo->BSSID , NullMacadress , 6 )==0)) { for( ulIndex=0; ulIndex<NUM_PMKID_CACHE; ulIndex++ ) { // Clear all PMK cash !! pSecInfo->PMKIDList[ulIndex].bUsed = FALSE; PlatformZeroMemory(pSecInfo->PMKIDList[ulIndex].Bssid, sizeof(pSecInfo->PMKIDList[ulIndex].Bssid)); pSecInfo->PMKIDList[ulIndex].Ssid.Length = 0; } return; } // // Clear the entry with different SSID from the AP we are associating with. // for( ulIndex=0; ulIndex<NUM_PMKID_CACHE; ulIndex++ ) { if( !eqNByte(pMgntInfo->Ssid.Octet, pSecInfo->PMKIDList[ulIndex].SsidBuf, pMgntInfo->Ssid.Length) || (pMgntInfo->Ssid.Length != pSecInfo->PMKIDList[ulIndex].Ssid.Length) ) { // SSID is not matched => Clear the entry! pSecInfo->PMKIDList[ulIndex].bUsed = FALSE; PlatformZeroMemory(pSecInfo->PMKIDList[ulIndex].Bssid, sizeof(pSecInfo->PMKIDList[ulIndex].Bssid)); pSecInfo->PMKIDList[ulIndex].Ssid.Length = 0; } } // // Insert or cover with new PMKID. // for( i=0; i<pPMKid->BSSIDInfoCount; i++ ) { if( i >= NUM_PMKID_CACHE ) { RT_TRACE( COMP_SEC, DBG_WARNING, ("SecSetPMKID(): BSSIDInfoCount is more than NUM_PMKID_CACHE!%d\n", pPMKid->BSSIDInfoCount) ); break; } blInserted = FALSE; for(j=0 ; j<NUM_PMKID_CACHE; j++) { if( pSecInfo->PMKIDList[j].bUsed && eqMacAddr(pSecInfo->PMKIDList[j].Bssid, pBssidInfo->BSSID) ) { // BSSID is matched, the same AP => rewrite with new PMKID. CopyMem(pSecInfo->PMKIDList[j].PMKID, pBssidInfo->PMKID, sizeof(pBssidInfo->PMKID)); blInserted = TRUE; break; } } if(blInserted) { pBssidInfo ++; // pointer to next BSSID_INFO. continue; } else { // Find a new entry for( j=0 ; j<NUM_PMKID_CACHE; j++ ) { if(pSecInfo->PMKIDList[j].bUsed == FALSE) { pSecInfo->PMKIDList[j].bUsed = TRUE; CopyMem(pSecInfo->PMKIDList[j].Bssid, pBssidInfo->BSSID, 6); CopyMem(pSecInfo->PMKIDList[j].PMKID, pBssidInfo->PMKID, PMKID_LEN); CopySsid(pSecInfo->PMKIDList[j].SsidBuf, pSecInfo->PMKIDList[j].Ssid.Length, pMgntInfo->SsidBuf, pMgntInfo->Ssid.Length); break; } } } pBssidInfo ++; // pointer to next BSSID_INFO. } // // For debug purpose: Check current PMKID list. // for( ulIndex=0; ulIndex<NUM_PMKID_CACHE ; ulIndex++ ) { if(pSecInfo->PMKIDList[ulIndex].bUsed) { RT_TRACE( COMP_SEC, DBG_LOUD, ("------------------------------------------\n") ); RT_TRACE( COMP_SEC, DBG_LOUD, ("[PMKID %d]\n", ulIndex ) ); RT_TRACE( COMP_SEC, DBG_LOUD, ("------------------------------------------\n") ); RT_TRACE( COMP_SEC, DBG_LOUD, ("SecSetPMKID(): PMKIDList[%d].bUsed is TRUE\n", ulIndex) ); RT_PRINT_STR( COMP_SEC, DBG_LOUD, "SSID", pSecInfo->PMKIDList[ulIndex].Ssid.Octet, pSecInfo->PMKIDList[ulIndex].Ssid.Length); RT_PRINT_DATA( COMP_SEC, DBG_LOUD, "BSSID", pSecInfo->PMKIDList[ulIndex].Bssid, 6); RT_PRINT_DATA( COMP_SEC, DBG_LOUD, "PMKID", pSecInfo->PMKIDList[ulIndex].PMKID, sizeof(pBssidInfo->PMKID)); } } } // // Ported from 8185: IsInPreAuthKeyList(). (Renamed from SecIsInPreAuthKeyList(), 2006-10-13.) // Added by Annie, 2006-05-07. // // Search by BSSID, // Return Value: // -1 :if there is no pre-auth key in the table // >=0 :if there is pre-auth key, and return the entry id // int SecIsInPMKIDList( IN PADAPTER Adapter, IN pu1Byte bssid ) { PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); PRT_SECURITY_T pSecInfo = &(pMgntInfo->SecurityInfo); int i; for( i=0; i<NUM_PMKID_CACHE; i++ ) { if( pSecInfo->PMKIDList[i].bUsed && eqMacAddr(pSecInfo->PMKIDList[i].Bssid, bssid) ) { break; } else { continue; } } if( i == NUM_PMKID_CACHE ) { // Could not find. i = -1; } else { // There is one Pre-Authentication Key for the specific BSSID. } RT_TRACE( COMP_SEC, DBG_LOUD, ("SecIsInPMKIDList(): i=%d\n", i) ); return i; } // // Ported from 8185: WMacCatPMKID(). // Added by Annie, 2006-05-07. // VOID SecCatPMKID( IN PADAPTER Adapter, IN pu1Byte CurAPbssid, IN PRT_WLAN_BSS pBssDesc ) { PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); PRT_SECURITY_T pSecInfo = &(pMgntInfo->SecurityInfo); pu1Byte pIECurrent = NULL; int iEntry = 0; BOOLEAN bCCX8021xenable = FALSE; BOOLEAN bAPSuportCCKM = FALSE; u1Byte BIPOui[4] = {0x00, 0x0f , 0xac , 0x06}; // Note: PMKID can only be included in (Re)Association. if( ACTING_AS_AP(Adapter) || pMgntInfo->mIbss ) { return; } // Note: PMKID fileds are defined in WPA2. if( pSecInfo->SecLvl < RT_SEC_LVL_WPA2 ) return; if(WAPI_QuerySetVariable(Adapter, WAPI_QUERY, WAPI_VAR_WAPISUPPORT, 0) && pSecInfo->SecLvl == RT_SEC_LVL_WAPI) return; // // CCKM mode return. // Note: // Putting PMKID and CCKM together in the reassociation request must confuse the AP and // make it no response after reassociation request packet. // CCX_QueryCCKMSupport(Adapter, &bCCX8021xenable, &bAPSuportCCKM); if( bCCX8021xenable && bAPSuportCCKM) { return; } // // 1. Search PMKID list (pSecInfo->PMKIDList[i]) by BSSID. // iEntry = SecIsInPMKIDList( Adapter, CurAPbssid ); if( iEntry < 0 ) { RT_TRACE( COMP_SEC, DBG_LOUD, ("SecCatPMKID(): AP is not in current PMKID List => do nothing.\n") ); // Check Need to add MFP IE or not !! if( pBssDesc->bMFPC && pMgntInfo->bInBIPMFPMode) { pIECurrent = pSecInfo->RSNIE.Octet + pSecInfo->RSNIE.Length - 2; // Point to RSN Capablite SET_RSN_CAP_MFP_CAPABLE(pIECurrent , 1 ); if( pBssDesc->bMFPR ) { // Removed by Bruce, 2014-12-08. // From MSDN: // Management Frame Protection Required (MFPR) enforcement on Windows 8 is not supported. Hence miniport drivers should never set // this bit in the RSN capabilities of RSN IE during an association request. For policy, the access point may advertise MFPR which will // allow MFP-capable STA to associate. Access points not supporting MFP capability will fail association. If MFPR is set by an access point // and STA is not MFP capable, Windows 8 will treat the network as mismatched in capability and not send an association request to the // miniport. http://msdn.microsoft.com/en-us/library/windows/hardware/ff547688(v=vs.85).aspx // // SET_RSN_IE_CAP_MFP_REQUIRED(pIECurrent, 1); } pIECurrent += 2; if( pBssDesc->bMFPBIP ) { // Add PMKID counter = 0x00 0x00 PlatformZeroMemory( pIECurrent , 2 ); pIECurrent += 2; // Add BIP oui PlatformMoveMemory( pIECurrent ,BIPOui , 4 ); pSecInfo->RSNIE.Length += 6; } } return; } // // 2. Cat PMKID to RSNIE. // pIECurrent = pSecInfo->RSNIE.Octet + pSecInfo->RSNIE.Length; ((PDOT11_RSN_IE_PMKID)pIECurrent)->SuiteCount = NUM_CAT_PMKID; // NUM_CAT_PMKID=1 CopyMem( ((PDOT11_RSN_IE_PMKID)pIECurrent)->PMKList, pSecInfo->PMKIDList[iEntry].PMKID, sizeof(pSecInfo->PMKIDList[iEntry].PMKID) ); pSecInfo->RSNIE.Length += ( sizeof( ((PDOT11_RSN_IE_PMKID)pIECurrent)->SuiteCount ) + // 2 bytes for PMKID count. PMKID_LEN*NUM_CAT_PMKID ); // 16*s bytes for PMKID List. // // Note : 802.11w sample RSN PMK and BIP support at same time !! // // Check Need to add MFP IE or not !! if( pBssDesc->bMFPC && pMgntInfo->bInBIPMFPMode ) { pIECurrent = pIECurrent - 2; // Point to RSN Capablite SET_RSN_IE_CAP_MFP_CAPABLE(pIECurrent , 1 ); if( pBssDesc->bMFPR ) { SET_RSN_CAP_MFP_REQUIRED(pIECurrent, 1); } pIECurrent = pSecInfo->RSNIE.Octet + pSecInfo->RSNIE.Length; if( pBssDesc->bMFPBIP ) { // Add BIP oui PlatformMoveMemory( pIECurrent ,BIPOui , 4 ); pSecInfo->RSNIE.Length += 4; } } RT_PRINT_DATA( COMP_SEC, DBG_LOUD, "SecCatPMKID(): New RSNIE", pSecInfo->RSNIE.Octet, pSecInfo->RSNIE.Length ); } // // If there is no key when security enabled, drop data frames. // Added by Annie, 2006-08-15. // BOOLEAN SecDropForKeyAbsent( PADAPTER Adapter, PRT_TCB pTcb ) { PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); PRT_SECURITY_T pSecInfo = &(pMgntInfo->SecurityInfo); BOOLEAN bDrop = FALSE; pu1Byte pRa = NULL; BOOLEAN bFindMatchPeer = FALSE; RT_TRACE( COMP_SEC, DBG_TRACE, ("==> SecDropForKeyAbsent()\n") ); GetTcbDestaddr(Adapter, pTcb, &pRa); //<TODO: How about in AP mode> if(ACTING_AS_AP(Adapter)) { return bDrop; } if ( pSecInfo->SecLvl == RT_SEC_LVL_WAPI) { if(RT_STATUS_SUCCESS == WAPI_SecFuncHandler(WAPI_DROPFORSECKEYABSENT,Adapter, (PVOID)pRa, WAPI_END)) bDrop = TRUE; } else { if(pMgntInfo->SafeModeEnabled || pMgntInfo->mIbss) { return bDrop; } if( pTcb->EncInfo.SecProtInfo == RT_SEC_NORMAL_DATA ) { // Data frame, not EAPOL packet. if(RT_STATUS_SUCCESS == WAPI_SecFuncHandler(WAPI_DROPFORSECKEYABSENT,Adapter, (PVOID)pRa, WAPI_END)) bDrop = TRUE; if( pSecInfo->SecLvl > RT_SEC_LVL_NONE ) { // WPA or WPA2. if( MacAddr_isMulticast(pRa) ) { // Need group key. if(pSecInfo->KeyLen[pSecInfo->GroupTransmitKeyIdx]==0) { bDrop = TRUE; RT_TRACE( COMP_SEC, DBG_LOUD, ("SecDropForKeyAbsent(): Tx Data Without Group Key %d\n", pSecInfo->GroupTransmitKeyIdx ) ); } } else { // Need pairwise key. if(pSecInfo->KeyLen[PAIRWISE_KEYIDX]==0) { bDrop = TRUE; RT_TRACE( COMP_SEC, DBG_LOUD, ("SecDropForKeyAbsent(): Tx Data Without Pairwise Key!\n") ); } } } else { // Check WEP if( pSecInfo->EncryptionStatus==RT802_11Encryption1Enabled ) // Is this OK?? Annie, 2006-05-04. { if(pSecInfo->KeyLen[pSecInfo->DefaultTransmitKeyIdx]==0) { bDrop = TRUE; RT_TRACE( COMP_SEC, DBG_LOUD, ("SecDropForKeyAbsent(): Tx Data Without WEP Key %d\n", pSecInfo->DefaultTransmitKeyIdx ) ); } } } } } if(bDrop) { RT_TRACE( COMP_SEC, DBG_WARNING, ("SecDropForKeyAbsent(): Not to send data frame since there is no key!\n") ); RT_PRINT_DATA(COMP_SEC, DBG_TRACE, "Discarded Packet", pTcb->BufferList[0].VirtualAddress, pTcb->BufferList[0].Length); } RT_TRACE( COMP_SEC, DBG_TRACE, ("<== SecDropForKeyAbsent(), bDrop=%d\n", bDrop) ); return bDrop; } VOID SecSetSwEncryptionDecryption( PADAPTER Adapter, BOOLEAN bSWTxEncrypt, BOOLEAN bSWRxDecrypt ) { PRT_SECURITY_T pSec = &Adapter->MgntInfo.SecurityInfo; // Tx Sw Encryption. if ( (pSec->RegSWTxEncryptFlag == EncryptionDecryptionMechanism_Auto) || (pSec->RegSWTxEncryptFlag >= EncryptionDecryptionMechanism_Undefined) ) { pSec->SWTxEncryptFlag = bSWTxEncrypt; } else if ( pSec->RegSWTxEncryptFlag == EncryptionDecryptionMechanism_Hw ) { pSec->SWTxEncryptFlag = FALSE; } else if ( pSec->RegSWTxEncryptFlag == EncryptionDecryptionMechanism_Sw ) { pSec->SWTxEncryptFlag = TRUE; } // If the encryption mechanism differs between driver determined and registry determined. // Print an warning message. if (pSec->RegSWTxEncryptFlag != bSWTxEncrypt) { RT_TRACE(COMP_SEC, DBG_WARNING, ("SecSetSwEncryptionDecryption(): Warning! User and driver determined encryption mechanism mismatch.\n")); RT_TRACE(COMP_SEC, DBG_WARNING, ("SecSetSwEncryptionDecryption(): RegSWTxEncryptFlag = %d, bSWTxEncrypt = %d\n", pSec->RegSWTxEncryptFlag, bSWTxEncrypt)); } // Rx Sw Decryption. if ( (pSec->RegSWRxDecryptFlag == EncryptionDecryptionMechanism_Auto) || (pSec->RegSWRxDecryptFlag == EncryptionDecryptionMechanism_Undefined) ) { pSec->SWRxDecryptFlag = bSWRxDecrypt; } else if ( pSec->RegSWRxDecryptFlag == EncryptionDecryptionMechanism_Hw ) { pSec->SWRxDecryptFlag = FALSE; } else if ( pSec->RegSWRxDecryptFlag == EncryptionDecryptionMechanism_Sw) { pSec->SWRxDecryptFlag = TRUE; } // If the decryption mechanism differs between driver determined and registry determined. // Print an warning message. if (pSec->RegSWRxDecryptFlag != bSWRxDecrypt) { RT_TRACE(COMP_SEC, DBG_WARNING, ("SecSetSwEncryptionDecryption(): Warning! User and driver determined decryption mechanism mismatch.\n")); RT_TRACE(COMP_SEC, DBG_WARNING, ("SecSetSwEncryptionDecryption(): RegSWRxDecryptFlag = %d, bSWRxDecrypt = %d\n", pSec->RegSWRxDecryptFlag, bSWRxDecrypt)); } } // // Description: // Determine if the specifed key is available for RA // BOOLEAN SecIsTxKeyInstalled( IN PADAPTER pAdapter, IN pu1Byte pRA ) { PMGNT_INFO pMgntInfo = &(pAdapter->MgntInfo); PRT_SECURITY_T pSecInfo = &(pMgntInfo->SecurityInfo); if (ACTING_AS_AP(pAdapter) && MgntActQuery_ApType(pAdapter) == RT_AP_TYPE_LINUX ) {// AP mode if(!MacAddr_isMulticast(pRA)) { PRT_WLAN_STA pEntry; pEntry = AsocEntry_GetEntry(pMgntInfo,pRA); if(pEntry == NULL) return FALSE; else if(pEntry->keyindex != 0) return TRUE; else return FALSE; } else { return FALSE; } } if( !pMgntInfo->bRSNAPSKMode ) { if( pSecInfo->KeyLen[0] == 0 && pSecInfo->KeyLen[1] == 0 && pSecInfo->KeyLen[2] == 0 && pSecInfo->KeyLen[3] == 0 && pSecInfo->KeyLen[4] == 0 && 0 == WAPI_QuerySetVariable(pAdapter, WAPI_QUERY, WAPI_VAR_ISCAMUSED, 0) ) { return FALSE; } else { // Check Pawise Key only !! if(!ACTING_AS_AP(pAdapter) && pSecInfo->SecLvl > RT_SEC_LVL_NONE ) { // // Check Tx key // Note: // This is special case for WPA-2 (RSN). // When the CCX service (supplicant) receives the ANoce packet in the 1st packet of 4-way, // the supplicant set the Group Key to driver and thus the driver then sends the SNonce packet "encrypted" // to AP by an empty PTK just because the driver determine that the Keys has been installed // from the procedure SecIsTxKeyInstalled(). // We find this behavior of CCX service in the CCX SDK version 1.1.13. // Advised from CCW, and edited by Bruce, 2009-09-04. // if( pSecInfo->KeyLen[0] == 0 && 0 == WAPI_QuerySetVariable(pAdapter, WAPI_QUERY, WAPI_VAR_ISCAMUSED, 0) ) { RT_TRACE(COMP_SEC, DBG_LOUD, ("SecIsTxKeyInstalled(): pSecInfo->KeyLen[0] == 0, Tx Key is not installed!\n")); return FALSE; } } return TRUE; } } else { // RSNA IBSS mode. u4Byte index; if(!MacAddr_isMulticast(pRA)) { PPER_STA_MPAKEY_ENTRY pMapKey; for( index = 0 ; index < MAX_NUM_PER_STA_KEY ; index++) { pMapKey = &(pSecInfo->MAPKEYTable[index]); if( pMapKey->Valid && eqMacAddr(pMapKey->MACAdrss , pRA) ) { return TRUE; } } return FALSE; } else { PPER_STA_DEFAULT_KEY_ENTRY pDefKey; // // TODO: remvoe our group key from PerStaDefKeyTable[] // for( index = 0 ; index < MAX_NUM_PER_STA_KEY ; index++) { pDefKey = &(pSecInfo->PerStaDefKeyTable[index]); if( pDefKey->Valid && eqMacAddr(pDefKey->MACAdrss, pAdapter->CurrentAddress) ) { return TRUE; } } return FALSE; } } } // // Description: // Descrypt the mgnt frame by SW and check if this packet is valid. // Arguments: // [in] Adapter - // The NIC context. // [in] pRfd - // The Rx buffer and information. // Return: // RT_SEC_STATUS_SUCCESS if this packet is descrypted successfully, and otherwise if any error(this packet should be dropped). // Assumption: // Before calling this function, be sure these conditions are correct, // (1) This packet is mgnt frame. // (2) MFP is enabled. // By Bruce, 2009-10-08. // RT_SEC_STATUS SecSWMFPDecryption( IN PADAPTER pAdapter, IN PRT_RFD pRfd ) { PMGNT_INFO pMgntInfo = &(pAdapter->MgntInfo); PRT_SECURITY_T pSec = &(pMgntInfo->SecurityInfo); RT_SEC_STATUS secStatus = RT_SEC_STATUS_SUCCESS; if(RT_SEC_STATUS_SUCCESS != (secStatus = SecSoftwareDecryption(pAdapter, pRfd))) { switch(pSec->PairwiseEncAlgorithm) { case RT_ENC_ALG_TKIP: CountRxMgntTKIPDecryptErrorsStatistics(pAdapter, pRfd); break; case RT_ENC_ALG_AESCCMP: CountRxMgntCCMPDecryptErrorsStatistics(pAdapter, pRfd); break; default: //for MacOSX Compiler warning. break; } RT_TRACE(COMP_SEC , DBG_WARNING , ("SecSWMFPDecryption(): Fail (0x%08X) MFP packe decrypt !!\n", secStatus) ); return secStatus; } else if( pMgntInfo->bInBIPMFPMode) { // 802.11 MFP OCTET_STRING frame; FillOctetString(frame, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); // Remove IV, but we haven't remove MIC if(frame.Length > (sMacHdrLng + pMgntInfo->SecurityInfo.EncryptionHeadOverhead)) { PlatformMoveMemory((frame.Octet+ sMacHdrLng), (frame.Octet + sMacHdrLng + pMgntInfo->SecurityInfo.EncryptionHeadOverhead), (frame.Length - (sMacHdrLng + pMgntInfo->SecurityInfo.EncryptionHeadOverhead))); // Clear the WEP bit because we have removed the IV field. SET_80211_HDR_WEP(pRfd->Buffer.VirtualAddress, 0); } else { RT_TRACE(COMP_SEC , DBG_WARNING , ("SecSWMFPDecryption(): Check Packet Length failed!!\n") ); return RT_SEC_STATUS_INVALID_PKT_LEN; } } else { OCTET_STRING frame; FillOctetString(frame, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); // Check MHDR IE for TKIP... if(pSec->PairwiseEncAlgorithm == RT_ENC_ALG_TKIP) { // Remove the ICV so that we can caculate the MIC. MAKE_RFD_OFFSET_AT_BACK(pRfd, pMgntInfo->SecurityInfo.EncryptionTailOverhead); // Check the length is valid including MHDRIE and MIC if(frame.Length < (sMacHdrLng + pMgntInfo->SecurityInfo.EncryptionHeadOverhead + 2 + CCX_MFP_TKIP_MHDR_IE_LEN + TKIP_MIC_LEN)) // MHDRIE (2 + 12) + MIC (8) return RT_SEC_STATUS_INVALID_PKT_LEN; if(!CCX_VerifyRxMFP_MHDRIE(pAdapter, pRfd)) { RT_PRINT_DATA(COMP_SEC, DBG_WARNING, " Verify MFP MHDRIE Error, content:\n", frame.Octet, frame.Length); CountRxMgntMFPTKIPMHDRStatistics(pAdapter, pRfd); return RT_SEC_STATUS_MFP_MGNT_MHDR_FAILURE; } RT_PRINT_DATA(COMP_CCX, DBG_LOUD, " Content:\n", pRfd->Buffer.VirtualAddress, pRfd->PacketLength); // GET_80211_HDR_MORE_FRAG(frame.Octet) may need to chech more frg bit not set !! if(!SecCheckMIC( pAdapter , pRfd )) { return RT_SEC_STATUS_MGNT_MIC_FAILURE; } } // Remove IV, but we haven't remove MIC and MHDR IE if(frame.Length > (sMacHdrLng + pMgntInfo->SecurityInfo.EncryptionHeadOverhead)) { PlatformMoveMemory((frame.Octet+ sMacHdrLng), (frame.Octet + sMacHdrLng + pMgntInfo->SecurityInfo.EncryptionHeadOverhead), (frame.Length - (sMacHdrLng + pMgntInfo->SecurityInfo.EncryptionHeadOverhead))); // Clear the WEP bit because we have removed the IV field. SET_80211_HDR_WEP(pRfd->Buffer.VirtualAddress, 0); } else { RT_TRACE(COMP_SEC , DBG_WARNING , ("SecSWMFPDecryption(): Check Packet Length failed!!\n") ); return RT_SEC_STATUS_INVALID_PKT_LEN; } } RT_TRACE(COMP_SEC, DBG_LOUD , ("SecSWMFPDecryption(): SW Descryption OK!\n") ); return RT_SEC_STATUS_SUCCESS; } // // Description: // Handle 802.11w BIP MIC . // Arguments: // [in] Adapter - // The NIC context. // [in] pRfd - // The Rx buffer and information. // Return: // RT_SEC_STATUS_SUCCESS if MIC and MMIE are OK , and otherwise if any error(this packet should be dropped and Do nothing !!). // RT_SEC_STATUS SecCheckMMIE( IN PADAPTER pAdapter, IN PRT_RFD pRfd ) { OCTET_STRING frame; PMGNT_INFO pMgntInfo = &pAdapter->MgntInfo; PRT_SECURITY_T pSec = &(pMgntInfo->SecurityInfo); u1Byte Micdata[256] = {0}; u4Byte MACTextLength = 8; u1Byte PlantData[256] = {0}; pu1Byte pCurrent = PlantData; u1Byte PlantDataLen = 0; u1Byte MMIE[2] = { 0x4c , 0x10 }; // ID and Len PMMIE_STRUC pMMIE = NULL; u1Byte index = 0; FillOctetString(frame, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); if( frame.Length > 256 || frame.Length < 18 ) return RT_SEC_STATUS_MFP_MGNT_LEN_FAILURE; if( pSec->BIPKeyBuffer[0] == 0 ) { RT_TRACE( COMP_SEC , DBG_TRACE , ("===> BIP key no install !!\n")); return RT_SEC_STATUS_SUCCESS; } //Check MMIE exit !! if( PlatformCompareMemory( MMIE , frame.Octet + frame.Length - 18, 2 )) { return RT_SEC_STATUS_MFP_MGNT_MMIE_FAILURE; } // Get MMIE pMMIE = (PMMIE_STRUC)( frame.Octet + frame.Length - 18 ); if(0 == PlatformCompareMemory(pMMIE->IPN, pSec->IPN, 6)) { RT_PRINT_DATA(COMP_SEC, DBG_WARNING, "[WARNING] Skip this frame because we received the same IPN = \n", pMMIE->IPN, 6); return RT_SEC_STATUS_MGNT_IV_REPLAY; } // Check PN for( index = 0 ; index < 6 ; index++ ) { if(pMMIE->IPN[5 - index] > pSec->IPN[5- index]) break; else if(pMMIE->IPN[5 - index] < pSec->IPN[5- index]) { RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "MMIE PN Data:", pMMIE->IPN, 6); RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "My PN Data:", pSec->IPN, 6); return RT_SEC_STATUS_MFP_MGNT_MMIE_FAILURE; // PN error !! } else continue; } // Constr ADD | frame body PlatformZeroMemory( PlantData , 256 ); PlatformMoveMemory( pCurrent , frame.Octet , 2 ); // FC // Reset Retry , PW_MGN and MORE bit SET_80211_HDR_RETRY(PlantData, 0); SET_80211_HDR_PWR_MGNT(PlantData, 0); SET_80211_HDR_MORE_DATA(PlantData, 0); pCurrent += 2; // A1 , A2 and A3 PlatformMoveMemory( pCurrent , frame.Octet + 4 , 18 ); pCurrent += 18; // Frame body PlatformMoveMemory( pCurrent , frame.Octet + 24 , frame.Length - 24 ); // PlantData length = AAD + PacketLen - Hardlen PlantDataLen = 20 + frame.Length - 24 ; // Clear MIC Fild PlatformZeroMemory( (PlantData + PlantDataLen - 8 ) , 8); RT_PRINT_DATA(COMP_SEC , DBG_LOUD , " PlantData :\n" , PlantData , PlantDataLen); // Calculate MIC AES_CMAC_1W( PlantData , PlantDataLen , pSec->BIPKeyBuffer , 16 , Micdata , &MACTextLength); // Compare MIC if(!PlatformCompareMemory( Micdata , pMMIE->MIC , 8 ) ) { PlatformMoveMemory(pSec->IPN, pMMIE->IPN, 6); return RT_SEC_STATUS_SUCCESS; } RT_PRINT_DATA(COMP_SEC, DBG_WARNING, "[WARNING] Mismatched MIC for MMIE=\n", pMMIE->MIC, 8); RT_PRINT_DATA(COMP_SEC, DBG_WARNING, "[WARNING] Mismatched MIC for Mine=\n", Micdata, MACTextLength); return RT_SEC_STATUS_MFP_MGNT_MMIE_MIC_FAILURE; } // // Description: // Handle Rx Packet encryption status and descrypt it if need. // Arguments: // [in] Adapter - // The NIC context. // [in] pRfd - // The Rx buffer and information. // Return: // RT_SEC_STATUS_SUCCESS if this packet is descrypted successfully, and otherwise if any error(this packet should be dropped). // By Bruce, 2009-10-15. // RT_SEC_STATUS SecRxDescryption( IN PADAPTER pAdapter, IN PRT_RFD pRfd ) { PMGNT_INFO pMgntInfo = &pAdapter->MgntInfo; PRT_SECURITY_T pSec = &(pMgntInfo->SecurityInfo); OCTET_STRING frame; RT_SEC_STATUS secStatus = RT_SEC_STATUS_SUCCESS; // Default mark this packet isn't MFP packet. pRfd->Status.bRxMFPPacket = FALSE; FillOctetString(frame, pRfd->Buffer.VirtualAddress, pRfd->PacketLength); //3 // Check Frame WEP bit // This packet should not be descrypted. if(!Frame_WEP(frame)) { if(!eqMacAddr(pMgntInfo->Bssid, Frame_Addr3(frame))) return RT_SEC_STATUS_SUCCESS; if(!((IsMgntDeauth(frame.Octet) || IsMgntDisasoc(frame.Octet)))) // Just check Deauth/Disassoc return RT_SEC_STATUS_SUCCESS; if(ACTING_AS_AP(pAdapter) || ACTING_AS_IBSS(pAdapter)) // Don't support in AP mode return RT_SEC_STATUS_SUCCESS; if(MacAddr_isMulticast(Frame_Addr1(frame))) { if(CCX_IS_MFP_ENABLED(pAdapter)) // CCX MFP does NOT support multicast return RT_SEC_STATUS_SUCCESS; else if(pMgntInfo->bInBIPMFPMode) { if(RT_SEC_STATUS_SUCCESS == (secStatus = SecCheckMMIE( pAdapter , pRfd ))) { RT_TRACE_F(COMP_SEC, DBG_LOUD, ("Check MMIE OK!\n")); pRfd->Status.bRxMFPPacket = TRUE; return RT_SEC_STATUS_SUCCESS; } else { RT_TRACE_F(COMP_SEC, DBG_LOUD, ("Failed (0x%08X) from SecCheckMMIE()\n", secStatus)); return secStatus; } } else { return RT_SEC_STATUS_SUCCESS; } } else // Unicast { if(CCX_IS_MFP_ENABLED(pAdapter)) { // Do nothing. } else if(pMgntInfo->bInBIPMFPMode) { if(((IsMgntDeauth(frame.Octet) && class3_err == Frame_DeauthReasonCode(frame)) || (IsMgntDisasoc(frame.Octet) && class3_err == Frame_DeassocReasonCode(frame))) && RT_SA_QUERY_STATE_UNINITIALIZED == pSec->pmfSaState) { RT_TRACE_F(COMP_SEC, DBG_LOUD, ("Received deauth/disassoc frame wit reason = 7 in PMF mode, start SA query process\n")); pSec->pmfSaState = RT_SA_QUERY_STATE_SA_DETECTED; PlatformSetTimer(pAdapter, &(pSec->SAQueryTimer), 100); } } else { return RT_SEC_STATUS_SUCCESS; } if(!SecIsTxKeyInstalled(pAdapter, pMgntInfo->Bssid)) return RT_SEC_STATUS_SUCCESS; if(IsMgntDisasoc(frame.Octet) || IsMgntDeauth(frame.Octet) || (IsMgntAction(frame.Octet) && !CCX_IS_MFP_ENABLED(pAdapter))) { // CCXv5 S67 MFP enabled, these packets should be encrypted, if not, count the statistic. switch(pSec->PairwiseEncAlgorithm) { case RT_ENC_ALG_TKIP: CountRxMgntTKIPNoEncryptStatistics(pAdapter, pRfd); break; case RT_ENC_ALG_AESCCMP: CountRxMgntCCMPNoEncryptStatistics(pAdapter, pRfd); break; default: //for MacOSX Compiler warning. break; } RT_PRINT_DATA(COMP_SEC, DBG_WARNING, "[WARNING] Received mgnt frame without protection bit\n", frame.Octet, frame.Length); return RT_SEC_STATUS_MGNT_FRAME_UNENCRYPT; } } return RT_SEC_STATUS_SUCCESS; } //3 // Descryption for Mgnt Frame. if(IsMgntFrame(frame.Octet)) { // Open Share Key mode, we do not handle this condition here. if( IsMgntAuth(frame.Octet) && (pSec->PairwiseEncAlgorithm == RT_ENC_ALG_WEP40 || pSec->PairwiseEncAlgorithm == RT_ENC_ALG_WEP104)) { return SecSoftwareDecryption(pAdapter, pRfd); } if(!eqMacAddr(pMgntInfo->Bssid, Frame_Addr3(frame))) return RT_SEC_STATUS_SUCCESS; // // 802.11 MFP AES // if(pMgntInfo->bInBIPMFPMode || CCX_IS_MFP_ENABLED(pAdapter)) { // Mark this packet as MFP Packet to make sure the Descryption process fills the correct values in the fields. pRfd->Status.bRxMFPPacket = TRUE; RT_PRINT_DATA(COMP_SEC , DBG_LOUD, "SecRxDescryption(): Received Unicast Mgnt Frame with protection:\n" , frame.Octet, frame.Length ); secStatus = SecSWMFPDecryption(pAdapter, pRfd); return secStatus; } else { RT_TRACE(COMP_SEC, DBG_WARNING, ("SecRxDescryption(): Error!!! Receive Mgnt Frame with WEP bit (Not support)!")); return RT_SEC_STATUS_PKT_TYPE_NOT_SUPPORT; } return secStatus; } //3 // Data packet. if(IsDataFrame(frame.Octet)) { if(pSec->SWRxDecryptFlag) { if(pMgntInfo->SafeModeEnabled) { RT_TRACE_F(COMP_RECV, DBG_LOUD, ("Do not use SecSoftwareDecryption when SafeModeEnabled\n")); return RT_SEC_STATUS_SUCCESS; } if(RT_SEC_STATUS_SUCCESS != (secStatus = SecSoftwareDecryption(pAdapter, pRfd))) { RT_TRACE(COMP_SEC , DBG_LOUD , ("SecRxDescryption(): SW Descrypt Fail(0x%08X) for data packet\n", secStatus) ); return secStatus; } return RT_SEC_STATUS_SUCCESS; } // Win7 SW Descryption Special Case if( pMgntInfo->NdisVersion >= RT_NDIS_VERSION_6_20 || pMgntInfo->bConcurrentMode || pMgntInfo->bBTMode ) { BOOLEAN bSWSec = FALSE; if( ( MacAddr_isBcst(Frame_pDaddr(frame)) || MacAddr_isMulticast(Frame_pDaddr(frame)) ) && MgntActQuery_ApType(pAdapter) == RT_AP_TYPE_NONE) bSWSec = TRUE; else if( pSec->PairwiseEncAlgorithm == RT_ENC_ALG_WEP104 || pSec->PairwiseEncAlgorithm == RT_ENC_ALG_WEP40) bSWSec = TRUE; else if( pMgntInfo->Regdot11networktype == RT_JOIN_NETWORKTYPE_ADHOC && MgntActQuery_ApType(pAdapter) == RT_AP_TYPE_NONE) bSWSec = TRUE; else if(!pMgntInfo->SecurityInfo.SWRxDecryptFlag && Frame_WEP(frame) && pRfd->Status.Decrypted == 0) bSWSec = TRUE; else bSWSec = FALSE; //for win7 FPGA Verification, Adhoc TP test if(pMgntInfo->bRegAdhocUseHWSec && pMgntInfo->Regdot11networktype == RT_JOIN_NETWORKTYPE_ADHOC) bSWSec = FALSE; if(bSWSec) { if(RT_SEC_STATUS_SUCCESS != (secStatus = SecSoftwareDecryption(pAdapter, pRfd))) { { RT_TRACE(COMP_SEC , DBG_TRACE , ("===>Fail Win7 SW decrypt\n") ); return RT_SEC_STATUS_FAILURE; } } } } // Normal Case with HW Descryption return RT_SEC_STATUS_SUCCESS; } RT_TRACE(COMP_SEC, DBG_WARNING, ("SecRxDescryption(): Error!!! Receive Frame(Type = 0x%02X) with WEP bit (Not support)!", frame.Octet[0])); return RT_SEC_STATUS_PKT_TYPE_NOT_SUPPORT; } // // Description: // Append 802.11w MFP MMIE , just for AP mode !! // Input : // posFrame : Action or mgnt frame , DA is broadcast !! // void SecAppenMMIE( IN PADAPTER pAdapter, OUT POCTET_STRING posFrame ) { if( !(ACTING_AS_AP(pAdapter) )) return; // TO DO !! RT_TRACE(COMP_SEC, DBG_LOUD , ( " ===> AP mode support MFP ??\n" )); return; } BOOLEAN SecStaGetANoseForS5( IN PADAPTER Adapter, IN POCTET_STRING pPduOS ) { PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); u1Byte Offset_TypeEAPOL = sMacHdrLng + LLC_HEADER_SIZE; // 30 OCTET_STRING EapMessage; OCTET_STRING EapKeyMessage; OCTET_STRING ANonce; if( IsQoSDataFrame(pPduOS->Octet) ) { Offset_TypeEAPOL += sQoSCtlLng; // +2 } if( Frame_WEP(*pPduOS)) { Offset_TypeEAPOL += Adapter->MgntInfo.SecurityInfo.EncryptionHeadOverhead; // 4 or 8 } // Length Check if( pPduOS->Length < (Offset_TypeEAPOL+1) ) { RT_TRACE( COMP_SEC, DBG_TRACE, ("SecGetANoseForS5(): invalid length(%d)\n", pPduOS->Length ) ); return FALSE; } // 888e? if( (pPduOS->Octet[Offset_TypeEAPOL]==0x88) && (pPduOS->Octet[Offset_TypeEAPOL+1]==0x8e) ) { //TYPE_LENGTH_FIELD_SIZE EapMessage.Octet = pPduOS->Octet+(Offset_TypeEAPOL+TYPE_LENGTH_FIELD_SIZE); EapMessage.Length = pPduOS->Length - (Offset_TypeEAPOL+TYPE_LENGTH_FIELD_SIZE); //RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "===> SecStaGetANoseForS5 \n", EapMessage.Octet, EapMessage.Length); if( (u1Byte)( *(EapMessage.Octet+1) ) == LIB1X_EAPOL_KEY ) { FillOctetString(EapKeyMessage, EapMessage.Octet+LIB1X_EAPOL_HDRLEN, EapMessage.Length-LIB1X_EAPOL_HDRLEN ); if( Message_KeyType(EapKeyMessage) == type_Pairwise && Message_KeyMIC(EapKeyMessage) == FALSE) // 1st message of 4-Way { ANonce = Message_KeyNonce(EapKeyMessage); PlatformMoveMemory(pMgntInfo->mbS5ANose,ANonce.Octet,KEY_NONCE_LEN); RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "===> SecStaGetANoseForS5 \n", pMgntInfo->mbS5ANose,KEY_NONCE_LEN); } } } return FALSE; } BOOLEAN SecStaGenPMKForS5( IN PADAPTER Adapter ) { PMGNT_INFO pMgntInfo = &(Adapter->MgntInfo); PasswordHash(pMgntInfo->mbPassphrase,pMgntInfo->mPasspharseLen, pMgntInfo->Ssid.Octet, pMgntInfo->Ssid.Length, pMgntInfo->mbS5PMK); // Calcut PTK CalcPTK(pMgntInfo->Bssid , Adapter->CurrentAddress, pMgntInfo->mbS5ANose, pMgntInfo->mbS5SNose, pMgntInfo->mbS5PMK, PMK_LEN, pMgntInfo->mbS5PTK, PTK_LEN_TKIP); PlatformMoveMemory(pMgntInfo->PMDot11RSNRekeyPara.KCK , pMgntInfo->mbS5PTK , PTK_LEN_EAPOLMIC); // PlatformMoveMemory(pMgntInfo->PMDot11RSNRekeyPara.KEK , pMgntInfo->mbS5PTK+PTK_LEN_EAPOLMIC , PTK_LEN_EAPOLENC); RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "===>SecStaGenPMKForS5 PMK : \n", pMgntInfo->mbS5PMK, PMK_LEN); RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "===>SecStaGenPMKForS5 PTK : \n", pMgntInfo->mbS5PTK, PTK_LEN_TKIP); return TRUE; } // // Description: // Received the SA query packet from the STA. // RT_STATUS OnSAQueryReq( IN PADAPTER pAdapter, IN PRT_RFD pRfd, IN POCTET_STRING posMpdu ) { PMGNT_INFO pMgntInfo = &pAdapter->MgntInfo; RT_STATUS rtStatus = RT_STATUS_SUCCESS; RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "OnSAQueryReq(): Content:\n", posMpdu->Octet, posMpdu->Length); do { if(!pRfd->Status.bRxMFPPacket) { if(pMgntInfo->bInBIPMFPMode) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("[WARNING] Received an unproteced SA query frame in PMF mode\n")); } rtStatus = RT_STATUS_PKT_DROP; break; } if(posMpdu->Length < MIN_ACTION_SA_QUERY_FRAME_LEN) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("[WARNING] Received Length (%d) of SA Query Req < %d, skip this frame\n", posMpdu->Length, MIN_ACTION_SA_QUERY_FRAME_LEN)); rtStatus = RT_STATUS_INVALID_LENGTH; } SendSAQueryRsp(pAdapter, Frame_Addr2(*posMpdu), GET_ACTFRAME_SA_QUERY_ID(posMpdu->Octet)); RT_TRACE_F(COMP_SEC, DBG_LOUD, ("Send SA Query Rsp with Identifier = 0x%04X\n", GET_ACTFRAME_SA_QUERY_ID(posMpdu->Octet))); }while(FALSE); return RT_STATUS_SUCCESS; } // // Description: // Received the SA query response packet from the STA. // RT_STATUS OnSAQueryRsp( IN PADAPTER pAdapter, IN PRT_RFD pRfd, IN POCTET_STRING posMpdu ) { PMGNT_INFO pMgntInfo = &pAdapter->MgntInfo; PRT_SECURITY_T pSecInfo = &(pMgntInfo->SecurityInfo); RT_STATUS rtStatus = RT_STATUS_SUCCESS; RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "OnSAQueryRsp(): Content:\n", posMpdu->Octet, posMpdu->Length); do { if(!pRfd->Status.bRxMFPPacket) { if(pMgntInfo->bInBIPMFPMode) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("[WARNING] Received an unproteced SA query frame in PMF mode\n")); } rtStatus = RT_STATUS_PKT_DROP; break; } if(posMpdu->Length < MIN_ACTION_SA_QUERY_FRAME_LEN) { RT_TRACE_F(COMP_SEC, DBG_WARNING, ("[WARNING] Received Length (%d) of SA Query Req < %d, skip this frame\n", posMpdu->Length, MIN_ACTION_SA_QUERY_FRAME_LEN)); rtStatus = RT_STATUS_INVALID_LENGTH; } if(!pMgntInfo->mAssoc) { RT_TRACE_F(COMP_SEC, DBG_LOUD, ("Received SA query response without association, skip it\n")); rtStatus = RT_STATUS_INVALID_STATE; break; } if(RT_SA_QUERY_STATE_SA_REQ_IN_PROGRESS != pSecInfo->pmfSaState) { RT_TRACE_F(COMP_SEC, DBG_LOUD, ("Received SA query response mismaching my pmfState (%d), skip it\n", pSecInfo->pmfSaState)); rtStatus = RT_STATUS_INVALID_STATE; break; } RT_TRACE_F(COMP_SEC, DBG_LOUD, ("Idendifier = 0x%04X, my Identifier = 0x%04X\n", GET_ACTFRAME_SA_QUERY_ID(posMpdu->Octet), pSecInfo->SAReqIdentifier)); if(GET_ACTFRAME_SA_QUERY_ID(posMpdu->Octet) != pSecInfo->SAReqIdentifier) { RT_TRACE_F(COMP_SEC, DBG_LOUD, ("Received mismatched Idendifier = 0x%04X, my Identifier = 0x%04X, skip it\n", GET_ACTFRAME_SA_QUERY_ID(posMpdu->Octet), pSecInfo->SAReqIdentifier)); rtStatus = RT_STATUS_INVALID_DATA; break; } RT_TRACE_F(COMP_SEC, DBG_LOUD, ("SA Query process OK, cancel timer\n")); pSecInfo->pmfSaState = RT_SA_QUERY_STATE_UNINITIALIZED; PlatformCancelTimer(pAdapter, &(pSecInfo->SAQueryTimer)); }while(FALSE); return RT_STATUS_SUCCESS; } // // Description: // Fill and move IV and offset if this tx management frame shall be proteced. // Arguments: // [in] Adapter - // The NIC context. // [in] pTcb - // The context of tx frame. // Return: // TRUE if this frame is filled and reserved with security content. // FALSE if this frame is returned without any change. // Remark: // This function checks the association condition and determine if the current frame // needs to be proteced. If yes, this frame is filled with WEP bit set in the header. // By Bruce-2014-12-26. // BOOLEAN SecFillProtectTxMgntFrameHeader( IN PADAPTER pAdapter, IN PRT_TCB pTcb ) { PMGNT_INFO pMgntInfo = &(pAdapter->MgntInfo); PRT_SECURITY_T pSecInfo = &(pMgntInfo->SecurityInfo); OCTET_STRING osMpdu; BOOLEAN bProtected = FALSE; FillOctetString(osMpdu, GET_FRAME_OF_FIRST_FRAG(pAdapter, pTcb), (u2Byte)pTcb->BufferList[0].Length); do { // Currently, we only checks the action frame because some mgnt frames like deauth/disassociation are filled // with IV and WEP bit in the construction function, but others mgnt frames excluding deauth/disassociation/action // frame shall be sent without protection. // By Bruce, 2014-12-26. if(!IsMgntAction(osMpdu.Octet)) { break; } if(!pMgntInfo->bInBIPMFPMode) { break; } // We only support AES in PMF. if(RT_ENC_ALG_AESCCMP != pSecInfo->PairwiseEncAlgorithm) { break; } // We don't support PMF in AP mode. if(MacAddr_isMulticast(Frame_Addr1(osMpdu))) { break; } if(0 == pSecInfo->EncryptionHeadOverhead) break; bProtected = TRUE; }while(FALSE); if(bProtected) { //3 // Determine different kind of frames before fill the IV // ToDo //RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "SecFillProtectTxMgntFrameHeader(): Before extend IV content:\n", osMpdu.Octet, osMpdu.Length); // Set WEP bit !! SET_80211_HDR_WEP(osMpdu.Octet, 1); PlatformMoveMemory(pSecInfo->SecBuffer, (osMpdu.Octet + sMacHdrLng), (osMpdu.Length - sMacHdrLng)); PlatformMoveMemory((osMpdu.Octet+ sMacHdrLng + pSecInfo->EncryptionHeadOverhead), pSecInfo->SecBuffer, (osMpdu.Length - sMacHdrLng)); PlatformZeroMemory(osMpdu.Octet + sMacHdrLng , pSecInfo->EncryptionHeadOverhead); osMpdu.Length += pSecInfo->EncryptionHeadOverhead; pTcb->BufferList[0].Length += pSecInfo->EncryptionHeadOverhead; pTcb->PacketLength += pSecInfo->EncryptionHeadOverhead; //RT_PRINT_DATA(COMP_SEC, DBG_LOUD, "SecFillProtectTxMgntFrameHeader(): After extend IV content:\n", osMpdu.Octet, osMpdu.Length); } return bProtected; } // Description: // Timer callback function to handle SA query mechanism. VOID SAQueryTimerCallback( IN PRT_TIMER pTimer ) { PADAPTER pAdapter = (PADAPTER)pTimer->Adapter; PMGNT_INFO pMgntInfo = &(pAdapter->MgntInfo); PRT_SECURITY_T pSec = &pAdapter->MgntInfo.SecurityInfo; RT_TRACE_F(COMP_SEC, DBG_LOUD, ("pmfSaState = %d\n", pSec->pmfSaState)); if(!pMgntInfo->mAssoc) { pSec->pmfSaState = RT_SA_QUERY_STATE_UNINITIALIZED; RT_TRACE_F(COMP_SEC, DBG_LOUD, ("State is not associated, skip SA query\n")); return; } if(RT_SA_QUERY_STATE_SA_DETECTED == pSec->pmfSaState) { pSec->SAReqIdentifier = (pSec->SAReqIdentifier + 1) % 0xFFFFFFFF; pSec->pmfSaState = RT_SA_QUERY_STATE_SA_REQ_IN_PROGRESS; RT_TRACE_F(COMP_SEC, DBG_LOUD, ("Send SA query request with ID = %04X to AP\n", pSec->SAReqIdentifier)); SendSAQueryReq(pAdapter, pMgntInfo->Bssid, pSec->SAReqIdentifier); PlatformSetTimer(pAdapter, &(pSec->SAQueryTimer), 1000); } else if(RT_SA_QUERY_STATE_SA_REQ_IN_PROGRESS == pSec->pmfSaState) { RT_TRACE_F(COMP_SEC, DBG_LOUD, ("Disconnect from the AP\n")); MgntDisconnectAP(pAdapter, unspec_reason); pSec->pmfSaState = RT_SA_QUERY_STATE_UNINITIALIZED; } else { RT_TRACE_F(COMP_SEC, DBG_LOUD, ("[WARNING] Unknown pmfstate = %d\n", pSec->pmfSaState)); } } // // 2011/03/04 MH Move all new CAN search metho to here forcommon binary . // We need to reorganize the locaton in he future. // --------------------------------------------------------------- // #if (HW_EN_DE_CRYPTION_FOR_NEW_CAM_SEARCH_FLOW == 1) VOID SEC_AsocEntry_ResetEntry( IN PADAPTER Adapter, IN PRT_WLAN_STA pEntry ) { u1Byte i; for( i = 4 ; i < Adapter->TotalCamEntry ; i++) { if( (Adapter->MgntInfo.SWCamTable[i].bUsed) &&(PlatformCompareMemory(pEntry->MacAddr, Adapter->MgntInfo.SWCamTable[i].macAddress, 6)==0)) { CamDeleteOneEntry( Adapter , pEntry->MacAddr, i); PlatformZeroMemory( & Adapter->MgntInfo.SWCamTable[i] , sizeof(SW_CAM_TABLE) ); } } } #endif // #if (HW_EN_DE_CRYPTION_FOR_NEW_CAM_SEARCH_FLOW == 1) VOID SecUpdateSWGroupKeyInfo( IN PADAPTER Adapter, IN u4Byte KeyIndex, IN u4Byte KeyLength, IN pu1Byte KeyMaterial ) { PRT_SECURITY_T pSecInfo = &Adapter->MgntInfo.SecurityInfo; RT_ENC_ALG EncAlgorithm; EncAlgorithm = pSecInfo->GroupEncAlgorithm; RT_TRACE( COMP_INIT, DBG_LOUD, ("SecUpdateSWGroupKeyInfo(): SecLvl>0, Group EncAlgorithm=0x%08X, Pairwise EncAlgo=0x%08X\n", EncAlgorithm, pSecInfo->PairwiseEncAlgorithm) ); SecClearGroupKeyByIdx(Adapter, (u1Byte)KeyIndex); CopyMem(pSecInfo->KeyBuf[KeyIndex], KeyMaterial, KeyLength ); pSecInfo->KeyLen[KeyIndex]= (u1Byte)KeyLength; if(EncAlgorithm == RT_ENC_ALG_TKIP) { if((KeyIndex & ADD_KEY_IDX_AS)){//kcwu: Key is set by an Authenticator, exchange Tx/Rx MIC u1Byte tmpbuf[TKIP_MIC_KEY_LEN]; PlatformMoveMemory(tmpbuf, KeyMaterial+TKIP_ENC_KEY_LEN, TKIP_MIC_KEY_LEN); PlatformMoveMemory(KeyMaterial+TKIP_ENC_KEY_LEN, KeyMaterial+TKIP_ENC_KEY_LEN+TKIP_MIC_KEY_LEN, TKIP_MIC_KEY_LEN); PlatformMoveMemory(KeyMaterial+TKIP_ENC_KEY_LEN+TKIP_MIC_KEY_LEN, tmpbuf, TKIP_MIC_KEY_LEN); } PlatformMoveMemory(pSecInfo->RxMICKey, KeyMaterial+TKIP_MICKEYRX_POS, TKIP_MIC_KEY_LEN); PlatformMoveMemory(pSecInfo->TxMICKey, KeyMaterial+TKIP_MICKEYTX_POS, TKIP_MIC_KEY_LEN); } else if(EncAlgorithm == RT_ENC_ALG_AESCCMP) { //2004/09/07, kcwu, AES Key Initialize AESCCMP_BLOCK blockKey; PlatformMoveMemory(blockKey.x, pSecInfo->KeyBuf[KeyIndex],16); AES_SetKey(blockKey.x, AESCCMP_BLK_SIZE*8, (u4Byte *)pSecInfo->AESKeyBuf[KeyIndex]); // run the key schedule } else if(EncAlgorithm==RT_ENC_ALG_WEP40 || EncAlgorithm==RT_ENC_ALG_WEP104) { RT_TRACE( COMP_SEC, DBG_LOUD, ("MgntActSet_802_11_ADD_KEY(): SecLvl>0, EncAlgorithm=%d\n", EncAlgorithm) ); } } // // --------------------------------------------------------------- // 2011/03/04 MH Move all new CAN search metho to here forcommon binary . // We need to reorganize the locaton in he future. //
85,120
446
<filename>applications/templatetags/applications_tags.py from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def display_sorting_arrow(name, current_order): is_reversed = False if f'-{name}' == current_order: is_reversed = True if is_reversed: return mark_safe(f'<a href="?order={name}">▼</a>') else: return mark_safe(f'<a href="?order=-{name}">▲</a>')
194
21,382
package io.ray.streaming.runtime.config; import java.io.Serializable; import java.util.Map; /** Streaming config including general, master and worker part. */ public class StreamingConfig implements Serializable { public StreamingMasterConfig masterConfig; public StreamingWorkerConfig workerConfigTemplate; public StreamingConfig(final Map<String, String> conf) { masterConfig = new StreamingMasterConfig(conf); workerConfigTemplate = new StreamingWorkerConfig(conf); } public Map<String, String> getMap() { Map<String, String> wholeConfigMap = masterConfig.configMap; wholeConfigMap.putAll(workerConfigTemplate.configMap); return wholeConfigMap; } }
188
535
<reponame>Nemo157/mynewt-core<gh_stars>100-1000 /* * 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. */ /** * @addtogroup HAL * @{ * @defgroup HALUart HAL UART * @{ */ #ifndef H_HAL_UART_H_ #define H_HAL_UART_H_ #ifdef __cplusplus extern "C" { #endif #include <inttypes.h> /** * Function prototype for UART driver to ask for more data to send. * Returns -1 if no more data is available for TX. * Driver must call this with interrupts disabled. */ typedef int (*hal_uart_tx_char)(void *arg); /** * Function prototype for UART driver to report that transmission is * complete. This should be called when transmission of last byte is * finished. * Driver must call this with interrupts disabled. */ typedef void (*hal_uart_tx_done)(void *arg); /** * Function prototype for UART driver to report incoming byte of data. * Returns -1 if data was dropped. * Driver must call this with interrupts disabled. */ typedef int (*hal_uart_rx_char)(void *arg, uint8_t byte); /** * Initializes given uart. Mapping of logical UART number to physical * UART/GPIO pins is in BSP. */ int hal_uart_init_cbs(int uart, hal_uart_tx_char tx_func, hal_uart_tx_done tx_done, hal_uart_rx_char rx_func, void *arg); enum hal_uart_parity { /** No Parity */ HAL_UART_PARITY_NONE = 0, /** Odd parity */ HAL_UART_PARITY_ODD = 1, /** Even parity */ HAL_UART_PARITY_EVEN = 2 }; enum hal_uart_flow_ctl { /** No Flow Control */ HAL_UART_FLOW_CTL_NONE = 0, /** RTS/CTS */ HAL_UART_FLOW_CTL_RTS_CTS = 1 }; /** * Initialize the HAL uart. * * @param uart The uart number to configure * @param cfg Hardware specific uart configuration. This is passed from BSP * directly to the MCU specific driver. * * @return 0 on success, non-zero error code on failure */ int hal_uart_init(int uart, void *cfg); /** * Applies given configuration to UART. * * @param uart The UART number to configure * @param speed The baudrate in bps to configure * @param databits The number of databits to send per byte * @param stopbits The number of stop bits to send * @param parity The UART parity * @param flow_ctl Flow control settings on the UART * * @return 0 on success, non-zero error code on failure */ int hal_uart_config(int uart, int32_t speed, uint8_t databits, uint8_t stopbits, enum hal_uart_parity parity, enum hal_uart_flow_ctl flow_ctl); /** * Close UART port. Can call hal_uart_config() with different settings after * calling this. * * @param uart The UART number to close */ int hal_uart_close(int uart); /** * More data queued for transmission. UART driver will start asking for that * data. * * @param uart The UART number to start TX on */ void hal_uart_start_tx(int uart); /** * Upper layers have consumed some data, and are now ready to receive more. * This is meaningful after uart_rx_char callback has returned -1 telling * that no more data can be accepted. * * @param uart The UART number to begin RX on */ void hal_uart_start_rx(int uart); /** * This is type of write where UART has to block until character has been sent. * Used when printing diag output from system crash. * Must be called with interrupts disabled. * * @param uart The UART number to TX on * @param byte The byte to TX on the UART */ void hal_uart_blocking_tx(int uart, uint8_t byte); #ifdef __cplusplus } #endif #endif /* H_HAL_UART_H_ */ /** * @} HALUart * @} HAL */
1,363
1,481
<filename>core/src/main/java/apoc/generate/relationship/SimpleGraphRelationshipGenerator.java package apoc.generate.relationship; import apoc.generate.config.DistributionBasedConfig; import apoc.generate.distribution.MutableDegreeDistribution; import apoc.generate.distribution.MutableSimpleDegreeDistribution; import apoc.generate.utils.WeightedReservoirSampler; import org.neo4j.internal.helpers.collection.Pair; import java.util.ArrayList; import java.util.List; /** * A simple minded {@link RelationshipGenerator} based on a {@link apoc.generate.distribution.DegreeDistribution} * <p/> * Please note that the distribution of randomly generated graphs isn't exactly uniform (see the paper below) * <p/> * Uses Blitzstein-Diaconis algorithm Ref: * <p/> * A SEQUENTIAL IMPORTANCE SAMPLING ALGORITHM FOR GENERATING RANDOM GRAPHS WITH PRESCRIBED DEGREES * By <NAME> and <NAME> (Stanford University). (Harvard, June 2006) */ public class SimpleGraphRelationshipGenerator extends BaseRelationshipGenerator<DistributionBasedConfig> { public SimpleGraphRelationshipGenerator(DistributionBasedConfig configuration) { super(configuration); } /** * {@inheritDoc} * <p/> * Returns an edge-set corresponding to a randomly chosen simple graph. */ @Override protected List<Pair<Integer, Integer>> doGenerateEdges() { List<Pair<Integer, Integer>> edges = new ArrayList<>(); MutableDegreeDistribution distribution = new MutableSimpleDegreeDistribution(getConfiguration().getDegrees()); while (!distribution.isZeroList()) { // int length = distribution.size(); int index = 0; long min = Long.MAX_VALUE; // find minimal nonzero element for (int i = 0; i < distribution.size(); ++i) { long elem = distribution.get(i); if (elem != 0 && elem < min) { min = elem; index = i; } } WeightedReservoirSampler sampler = new WeightedReservoirSampler(); // Obtain a candidate list: while (true) { MutableDegreeDistribution temp = new MutableSimpleDegreeDistribution(distribution.getDegrees()); int candidateIndex = sampler.randomIndexChoice(temp.getDegrees(), index); Pair<Integer, Integer> edgeCandidate = Pair.of(candidateIndex, index); // Checks if edge has already been added. boolean skip = false; for (Pair<Integer, Integer> edge : edges) { if (edge.equals(edgeCandidate)) { skip = true; break; } } if (skip) { continue; } // Prepare the candidate set and test if it is graphical temp.decrease(index); temp.decrease(candidateIndex); if (temp.isValid()) { distribution = temp; edges.add(edgeCandidate); // edge is allowed, add it. break; } } } return edges; } }
1,432
354
<reponame>iabernikhin/VK-GL-CTS<gh_stars>100-1000 #ifndef _RRMULTISAMPLEPIXELBUFFERACCESS_HPP #define _RRMULTISAMPLEPIXELBUFFERACCESS_HPP /*------------------------------------------------------------------------- * drawElements Quality Program Reference Renderer * ----------------------------------------------- * * Copyright 2014 The Android Open Source Project * * 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. * *//*! * \file * \brief Multisampled pixel buffer access *//*--------------------------------------------------------------------*/ #include "rrDefs.hpp" #include "tcuTexture.hpp" namespace rr { /*--------------------------------------------------------------------*//*! * \brief Read-write pixel data access to multisampled buffers. * * Multisampled data access follows the multisampled indexing convention. * * Prevents accidental usage of non-multisampled buffer as multisampled * with PixelBufferAccess. *//*--------------------------------------------------------------------*/ class MultisamplePixelBufferAccess { MultisamplePixelBufferAccess (const tcu::PixelBufferAccess& rawAccess); public: MultisamplePixelBufferAccess (void); inline const tcu::PixelBufferAccess& raw (void) const { return m_access; } inline int getNumSamples (void) const { return raw().getWidth(); } const tcu::PixelBufferAccess toSinglesampleAccess (void) const; static MultisamplePixelBufferAccess fromSinglesampleAccess (const tcu::PixelBufferAccess& singlesampledAccess); static MultisamplePixelBufferAccess fromMultisampleAccess (const tcu::PixelBufferAccess& multisampledAccess); private: tcu::PixelBufferAccess m_access; } DE_WARN_UNUSED_TYPE; /*--------------------------------------------------------------------*//*! * \brief Read-only pixel data access to multisampled buffers. * * Multisampled data access follows the multisampled indexing convention. * * Prevents accidental usage of non-multisampled buffer as multisampled * with PixelBufferAccess. *//*--------------------------------------------------------------------*/ class MultisampleConstPixelBufferAccess { MultisampleConstPixelBufferAccess (const tcu::ConstPixelBufferAccess& rawAccess); public: MultisampleConstPixelBufferAccess (const rr::MultisamplePixelBufferAccess& msAccess); MultisampleConstPixelBufferAccess (void); inline const tcu::ConstPixelBufferAccess& raw (void) const { return m_access; } inline int getNumSamples (void) const { return raw().getWidth(); } const tcu::ConstPixelBufferAccess toSinglesampleAccess (void) const; static MultisampleConstPixelBufferAccess fromSinglesampleAccess (const tcu::ConstPixelBufferAccess& singlesampledAccess); static MultisampleConstPixelBufferAccess fromMultisampleAccess (const tcu::ConstPixelBufferAccess& multisampledAccess); private: tcu::ConstPixelBufferAccess m_access; } DE_WARN_UNUSED_TYPE; // Multisampled versions of tcu-utils MultisamplePixelBufferAccess getSubregion (const MultisamplePixelBufferAccess& access, int x, int y, int width, int height); MultisampleConstPixelBufferAccess getSubregion (const MultisampleConstPixelBufferAccess& access, int x, int y, int width, int height); void resolveMultisampleColorBuffer (const tcu::PixelBufferAccess& dst, const MultisampleConstPixelBufferAccess& src); void resolveMultisampleDepthBuffer (const tcu::PixelBufferAccess& dst, const MultisampleConstPixelBufferAccess& src); void resolveMultisampleStencilBuffer (const tcu::PixelBufferAccess& dst, const MultisampleConstPixelBufferAccess& src); void resolveMultisampleBuffer (const tcu::PixelBufferAccess& dst, const MultisampleConstPixelBufferAccess& src); tcu::Vec4 resolveMultisamplePixel (const MultisampleConstPixelBufferAccess& access, int x, int y); void clear (const MultisamplePixelBufferAccess& access, const tcu::Vec4& color); void clear (const MultisamplePixelBufferAccess& access, const tcu::IVec4& color); void clearDepth (const MultisamplePixelBufferAccess& access, float depth); void clearStencil (const MultisamplePixelBufferAccess& access, int stencil); } // rr #endif // _RRMULTISAMPLEPIXELBUFFERACCESS_HPP
1,520
1,442
<reponame>didichuxing/delta # Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. # All rights reserved. # # 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. # ============================================================================== ''' speaker task unittest''' import os from absl import logging import delta.compat as tf from delta.utils.kaldi import kaldi_dir from delta.utils.kaldi.kaldi_dir_utils import gen_dummy_meta class KaldiDirTest(tf.test.TestCase): ''' Kaldi dir meta data IO test''' def setUp(self): super().setUp() def tearDown(self): ''' tear down''' def test_property(self): ''' test custom properties ''' utt = kaldi_dir.Utt() self.assertIsNone(utt.wavlen) utt.wavlen = 1 self.assertEqual(utt.wavlen, 1) def test_gen_dummy_data(self): ''' test dump and load data ''' num_spk = 5 num_utt_per_spk = 3 meta = gen_dummy_meta(num_spk, num_utt_per_spk) self.assertEqual(len(meta.spks), num_spk) def test_dump_and_load(self): ''' test dump and load data ''' temp_dir = self.get_temp_dir() num_spk = 5 num_utt_per_spk = 3 meta = gen_dummy_meta(num_spk, num_utt_per_spk) meta.dump(temp_dir, True) with open(os.path.join(temp_dir, 'feats.scp'), 'r') as fp_in: logging.info('feats.scp:\n%s' % (fp_in.read())) loaded_meta = kaldi_dir.KaldiMetaData() loaded_meta.load(temp_dir) self.assertEqual(len(meta.utts), len(loaded_meta.utts)) for utt_key in meta.utts.keys(): self.assertIn(utt_key, loaded_meta.utts) self.assertEqual(len(meta.spks), len(loaded_meta.spks)) for spk_key in meta.spks.keys(): self.assertIn(spk_key, loaded_meta.spks) if __name__ == '__main__': logging.set_verbosity(logging.DEBUG) tf.test.main()
857
679
/************************************************************** * * 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.openoffice.setup.InstallerHelper; import org.openoffice.setup.InstallData; import org.openoffice.setup.ResourceManager; import org.openoffice.setup.SetupData.PackageDescription; import org.openoffice.setup.Util.Controller; import org.openoffice.setup.Util.Converter; import org.openoffice.setup.Util.ExecuteProcess; import org.openoffice.setup.Util.Informer; import org.openoffice.setup.Util.LogManager; import org.openoffice.setup.Util.SystemManager; import java.io.File; import java.util.HashMap; import java.util.Vector; public class SolarisHelper { public SolarisHelper() { } private void createLocalTempDir() { String mktempString = "/usr/bin/mktemp"; File mktemp = new File(mktempString); if ( mktemp.exists() ) { // this is Solaris 10 LogManager.setCommandsHeaderLine("Preparing Solaris 10 user installation"); InstallData data = InstallData.getInstance(); String mktempCommand = mktempString + " -d"; String[] mktempCommandArray = new String[2]; mktempCommandArray[0] = mktempString; mktempCommandArray[1] = "-d"; Vector returnVector = new Vector(); Vector returnErrorVector = new Vector(); int returnValue = ExecuteProcess.executeProcessReturnVector(mktempCommandArray, returnVector, returnErrorVector); String uniqueLocalDir = (String) returnVector.get(0); data.setLocalTempPath(uniqueLocalDir); String log = mktempCommand + "<br><b>Returns: " + uniqueLocalDir + "</b><br>"; LogManager.addCommandsLogfileComment(log); String installRoot = data.getInstallDir(); File installRootTemp = new File(installRoot, "tmp"); if ( installRootTemp.exists() ) { SystemManager.removeDirectory(installRootTemp); } String linkCommand = "ln -s " + uniqueLocalDir + " " + installRootTemp.getPath(); String[] linkCommandArray = new String[4]; linkCommandArray[0] = "ln"; linkCommandArray[1] = "-s"; linkCommandArray[2] = uniqueLocalDir; linkCommandArray[3] = installRootTemp.getPath(); // Vector returnVector = new Vector(); returnValue = ExecuteProcess.executeProcessReturnValue(linkCommandArray); log = linkCommand + "<br><b>Returns: " + returnValue + "</b><br>"; LogManager.addCommandsLogfileComment(log); } } private void removeLocalTempDir() { InstallData data = InstallData.getInstance(); if ( data.getLocalTempPath() != null ) { File installRootTemp = new File(data.getInstallDir(), "tmp"); if ( installRootTemp.exists() ) { installRootTemp.delete(); // removing the link SystemManager.createDirectory(installRootTemp); } File localTemp = new File(data.getLocalTempPath()); if ( localTemp.exists() ) { SystemManager.removeDirectory(localTemp); } } } private Vector getAdminFileContent(boolean relocatable, boolean rdepends) { Vector adminFile = new Vector(); InstallData data = InstallData.getInstance(); // if ( relocatable ) { // String installDir = data.getInstallDir(); // // installDir = installDir.replace(" ", "\\ "); // String baseDirLine = "basedir=" + installDir; // adminFile.add(baseDirLine); // } String mailLine = "mail="; adminFile.add(mailLine); String conflictLine = "conflict=nochange"; if ( data.isUserInstallation() ) { conflictLine = "conflict=nochange"; } adminFile.add(conflictLine); String runlevelLine = "runlevel=nocheck"; adminFile.add(runlevelLine); String setuidLine = "setuid=quit"; if ( data.isUserInstallation() ) { setuidLine = "setuid=nocheck"; } adminFile.add(setuidLine); String actionLine = "action=nocheck"; adminFile.add(actionLine); String partialLine = "partial=quit"; if ( data.isUserInstallation() ) { partialLine = "partial=nocheck"; } adminFile.add(partialLine); String instanceLine = "instance=unique"; adminFile.add(instanceLine); // String idependLine = "idepend=quit"; String idependLine = "idepend=nocheck"; // if ( data.isUserInstallation() ) { idependLine = "idepend=nocheck"; } adminFile.add(idependLine); // String rdependLine = "rdepend=nocheck"; String rdependLine = "rdepend=quit"; if ( ! rdepends ) { rdependLine = "rdepend=nocheck"; } if ( data.isUserInstallation() ) { rdependLine = "rdepend=nocheck"; } adminFile.add(rdependLine); String spaceLine = "space=quit"; if ( data.isUserInstallation() ) { spaceLine = "space=nocheck"; } adminFile.add(spaceLine); return adminFile; } private String getMainVersion (String version) { String mainVersion = null; int pos = version.indexOf(","); if ( pos > -1 ) { mainVersion = version.substring(0, pos); } return mainVersion; } private String getPackageRevision(String version) { String revision = null; int pos = version.indexOf("="); if ( pos > -1 ) { revision = version.substring(pos + 1, version.length() ); } return revision; } private Vector getVectorOfNumbers(String version) { Vector numbers = new Vector(); int pos = -1; // getting number from a string in format 2.0.0 do { pos = version.indexOf("."); if ( pos > -1 ) { String number = version.substring(0, pos); version = version.substring(pos + 1, version.length()); numbers.add(number); } } while ( pos > -1 ); numbers.add(version); return numbers; } private int getMinimum(int a, int b) { int minimum; if ( a < b ) { minimum = a; } else { minimum = b; } return minimum; } private String compareVersion(String firstVersion, String secondVersion) { // comparing strings with syntax 2.0.0 String comparison = "bothPackagesAreEqual"; Vector firstVector = getVectorOfNumbers(firstVersion); Vector secondVector = getVectorOfNumbers(secondVersion); int firstLength = firstVector.size(); int secondLength = secondVector.size(); int minimum = getMinimum(firstLength, secondLength); for (int i = 0; i < minimum; i++) { String firstS = (String)firstVector.get(i); String secondS = (String)secondVector.get(i); int first = Integer.parseInt(firstS); int second_ = Integer.parseInt(secondS); if ( second_ > first ) { comparison = "firstPackageIsOlder"; break; } else if ( second_ < first ) { comparison = "secondPackageIsOlder"; break; } } return comparison; } public void saveModulesLogFile(InstallData data) { if ( data.logModuleStates() ) { Vector logContent = LogManager.getModulesLogFile(); File baseDir = new File(data.getInstallDefaultDir(), data.getProductDir()); File uninstallDir = new File(baseDir, data.getUninstallDirName()); File modulesLogFile = new File(uninstallDir, "moduleSettingsLog.txt"); // System.err.println("Saving file: " + modulesLogFile.getPath()); SystemManager.saveCharFileVector(modulesLogFile.getPath(), logContent); } } public void removeSolarisLockFile() { String lockFileName = "/tmp/.ai.pkg.zone.lock-afdb66cf-1dd1-11b2-a049-000d560ddc3e"; File lockFile = new File(lockFileName); if ( lockFile.exists() ) { // System.err.println("Found file: " + lockFileName); boolean deleted = lockFile.delete(); } } public String getSolarisDatabasePath(InstallData data) { String databasePath = null; databasePath = data.getInstallDir(); return databasePath; } public void createAdminFile(boolean relocatable, boolean rdepends) { InstallData data = InstallData.getInstance(); Vector removeFiles = data.getRemoveFiles(); String adminFileName = ""; if ( relocatable ) { if ( rdepends ) { adminFileName = "adminFileReloc"; } else { adminFileName = "adminFileRelocNoDepends"; } } else { if ( rdepends ) { adminFileName = "adminFileNoReloc"; } else { adminFileName = "adminFileNoRelocNoDepends"; } } Vector fileContent = getAdminFileContent(relocatable, rdepends); File adminFile = new File(data.getInstallDir(), adminFileName); String completeAdminFileName = adminFile.getPath(); if ( relocatable ) { if ( rdepends ) { data.setAdminFileNameReloc(completeAdminFileName); } else { data.setAdminFileNameRelocNoDepends(completeAdminFileName); } } else { if ( rdepends ) { data.setAdminFileNameNoReloc(completeAdminFileName); } else { data.setAdminFileNameNoRelocNoDepends(completeAdminFileName); } } if ( ! adminFile.exists() ) { // only saving, if it did not exist SystemManager.saveCharFileVector(completeAdminFileName, fileContent); // only removing file in aborted installation, if it was created before removeFiles.add(completeAdminFileName); } // File dumpFile = new File(data.getInstallDir(), "dumpFile"); // String dumpFileName = dumpFile.getPath(); // SystemManager.dumpFile(adminFileName, dumpFileName); } // for user installations an environment hashmap is used public void setEnvironmentForUserInstall() { InstallData data = InstallData.getInstance(); HashMap env = SystemManager.getEnvironmentHashMap(); env.put("LD_PRELOAD_32", data.getGetUidPath()); data.setShellEnvironment(env); } public String getVersionString(Vector returnVector) { String versionString = null; String versionLine = null; for (int i = 0; i < returnVector.size(); i++) { String line = (String) returnVector.get(i); int pos = line.indexOf("REV="); if ( pos > -1 ) { versionLine = line; break; } } if ( versionLine != null ) { versionLine = versionLine.trim(); int pos = versionLine.lastIndexOf(" "); versionString = versionLine.substring(pos + 1, versionLine.length()); } return versionString; } public int getInstalledMinor(String version) { int minor = 0; int pos = version.indexOf("."); if ( pos > -1 ) { String reduced = version.substring(pos + 1, version.length()); pos = reduced.indexOf("."); if ( pos > -1 ) { reduced = reduced.substring(0, pos); minor = Integer.parseInt(reduced); } } return minor; } public boolean comparePackageVersions(String firstPackageVersion, String secondPackageVersion) { // Analyzing strings: version, 2.0.0,REV=106.2005.05.26 boolean firstPackageIsOlder = false; String comparison = null; String firstPackageMainVersion = getMainVersion(firstPackageVersion); // 2.0.0 String secondPackageMainVersion = getMainVersion(secondPackageVersion); // 2.0.0 if (( firstPackageMainVersion != null ) && ( secondPackageMainVersion != null )) { comparison = compareVersion(firstPackageMainVersion, secondPackageMainVersion); } if ( comparison.equals("firstPackageIsOlder") ) { firstPackageIsOlder = true; } else if ( comparison.equals("secondPackageIsOlder") ) { firstPackageIsOlder = false; } else if ( comparison.equals("bothPackagesAreEqual") ) { String firstPackageRevision = getPackageRevision(firstPackageVersion); // 106.2005.05.26 String secondPackageRevision = getPackageRevision(secondPackageVersion); // 106.2005.05.26 if (( firstPackageRevision != null ) && ( secondPackageRevision != null )) { comparison = compareVersion(firstPackageRevision, secondPackageRevision); if ( comparison.equals("firstPackageIsOlder") ) { firstPackageIsOlder = true; } else { firstPackageIsOlder = false; } } } // If version is equal, the patchlevel has to be analyzed // -> pkginfo does not offer this information // -> looking into file <root>/opt/var/sadm/pkg/<package>/pkginfo? return firstPackageIsOlder; } }
6,339
12,252
package org.keycloak.testsuite.dballocator.client.data; public class ReleaseResult { private final String uuid; private ReleaseResult(String uuid) { this.uuid = uuid; } public static ReleaseResult successful(String uuid) { return new ReleaseResult(uuid); } public String getUUID() { return uuid; } @Override public String toString() { return "ReleaseResult{" + "uuid='" + uuid + '\'' + '}'; } }
221