repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-sdk-net
aws
C#
using System; using System.Net; #if AWS_ASYNC_API using System.Threading.Tasks; #endif namespace Amazon.Runtime.SharedInterfaces { /// <summary> /// ICoreAmazonSTS is not meant to be used directly. It defines Security Token /// service with basic .NET types and allows other services to be able to use the service as /// a runtime dependency. This interface is implemented by the AmazonSecurityTokenServiceClient /// defined in the AWSSDK.SecurityToken assembly. /// </summary> public interface ICoreAmazonSTS { /// <summary> /// <para> /// This method is used internally to access the Amazon Security Token /// service within other service assemblies. /// Please use AmazonSecurityTokenServiceClient to access the Amazon Security Token /// service instead. /// </para> /// Use Amazon Security Token Service to assume a role. /// <remarks> /// Proxy settings that are required for the HTTPS and STS calls made during the authentication/credential /// generation process are supported and should have been configured on the STS ClientConfig instance /// associated with the STS client instance exposing this interface. /// </remarks> /// </summary> /// <param name="roleArn">The Amazon Resource Name (ARN) of the role to assume.</param> /// <param name="roleSessionName"> An identifier for the assumed role session.</param> /// <param name="options">Options to be used in the call to AssumeRole.</param> /// <returns></returns> AssumeRoleImmutableCredentials CredentialsFromAssumeRoleAuthentication(string roleArn, string roleSessionName, AssumeRoleAWSCredentialsOptions options); #if !BCL // In the NETSTANDARD flavors of the SDK ICoreAmazonSTS is declared without CredentialsFromSAMLAuthentication, } // we cannot add a new method to the interface for backward compatibility concerns. /// <summary> /// ICoreAmazonSTS_SAML is not meant to be used directly. It defines Security Token /// service with basic .NET types and allows other services to be able to use the service as /// a runtime dependency. This interface is implemented by the AmazonSecurityTokenServiceClient /// defined in the AWSSDK.SecurityToken assembly. /// </summary> public interface ICoreAmazonSTS_SAML { #endif /// <summary> /// <para> /// This method is used internally to access the Amazon Security Token /// service within other service assemblies. /// Please use AmazonSecurityTokenServiceClient to access the Amazon Security Token /// service instead. /// </para> /// Authenticates against a federated identity endpoint supporting SAML and returns /// temporary AWS credentials for the supplied role. /// </summary> /// <param name="endpoint">The endpoint for the federated identity provider</param> /// <param name="authenticationType">The authentication type to use (NTLM, Kerberos etc)</param> /// <param name="roleARN">The ARN of the role the user is to assume following authentication</param> /// <param name="credentialDuration">TTL duration for the generated credentials.</param> /// <param name="userCredential"> /// Optional; alternate user credential for authentication. If null the identity of the /// current process is used. /// </param> /// <returns>Generated credential data, including SAML-related information such as subject.</returns> /// <remarks> /// Proxy settings that are required for the HTTPS and STS calls made during the authentication/credential /// generation process are supported and should have been configured on the STS ClientConfig instance /// associated with the STS client instance exposing this interface. /// </remarks> SAMLImmutableCredentials CredentialsFromSAMLAuthentication(string endpoint, string authenticationType, string roleARN, TimeSpan credentialDuration, ICredentials userCredential); } public interface ICoreAmazonSTS_WebIdentity : IDisposable { /// <summary> /// <para> /// This method is used internally to access the Amazon Security Token /// service within other service assemblies. /// Please use AmazonSecurityTokenServiceClient to access the Amazon Security Token /// service instead. /// </para> /// Use Amazon Security Token Service to assume a role. /// <remarks> /// Proxy settings that are required for the HTTPS and STS calls made during the authentication/credential /// generation process are supported and should have been configured on the STS ClientConfig instance /// associated with the STS client instance exposing this interface. /// </remarks> /// </summary> /// <param name="webIdentityToken">The web identity token used to assume the role.</param> /// <param name="roleArn">The Amazon Resource Name (ARN) of the role to assume.</param> /// <param name="roleSessionName">An identifier for the assumed role session.</param> /// <param name="options">Options to be used in the call to AssumeRoleWithWebIdentity</param> /// <returns></returns> AssumeRoleImmutableCredentials CredentialsFromAssumeRoleWithWebIdentityAuthentication(string webIdentityToken, string roleArn, string roleSessionName, AssumeRoleWithWebIdentityCredentialsOptions options); #if AWS_ASYNC_API /// <summary> /// <para> /// This method is used internally to access the Amazon Security Token /// service within other service assemblies. /// Please use AmazonSecurityTokenServiceClient to access the Amazon Security Token /// service instead. /// </para> /// Use Amazon Security Token Service to assume a role. /// <remarks> /// Proxy settings that are required for the HTTPS and STS calls made during the authentication/credential /// generation process are supported and should have been configured on the STS ClientConfig instance /// associated with the STS client instance exposing this interface. /// </remarks> /// </summary> /// <param name="webIdentityToken">The web identity token used to assume the role.</param> /// <param name="roleArn">The Amazon Resource Name (ARN) of the role to assume.</param> /// <param name="roleSessionName">An identifier for the assumed role session.</param> /// <param name="options">Options to be used in the call to AssumeRoleWithWebIdentity</param> /// <returns></returns> Task<AssumeRoleImmutableCredentials> CredentialsFromAssumeRoleWithWebIdentityAuthenticationAsync(string webIdentityToken, string roleArn, string roleSessionName, AssumeRoleWithWebIdentityCredentialsOptions options); #endif } }
127
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Runtime.Internal; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; namespace Amazon.Runtime.SharedInterfaces.Internal { /// <summary> /// CoreAmazonKMS is not meant to use directly. It implements ICoreAmazonKMS /// and allows other service clients to be able to use the KMS service as a runtime dependency. /// /// This class waits until a method is actually called on the ICoreAmazonKMS interface /// before requiring the KMS assembly to be present and loaded. /// </summary> public class CoreAmazonKMS : ICoreAmazonKMS { private object wrappedClientLock = new object(); private ICoreAmazonKMS wrappedClient; private AmazonServiceClient existingClient; private string feature; private bool disposed = false; public CoreAmazonKMS(AmazonServiceClient existingClient, string feature) { this.existingClient = existingClient; this.feature = feature; } public byte[] Decrypt(byte[] ciphertextBlob, Dictionary<string, string> encryptionContext) { EnsureWrappedClientIsInstantiated(); return wrappedClient.Decrypt(ciphertextBlob, encryptionContext); } public GenerateDataKeyResult GenerateDataKey(string keyID, Dictionary<string, string> encryptionContext, string keySpec) { EnsureWrappedClientIsInstantiated(); return wrappedClient.GenerateDataKey(keyID, encryptionContext, keySpec); } #if AWS_ASYNC_API public async System.Threading.Tasks.Task<byte[]> DecryptAsync(byte[] ciphertextBlob, Dictionary<string, string> encryptionContext) { EnsureWrappedClientIsInstantiated(); return await wrappedClient.DecryptAsync(ciphertextBlob, encryptionContext).ConfigureAwait(false); } public async System.Threading.Tasks.Task<GenerateDataKeyResult> GenerateDataKeyAsync(string keyID, Dictionary<string, string> encryptionContext, string keySpec) { EnsureWrappedClientIsInstantiated(); return await wrappedClient.GenerateDataKeyAsync(keyID, encryptionContext, keySpec).ConfigureAwait(false); } #endif private void EnsureWrappedClientIsInstantiated() { if (wrappedClient == null) { lock (wrappedClientLock) { if (wrappedClient == null) { wrappedClient = CreateFromExistingClient(existingClient, feature); } } } } private static ICoreAmazonKMS CreateFromExistingClient(AmazonServiceClient existingClient, string feature) { ICoreAmazonKMS coreKMSClient = null; try { coreKMSClient = ServiceClientHelpers.CreateServiceFromAssembly<ICoreAmazonKMS>( ServiceClientHelpers.KMS_ASSEMBLY_NAME, ServiceClientHelpers.KMS_SERVICE_CLASS_NAME, existingClient); } catch (Exception e) { var msg = string.Format(CultureInfo.CurrentCulture, "Error instantiating {0} from assembly {1}. " + "The assembly and class must be available at runtime in order to use {2}.", ServiceClientHelpers.KMS_SERVICE_CLASS_NAME, ServiceClientHelpers.KMS_ASSEMBLY_NAME, feature); throw new InvalidOperationException(msg, e); } return coreKMSClient; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { lock (wrappedClientLock) { if (wrappedClient != null) { wrappedClient.Dispose(); wrappedClient = null; } } disposed = true; } } } }
136
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ namespace Amazon.Runtime.SharedInterfaces.Internal { /// <summary> /// Interface for an implementation of checksum algorithms /// </summary> public interface IChecksumProvider { /// <summary> /// Computes a CRC32 hash /// </summary> /// <param name="source">Data to hash</param> /// <returns>CRC32 hash as a base64-encoded string</returns> string Crc32(byte[] source); /// <summary> /// Computes a CRC32 hash /// </summary> /// <param name="source">Data to hash</param> /// <param name="previous">Previous value of a rolling checksum</param> /// <returns>Updated CRC32 hash as 32-bit integer</returns> uint Crc32(byte[] source, uint previous); /// <summary> /// Computes a CRC32C hash /// </summary> /// <param name="source">Data to hash</param> /// <returns>CRC32C hash as a base64-encoded string</returns> string Crc32C(byte[] source); /// <summary> /// Computes a CRC32C hash /// </summary> /// <param name="source">Data to hash</param> /// <param name="previous">Previous value of a rolling checksum</param> /// <returns>Updated CRC32C hash as 32-bit integer</returns> uint Crc32C(byte[] source, uint previous); } }
54
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Amazon.Runtime.SharedInterfaces { /// <summary> /// ICoreAmazonS3 is not meant to use directly. It defines S3 with basic .NET types /// and allows other services to be able to use S3 as a runtime dependency. This interface /// is implemented by the AmazonS3Client defined in the S3 assembly. /// </summary> public partial interface ICoreAmazonS3 { /// <summary> /// Get all the object keys for the particular bucket and key prefix. /// </summary> /// <param name="bucketName"></param> /// <param name="prefix"></param> /// <param name="additionalProperties"></param> /// <returns></returns> Task<IList<string>> GetAllObjectKeysAsync(string bucketName, string prefix, IDictionary<string, object> additionalProperties); /// <summary> /// Upload an object from a stream. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="stream"></param> /// <param name="additionalProperties"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task UploadObjectFromStreamAsync(string bucketName, string objectKey, Stream stream, IDictionary<string, object> additionalProperties, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an object. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="additionalProperties"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task DeleteAsync(string bucketName, string objectKey, IDictionary<string, object> additionalProperties, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an object. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKeys"></param> /// <param name="additionalProperties"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task DeletesAsync(string bucketName, IEnumerable<string> objectKeys, IDictionary<string, object> additionalProperties, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Open a stream to an object in S3. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="additionalProperties"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task<Stream> GetObjectStreamAsync(string bucketName, string objectKey, IDictionary<string, object> additionalProperties, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Upload an object from a file path. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="filepath"></param> /// <param name="additionalProperties"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task UploadObjectFromFilePathAsync(string bucketName, string objectKey, string filepath, IDictionary<string, object> additionalProperties, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Download an object in S3 to a file path. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="filepath"></param> /// <param name="additionalProperties"></param> /// <param name="cancellationToken"></param> /// <returns></returns> Task DownloadToFilePathAsync(string bucketName, string objectKey, string filepath, IDictionary<string, object> additionalProperties, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set the ACL on the object to public readable. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="enable"></param> Task MakeObjectPublicAsync(string bucketName, string objectKey, bool enable); /// <summary> /// Check to see if the bucket exists and if it doesn't create the bucket. /// </summary> /// <param name="bucketName"></param> Task EnsureBucketExistsAsync(string bucketName); /// <summary> /// Check to see if the bucket exists. /// </summary> /// <param name="bucketName"></param> /// <returns></returns> [Obsolete("This method is deprecated: its behavior is inconsistent and always uses HTTP. Please use Amazon.S3.Util.AmazonS3Util.DoesS3BucketExistV2Async instead.")] Task<bool> DoesS3BucketExistAsync(string bucketName); } }
113
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; namespace Amazon.Runtime.SharedInterfaces { /// <summary> /// ICoreAmazonS3 is not meant to use directly. It defines S3 with basic .NET types /// and allows other services to be able to use S3 as a runtime dependency. This interface /// is implemented by the AmazonS3Client defined in the S3 assembly. /// </summary> public partial interface ICoreAmazonS3 { /// <summary> /// Get all the object keys for the particular bucket and key prefix. /// </summary> /// <param name="bucketName"></param> /// <param name="prefix"></param> /// <param name="additionalProperties"></param> /// <returns></returns> IList<string> GetAllObjectKeys(string bucketName, string prefix, IDictionary<string, object> additionalProperties); /// <summary> /// Delete the object. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="additionalProperties"></param> void Delete(string bucketName, string objectKey, IDictionary<string, object> additionalProperties); /// <summary> /// Deletes the ojects. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKeys"></param> /// <param name="additionalProperties"></param> void Deletes(string bucketName, IEnumerable<string> objectKeys, IDictionary<string, object> additionalProperties); /// <summary> /// Upload an object from a stream. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="stream"></param> /// <param name="additionalProperties"></param> void UploadObjectFromStream(string bucketName, string objectKey, Stream stream, IDictionary<string, object> additionalProperties); /// <summary> /// Upload an object from a file path. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="filepath"></param> /// <param name="additionalProperties"></param> void UploadObjectFromFilePath(string bucketName, string objectKey, string filepath, IDictionary<string, object> additionalProperties); /// <summary> /// Download object to a file path. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="filepath"></param> /// <param name="additionalProperties"></param> void DownloadToFilePath(string bucketName, string objectKey, string filepath, IDictionary<string, object> additionalProperties); /// <summary> /// Get stream for an object. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="additionalProperties"></param> /// <returns></returns> Stream GetObjectStream(string bucketName, string objectKey, IDictionary<string, object> additionalProperties); /// <summary> /// Set the ACL on the object to public readable. /// </summary> /// <param name="bucketName"></param> /// <param name="objectKey"></param> /// <param name="enable"></param> void MakeObjectPublic(string bucketName, string objectKey, bool enable); /// <summary> /// Check to see if the bucket exists and if it doesn't create the bucket. /// </summary> /// <param name="bucketName"></param> void EnsureBucketExists(string bucketName); /// <summary> /// Check to see if the bucket exists. /// </summary> /// <param name="bucketName"></param> /// <returns></returns> bool DoesS3BucketExist(string bucketName); } }
101
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System.Collections.Generic; using System.Threading.Tasks; namespace Amazon.Runtime.SharedInterfaces { /// <summary> /// ICoreAmazonSSO is not meant to be used directly. It defines SSO /// service with basic .NET types and allows other services to be able to use the service as /// a runtime dependency. This interface is implemented by the AmazonSSOClient /// defined in the AWSSDK.SSO assembly. /// </summary> public interface ICoreAmazonSSO { #if BCL ImmutableCredentials CredentialsFromSsoAccessToken(string accountId, string roleName, string accessToken, IDictionary<string, object> additionalProperties); #endif #if AWS_ASYNC_API Task<ImmutableCredentials> CredentialsFromSsoAccessTokenAsync(string accountId, string roleName, string accessToken, IDictionary<string, object> additionalProperties); #endif } }
38
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Collections.Generic; #if AWS_ASYNC_API using System.Threading.Tasks; #endif namespace Amazon.Runtime.SharedInterfaces { /// <summary> /// ICoreAmazonSSOOIDC is not meant to be used directly. It defines SSO OIDC /// service with basic .NET types and allows other services to be able to use the service as /// a runtime dependency. This interface is implemented by the AmazonSSOOIDCClient /// defined in the AWSSDK.SSOOIDC assembly. /// </summary> public interface ICoreAmazonSSOOIDC { #if BCL /// <summary> /// This method is used internally to access the Amazon SSO OIDC service within other service assemblies. /// Please use AmazonSSOOIDCClient to access the Amazon SSO OIDC service instead. /// /// Use Amazon SSO OIDC to get an SSO Token /// </summary> GetSsoTokenResponse GetSsoToken(GetSsoTokenRequest getSsoTokenRequest); #endif #if AWS_ASYNC_API /// <summary> /// This method is used internally to access the Amazon SSO OIDC service within other service assemblies. /// Please use AmazonSSOOIDCClient to access the Amazon SSO OIDC service instead. /// /// Use Amazon SSO OIDC to get an SSO Token /// </summary> Task<GetSsoTokenResponse> GetSsoTokenAsync(GetSsoTokenRequest getSsoTokenRequest); #endif #if BCL /// <summary> /// This method is used internally to access the Amazon SSO OIDC service within other service assemblies. /// Please use AmazonSSOOIDCClient to access the Amazon SSO OIDC service instead. /// /// Use Amazon SSO OIDC to refresh <paramref name="previousResponse"/> /// </summary> GetSsoTokenResponse RefreshToken(GetSsoTokenResponse previousResponse); #endif #if AWS_ASYNC_API /// <summary> /// This method is used internally to access the Amazon SSO OIDC service within other service assemblies. /// Please use AmazonSSOOIDCClient to access the Amazon SSO OIDC service instead. /// /// Use Amazon SSO OIDC to refresh <paramref name="previousResponse"/> /// </summary> Task<GetSsoTokenResponse> RefreshTokenAsync(GetSsoTokenResponse previousResponse); #endif } public class GetSsoTokenRequest { /// <summary> /// Name of the application or system used during SSO client registration. /// </summary> public string ClientName { get; set; } /// <summary> /// OAuth client type /// </summary> public string ClientType { get; set; } /// <summary> /// The StartUrl to request an SSO Token from. /// </summary> public string StartUrl { get; set; } /// <summary> /// Callback for presenting the user with a SSO Login flow. /// </summary> public Action<SsoVerificationArguments> SsoVerificationCallback { get; set; } /// <summary> /// Additional properties to provide to the operation. /// Optional, can be null. /// </summary> public IDictionary<string, object> AdditionalProperties { get; set; } public IList<string> Scopes { get; set; } } public class GetSsoTokenResponse { /// <summary> /// The SSO login token that can be exchanged for temporary AWS credentials. /// </summary> public string AccessToken { get; set; } /// <summary> /// When <see cref="AccessToken"/> expires /// </summary> public DateTime ExpiresAt { get; set; } /// <summary> /// An opaque string returned by the sso-oidc service. /// </summary> public string RefreshToken { get; set; } /// <summary> /// The client ID generated when performing the registration portion of the OIDC authorization flow. /// The clientId is used alongside the <see cref="RefreshToken"/> to refresh the <see cref="AccessToken"/>. /// </summary> public string ClientId { get; set; } /// <summary> /// he client secret generated when performing the registration portion of the OIDC authorization flow. /// The <see cref="ClientSecret"/> is used alongside the <see cref="RefreshToken"/> to refresh the <see cref="AccessToken"/>. /// </summary> public string ClientSecret { get; set; } /// <summary> /// The expiration time of the client registration (<see cref="ClientId"/> and <see cref="ClientSecret"/>) as /// an RFC 3339 formatted timestamp. /// </summary> public string RegistrationExpiresAt { get; set; } /// <summary> /// The configured sso_region for the profile that credentials are being resolved for. /// This field is set as a convenience and is not directly used by the token provider but is useful in other contexts. /// Logic that requires the SSO region as part of the SSO token provider MUST use the SSO region configured on the profile /// and MUST NOT use the region in the cached token. /// </summary> public string Region { get; set; } /// <summary> /// The configured sso_start_url for the profile that credentials are being resolved for. /// This field is set as a convenience and is not directly used by the token provider but /// is useful in other contexts. Logic that requires the SSO start URL as part of the SSO /// token provider MUST use the SSO start URL configured on the profile and MUST NOT /// use the SSO start URL in the cached token. /// </summary> public string StartUrl { get; set; } } }
157
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Diagnostics; namespace Amazon.Runtime { /// <summary> /// Contains the metadata necessary for <see cref="BearerTokenSigner"/> to sign outgoing Api requests /// with an Authorization header. /// </summary> /// <remarks> /// This class is the focused public projection of the internal class /// <see cref="Amazon.Runtime.Credentials.Internal.SsoToken"/> /// </remarks> [DebuggerDisplay("{"+ nameof(Token) + "}")] public class AWSToken { public string Token { get; set; } public DateTime? ExpiresAt { get; set; } public override string ToString() { return Token; } } }
40
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System.Linq; #if AWS_ASYNC_API using System.Threading; using System.Threading.Tasks; #endif namespace Amazon.Runtime { /// <summary> /// Chain of <see cref="IAWSTokenProvider"/>. Providers are evaluated in order, and the /// first provider to return an <see cref="AWSToken"/> wins. /// </summary> public class AWSTokenProviderChain : IAWSTokenProvider { private readonly IAWSTokenProvider[] _chain; public AWSTokenProviderChain(params IAWSTokenProvider[] providers) { _chain = providers ?? new IAWSTokenProvider[0]; } #if BCL public bool TryResolveToken(out AWSToken token) { token = null; foreach (var provider in _chain) { if (provider.TryResolveToken(out token)) return true; } return false; } #endif #if AWS_ASYNC_API public async Task<TryResponse<AWSToken>> TryResolveTokenAsync(CancellationToken cancellationToken = default) { foreach (var provider in _chain) { var token = await provider.TryResolveTokenAsync(cancellationToken).ConfigureAwait(false); if (token.Success) return token; } return TryResponse<AWSToken>.Failure; } #endif } }
67
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; #if AWS_ASYNC_API using System.Threading; using System.Threading.Tasks; #endif namespace Amazon.Runtime { /// <summary> /// Combines the recommended <see cref="IAWSTokenProvider"/> into a <see cref="AWSTokenProviderChain"/>. /// <para /> /// Configuration parameters for each <see cref="IAWSTokenProvider"/> are exposed here to simplify configuration. /// <example> /// Example below demonstrates how to build a custom <see cref="DefaultAWSTokenProviderChain"/> in a /// <see cref="ClientConfig.AWSTokenProvider"/>. /// NOTE: The below example requires .NET 4.5 or above. /// <code> /// <![CDATA[ /// var exampleServiceClientConfig = new ExampleServiceClientConfig /// { /// AWSTokenProvider = new DefaultAWSTokenProviderChain /// { /// ProfileName = "my-sso-profile" /// } /// } /// ]]> /// </code> /// </example> /// </summary> public class DefaultAWSTokenProviderChain : IAWSTokenProvider { private readonly Lazy<IAWSTokenProvider> _chain; public DefaultAWSTokenProviderChain() { Func<IAWSTokenProvider> chainBuilder = () => new AWSTokenProviderChain( #if !BCL35 // ProfileTokenProvider doesn't support 3.5 new ProfileTokenProvider(ProfileName) #endif ); _chain = new Lazy<IAWSTokenProvider>(chainBuilder); } // default providers constructor parameters flattened to properties /// <summary> /// Used to initialize <see cref="ProfileTokenProvider"/>. /// </summary> public string ProfileName { get; set; } #if BCL public bool TryResolveToken(out AWSToken token) { return _chain.Value.TryResolveToken(out token); } #endif #if AWS_ASYNC_API public async Task<TryResponse<AWSToken>> TryResolveTokenAsync(CancellationToken cancellationToken = default) { return await _chain.Value.TryResolveTokenAsync(cancellationToken).ConfigureAwait(false); } #endif #if BCL35 private class Lazy<T> where T : class { private readonly Func<T> _builder; private object _lock = new object(); public Lazy(Func<T> builder) { _builder = builder; } private volatile T _value; public T Value { get { if (null != _value) return _value; lock (_lock) { if (null != _value) return _value; _value = _builder(); return _value; } } } } #endif } }
115
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #if AWS_ASYNC_API using System.Threading; using System.Threading.Tasks; #endif namespace Amazon.Runtime { /// <remarks> /// Any class that can provide a <see cref="AWSToken"/>. Intended to be consumed /// by <see cref="BearerTokenSigner"/> as part of signing. /// <para /> /// See <see cref="BearerTokenSigner"/> for more details. /// </remarks> public interface IAWSTokenProvider { #if BCL /// <summary> /// Attempts to load an <see cref="AWSToken"/>. /// <para /> /// NOTE: In some extreme circumstances, providers may throw an /// exception. /// </summary> bool TryResolveToken(out AWSToken token); #endif #if AWS_ASYNC_API /// <summary> /// Attempts to load an <see cref="AWSToken"/>. /// <para /> /// NOTE: In some extreme circumstances, providers may throw an /// exception. /// </summary> Task<TryResponse<AWSToken>> TryResolveTokenAsync(CancellationToken cancellationToken = default); #endif } }
51
aws-sdk-net
aws
C#
using System; #if AWS_ASYNC_API using System.Threading; using System.Threading.Tasks; #endif using Amazon.Util; namespace Amazon.Runtime { /// <inheritdoc cref="StaticTokenProvider(string, DateTime?)"/> public class StaticTokenProvider : IAWSTokenProvider { private readonly string _token; private readonly DateTime? _expiration; /// <summary> /// Creates a new <see cref="StaticTokenProvider"/> that can be assigned to /// <see cref="IClientConfig.AWSTokenProvider"/> or added to a <see cref="AWSTokenProviderChain"/>. /// </summary> /// <param name="token"> /// Bearer token to use to authorize AWS SDK requests. /// </param> /// <param name="expiration"> /// An optional <see cref="DateTime"/> in UTC for which <paramref name="token"/> will no longer be /// valid. Attempting to retrieve <paramref name="token"/> after <paramref name="expiration"/> will cause /// a <see cref="AmazonClientException"/> to be thrown. /// </param> public StaticTokenProvider(string token, DateTime? expiration = null) { _token = token; _expiration = expiration; } #if BCL public bool TryResolveToken(out AWSToken token) { if (IsTokenUnexpired()) { token = new AWSToken {Token = _token}; return true; } else { token = null; return false; } } #endif #if AWS_ASYNC_API public Task<TryResponse<AWSToken>> TryResolveTokenAsync(CancellationToken cancellationToken = default) { var isTokenUnexpired = IsTokenUnexpired(); return Task.FromResult( new TryResponse<AWSToken> { Success = isTokenUnexpired, Value = isTokenUnexpired ? new AWSToken { Token = _token } : null }); } #endif private bool IsTokenUnexpired() { #pragma warning disable CS0618 // Type or member is obsolete return (!_expiration.HasValue || _expiration.Value < AWSSDKUtils.CorrectedUtcNow); #pragma warning restore CS0618 // Type or member is obsolete } } }
72
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * */ using System; using System.Collections.Specialized; using System.ComponentModel; using System.Configuration; using Amazon.Util; using System.Xml; using System.IO; using System.Linq; using System.Collections.Generic; using System.Globalization; using System.Xml.Linq; namespace Amazon { /// <summary> /// Root AWS config section /// </summary> internal class AWSSection : ConfigurationSection { private const string loggingKey = "logging"; private const string defaultsKey = "defaults"; private const string endpointDefinitionKey = "endpointDefinition"; private const string regionKey = "region"; private const string proxy = "proxy"; private const string profileNameKey = "profileName"; private const string profilesLocationKey = "profilesLocation"; private const string correctForClockSkewKey = "correctForClockSkew"; private const string useSdkCacheKey = "useSdkCache"; private const string applicationNameKey = "applicationName"; private const string csmConfigKey = "csmConfig"; [ConfigurationProperty(loggingKey)] public LoggingSection Logging { get { return (LoggingSection)this[loggingKey]; } set { this[loggingKey] = value; } } [ConfigurationProperty(csmConfigKey)] public CSMSection CSMConfig { get { return (CSMSection)this[csmConfigKey]; } set { this[csmConfigKey] = value; } } [ConfigurationProperty(endpointDefinitionKey)] public string EndpointDefinition { get { return (string)this[endpointDefinitionKey]; } set { this[endpointDefinitionKey] = value; } } [ConfigurationProperty(regionKey)] public string Region { get { return (string)this[regionKey]; } set { this[regionKey] = value; } } [ConfigurationProperty(profileNameKey)] public string ProfileName { get { return (string)this[profileNameKey]; } set { this[profileNameKey] = value; } } [ConfigurationProperty(profilesLocationKey)] public string ProfilesLocation { get { return (string)this[profilesLocationKey]; } set { this[profilesLocationKey] = value; } } [ConfigurationProperty(useSdkCacheKey)] public bool? UseSdkCache { get { return (bool?)this[useSdkCacheKey]; } set { this[useSdkCacheKey] = value; } } [ConfigurationProperty(correctForClockSkewKey)] public bool? CorrectForClockSkew { get { return (bool?)this[correctForClockSkewKey]; } set { this[correctForClockSkewKey] = value; } } [ConfigurationProperty(applicationNameKey)] public string ApplicationName { get { return (string)this[applicationNameKey]; } set { this[applicationNameKey] = value; } } /// <summary> /// Gets and sets the proxy settings for the SDK to use. /// </summary> [ConfigurationProperty(proxy)] public ProxySection Proxy { get { return (ProxySection)this[proxy]; } set { this[proxy] = value; } } private IDictionary<string, XElement> _serviceSections = null; public IDictionary<string, XElement> ServiceSections { get { if (_serviceSections == null) _serviceSections = new Dictionary<string, XElement>(StringComparer.Ordinal); return _serviceSections; } set { _serviceSections = value; } } protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader) { var section = (XElement)XElement.ReadFrom(reader); ServiceSections[elementName] = section; return true; } internal string Serialize(string name) { try { string basicXml = this.SerializeSection(null, name, ConfigurationSaveMode.Full); XmlDocument doc = new XmlDocument(); doc.LoadXml(basicXml); using (var textWriter = new StringWriter(CultureInfo.InvariantCulture)) { CleanUpNodes(doc); doc.Save(textWriter); return textWriter.ToString(); } } catch (Exception e) { return e.ToString(); } } internal static void CleanUpNodes(XmlNode node) { foreach (XmlNode child in node.ChildNodes) { var toRemove = child.Attributes.Cast<XmlAttribute>().Where(at => string.IsNullOrEmpty(at.Value)).ToList(); foreach (var rem in toRemove) child.Attributes.Remove(rem); CleanUpNodes(child); } } public override bool IsReadOnly() { return false; } } #region Basic sections /// <summary> /// Settings for configuring a proxy for the SDK to use. /// </summary> internal class ProxySection : WritableConfigurationElement { private const string hostSectionKey = "host"; private const string portSectionKey = "port"; private const string usernameSectionKey = "username"; private const string passwordSectionKey = "password"; private const string bypasslistSectionKey = "bypassList"; private const string bypassOnLocalSectionKey = "bypassOnLocal"; private const char bypasslistSectionSeparator = ';'; /// <summary> /// Gets and sets the host name or IP address of the proxy server. /// </summary> [ConfigurationProperty(hostSectionKey)] public string Host { get { return (string)this[hostSectionKey]; } set { this[hostSectionKey] = value; } } /// <summary> /// Gets and sets the port number of the proxy. /// </summary> [ConfigurationProperty(portSectionKey)] public int? Port { get { return (int?)this[portSectionKey]; } set { this[portSectionKey] = value; } } /// <summary> /// Gets and sets the username to authenticate with the proxy server. /// </summary> [ConfigurationProperty(usernameSectionKey)] public string Username { get { return (string)this[usernameSectionKey]; } set { this[usernameSectionKey] = value; } } /// <summary> /// Gets and sets the password to authenticate with the proxy server. /// </summary> [ConfigurationProperty(passwordSectionKey)] public string Password { get { return (string)this[passwordSectionKey]; } set { this[passwordSectionKey] = value; } } /// <summary> /// Gets and set the proxy bypass list. A set of semi-colon /// delimited regular expressions denoting the addresses that /// should bypass the proxy. /// </summary> [ConfigurationProperty(bypasslistSectionKey)] public string[] BypassList { get { var bypassList = (string)this[bypasslistSectionKey]; if (string.IsNullOrEmpty(bypassList)) return new string[0]; return bypassList.Split(new char[] { bypasslistSectionSeparator }, StringSplitOptions.RemoveEmptyEntries); } set { this[bypasslistSectionKey] = value == null ? null : string.Join(bypasslistSectionSeparator.ToString(), value); } } /// <summary> /// Gets and sets the proxy option to bypass local addresses. /// </summary> [ConfigurationProperty(bypassOnLocalSectionKey)] public bool? BypassOnLocal { get { return (bool?)this[bypassOnLocalSectionKey]; } set { this[bypassOnLocalSectionKey] = value; } } } /// <summary> /// Logging section /// </summary> internal class LoggingSection : WritableConfigurationElement { private const string logToKey = "logTo"; private const string logResponsesKey = "logResponses"; private const string logResponsesSizeLimitKey = "logResponsesSizeLimit"; private const string logMetricsKey = "logMetrics"; private const string logMetricsFormatKey = "logMetricsFormat"; private const string logMetricsCustomFormatterKey = "logMetricsCustomFormatter"; [ConfigurationProperty(logToKey)] public LoggingOptions LogTo { get { return (LoggingOptions)this[logToKey]; } set { this[logToKey] = value; } } [ConfigurationProperty(logResponsesKey)] public ResponseLoggingOption LogResponses { get { return (ResponseLoggingOption)this[logResponsesKey]; } set { this[logResponsesKey] = value; } } [ConfigurationProperty(logResponsesSizeLimitKey)] public int? LogResponsesSizeLimit { get { return (int?)this[logResponsesSizeLimitKey]; } set { this[logResponsesKey] = value; } } [ConfigurationProperty(logMetricsKey)] public bool? LogMetrics { get { return (bool?)this[logMetricsKey]; } set { this[logMetricsKey] = value; } } [ConfigurationProperty(logMetricsFormatKey)] public LogMetricsFormatOption LogMetricsFormat { get { return (LogMetricsFormatOption)this[logMetricsFormatKey]; } set { this[logMetricsFormatKey] = value; } } [TypeConverter(typeof(TypeNameConverter))] [ConfigurationProperty(logMetricsCustomFormatterKey)] public Type LogMetricsCustomFormatter { get { return (Type)this[logMetricsCustomFormatterKey]; } set { this[logMetricsCustomFormatterKey] = value; } } } internal class CSMSection : WritableConfigurationElement { private const string csmEnabledKey = "csmEnabled"; private const string csmClientIdKey = "csmClientId"; private const string csmPortKey = "csmPort"; [ConfigurationProperty(csmEnabledKey)] public bool? CSMEnabled { get { return (bool)this[csmEnabledKey]; } set { this[csmEnabledKey] = value; } } [ConfigurationProperty(csmPortKey)] public int? CSMPort { get { return (int?)this[csmPortKey]; } set { this[csmPortKey] = value; } } [ConfigurationProperty(csmClientIdKey)] public string CSMClientId { get { return (string)this[csmClientIdKey]; } set { this[csmClientIdKey] = value; } } } #endregion #region Abstract helper classes /// <summary> /// Easy-to-use generic collection /// </summary> /// <typeparam name="T"></typeparam> public abstract class WritableConfigurationElementCollection<T> : ConfigurationElementCollection where T : SerializableConfigurationElement, new() { protected abstract string ItemPropertyName { get; } protected override ConfigurationElement CreateNewElement() { return new T(); } protected override ConfigurationElement CreateNewElement(string elementName) { return new T(); } protected override object GetElementKey(ConfigurationElement element) { return element; } protected override string ElementName { get { return string.Empty; } } protected override bool IsElementName(string elementName) { return (string.Equals(elementName, ItemPropertyName, StringComparison.Ordinal)); } public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMapAlternate; } } public override bool IsReadOnly() { return false; } protected WritableConfigurationElementCollection() : base() { } public void Add(T t) { this.BaseAdd(t); } public void Add(T[] ts) { foreach (var t in ts) { Add(t); } } protected override bool SerializeElement(XmlWriter writer, bool serializeCollectionKey) { if (writer == null) return base.SerializeElement(writer, serializeCollectionKey); for (int i = 0; i < this.Count; i++) { var item = BaseGet(i) as SerializableConfigurationElement; writer.WriteStartElement(ItemPropertyName); item.SerializeElement(writer, serializeCollectionKey); writer.WriteEndElement(); } return (Count > 0); } public List<T> Items { get { return this.Cast<T>().ToList(); } } } /// <summary> /// Configuration element that serializes properly when used with collections /// </summary> public abstract class SerializableConfigurationElement : WritableConfigurationElement { new public bool SerializeElement(XmlWriter writer, bool serializeCollectionKey) { return base.SerializeElement(writer, serializeCollectionKey); } } /// <summary> /// ConfigurationElement class which returns false for IsReadOnly /// </summary> public abstract class WritableConfigurationElement : ConfigurationElement { public override bool IsReadOnly() { return false; } } #endregion }
454
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Net; using Amazon.Util; using System.Globalization; using System.Collections.Generic; namespace Amazon.Runtime { /// <summary> /// This class is the base class of all the configurations settings to connect /// to a service. /// </summary> public abstract partial class ClientConfig { private string proxyHost; private int proxyPort = -1; private List<string> proxyBypassList; private int? connectionLimit; private int? maxIdleTime; private bool useNagleAlgorithm = false; private static RegionEndpoint GetDefaultRegionEndpoint() { return FallbackRegionFactory.GetRegionEndpoint(); } /// <summary> /// Gets and sets of the ProxyHost property. /// </summary> public string ProxyHost { get { if (string.IsNullOrEmpty(this.proxyHost)) return AWSConfigs.ProxyConfig.Host; return this.proxyHost; } set { this.proxyHost = value; } } /// <summary> /// Gets and sets the ProxyPort property. /// </summary> public int ProxyPort { get { if (this.proxyPort <= 0) return AWSConfigs.ProxyConfig.Port.GetValueOrDefault(); return this.proxyPort; } set { this.proxyPort = value; } } /// <summary> /// Gets and sets the ProxyBypassList property; a collection /// of regular expressions denoting the set of endpoints for /// which the configured proxy host will be bypassed. /// </summary> /// <remarks> /// For more information on bypass lists /// see https://msdn.microsoft.com/en-us/library/system.net.webproxy.bypasslist%28v=vs.110%29.aspx. /// </remarks> public List<string> ProxyBypassList { get { if (this.proxyBypassList == null) return AWSConfigs.ProxyConfig.BypassList; return this.proxyBypassList; } set { this.proxyBypassList = value != null ? new List<string>(value) : null; } } /// <summary> /// Gets and sets the ProxyBypassOnLocal property. /// If set true requests to local addresses bypass the configured /// proxy. /// </summary> public bool ProxyBypassOnLocal { get; set; } /// <summary> /// Returns a WebProxy instance configured to match the proxy settings /// in the client configuration. /// </summary> public WebProxy GetWebProxy() { const string httpPrefix = "http://"; WebProxy proxy = null; if (!string.IsNullOrEmpty(ProxyHost) && ProxyPort > 0) { // WebProxy constructor adds the http:// prefix, but doesn't // account for cases where it's already present which leads to // malformed addresses var host = ProxyHost.StartsWith(httpPrefix, StringComparison.OrdinalIgnoreCase) ? ProxyHost.Substring(httpPrefix.Length) : ProxyHost; proxy = new WebProxy(host, ProxyPort); if (ProxyCredentials != null) { proxy.Credentials = ProxyCredentials; } if (ProxyBypassList != null) { proxy.BypassList = ProxyBypassList.ToArray(); } proxy.BypassProxyOnLocal = ProxyBypassOnLocal; } return proxy; } /// <summary> /// Unpacks the host, port and any credentials info into the instance's /// proxy-related fields. /// </summary> /// <param name="proxy">The proxy details</param> public void SetWebProxy(WebProxy proxy) { if (proxy == null) throw new ArgumentNullException("proxy"); var address = proxy.Address; ProxyHost = address.Host; ProxyPort = address.Port; ProxyBypassList = new List<string>(proxy.BypassList); ProxyBypassOnLocal = proxy.BypassProxyOnLocal; ProxyCredentials = proxy.Credentials; } /// <summary> /// Gets and sets the max idle time set on the ServicePoint for the WebRequest. /// Default value is 50 seconds (50,000 ms) unless ServicePointManager.MaxServicePointIdleTime is set, /// in which case ServicePointManager.MaxServicePointIdleTime will be used as the default. /// </summary> public int MaxIdleTime { get { return AWSSDKUtils.GetMaxIdleTime(this.maxIdleTime); } set { this.maxIdleTime = value; } } /// <summary> /// Gets and sets the connection limit set on the ServicePoint for the WebRequest. /// Default value is 50 connections unless ServicePointManager.DefaultConnectionLimit is set in /// which case ServicePointManager.DefaultConnectionLimit will be used as the default. /// </summary> public int ConnectionLimit { get { return AWSSDKUtils.GetConnectionLimit(this.connectionLimit); } set { this.connectionLimit = value; } } /// <summary> /// Gets or sets a Boolean value that determines whether the Nagle algorithm is used on connections managed by the ServicePoint object used /// for requests to AWS. This is defaulted to false for lower latency with responses that return small amount of data. This is the opposite /// default than ServicePoint.UseNagleAlgorithm which is optimized for large responses like web pages or images. /// </summary> public bool UseNagleAlgorithm { get { return this.useNagleAlgorithm; } set { this.useNagleAlgorithm = value; } } } }
188
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Util.Internal.PlatformServices; using System.Collections.Generic; using System; using Amazon.Util.Internal; using System.IO; namespace Amazon.Runtime.Internal { /// <summary> /// This class composes Client Context header for Amazon Web Service client. /// It contains information like app title, version code, version name, client id, OS platform etc. /// </summary> public partial class ClientContext { private ClientContextConfig _config; public ClientContext(string appId, ClientContextConfig config) { _config = config; this.AppID = appId; this._custom = new Dictionary<string, string>(); if (string.IsNullOrEmpty(_clientID)) { string fullPath = InternalSDKUtils.DetermineAppLocalStoragePath(CLIENT_ID_CACHE_FILENAME); var directoryPath = InternalSDKUtils.DetermineAppLocalStoragePath(); lock (_lock) { if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } if (!System.IO.File.Exists(fullPath) || new System.IO.FileInfo(fullPath).Length == 0) { _clientID = Guid.NewGuid().ToString(); System.IO.File.WriteAllText(fullPath, _clientID); } else { using (System.IO.StreamReader file = new System.IO.StreamReader(fullPath)) { _clientID = file.ReadToEnd(); file.Close(); } } } } } } }
70
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System.Collections; using System; using Amazon.Util; using Amazon.Util.Internal; namespace Amazon.Runtime.Internal { /// <summary> /// Provides information for Client Context header. /// Client Context header needs information like App title, version code, version name, package name etc. /// </summary> public class ClientContextConfig { /// <summary> /// The title of your app. For example, "My App". /// If this property is not null, the value would be used in Client Context header. /// </summary> public string AppTitle { get; set; } /// <summary> /// The version for your app. For example, V3.0. /// If this property is not null, the value would be used in Client Context header. /// </summary> public string AppVersionName { get; set; } /// <summary> /// The version code of your app. For example, 3.0. /// If this property is not null, the value would be used in Client Context header. /// </summary> public string AppVersionCode { get; set; } /// <summary> /// The name of your app package. For example, com.your_company.your_app. /// If this property is not null, the value would be used in Client Context header. /// </summary> public string AppPackageName { get; set; } /// <summary> /// The operating system of the device. For example, iPhoneOS. /// If this property is not null, the value would be used in Client Context header. /// </summary> public string Platform { get; set; } /// <summary> /// The version of the operating system of the device. For example, 8.1. /// If this property is not null, the value would be used in Client Context header. /// </summary> public string PlatformVersion { get; set; } /// <summary> /// The locale of the device. For example, en_US. /// If this property is not null, the value would be used in Client Context header. /// </summary> public string Locale { get; set; } /// <summary> /// The manufacturer of the device. For example, Samsung. /// If this property is not null, the value would be used in Client Context header. /// </summary> public string Make { get; set; } /// <summary> /// The model of the device. For example, Nexus. /// If this property is not null, the value would be used in Client Context header. /// </summary> public string Model { get; set; } } }
85
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Text; using Amazon.Util; using Amazon.Runtime.Internal.Auth; namespace Amazon.Runtime { public partial interface IClientConfig { /// <summary> /// Gets the ProxyHost property. /// </summary> string ProxyHost { get; } /// <summary> /// Gets the ProxyPort property. /// </summary> int ProxyPort { get; } /// <summary> /// Gets the max idle time set on the ServicePoint for the WebRequest. /// Default value is 50 seconds (50,000 ms) unless ServicePointManager.MaxServicePointIdleTime is set, /// in which case ServicePointManager.MaxServicePointIdleTime will be used as the default. /// </summary> int MaxIdleTime { get; } /// <summary> /// Gets the default read-write timeout value. /// </summary> /// <seealso cref="P:System.Net.HttpWebRequest.ReadWriteTimeout"/> /// <seealso cref="P:System.Net.Http.WebRequestHandler.ReadWriteTimeout"/> TimeSpan? ReadWriteTimeout { get; } /// <summary> /// Gets the connection limit set on the ServicePoint for the WebRequest. /// Default value is 50 connections unless ServicePointManager.DefaultConnectionLimit is set in /// which case ServicePointManager.DefaultConnectionLimit will be used as the default. /// </summary> int ConnectionLimit { get; } /// <summary> /// Gets whether the Nagle algorithm is used on connections managed by the ServicePoint object used /// for requests to AWS. This is defaulted to false for lower latency with responses that return small amount of data. This is the opposite /// default than ServicePoint.UseNagleAlgorithm which is optimized for large responses like web pages or images. /// </summary> bool UseNagleAlgorithm { get; } /// <summary> /// Returns a WebProxy instance configured to match the proxy settings /// in the client configuration. /// </summary> WebProxy GetWebProxy(); } }
74
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; namespace Amazon.Runtime { /// <summary> /// TcpKeepAlive class used to group all the different properties used for working with TCP keep-alives. /// </summary> public class TcpKeepAlive { private bool enabled = false; private TimeSpan? timeout = new TimeSpan(0, 5, 0); private TimeSpan? interval = new TimeSpan(0, 0, 15); /// <summary> /// Specifies if TCP keep-alive is enabled or disabled. The default value is false for all services except Lambda. /// </summary> public bool Enabled { get { return enabled; } set { enabled = value; } } /// <summary> /// The timeout before a TCP keep-alive packet will be sent. The timeout value must be greater /// than 0 seconds and not null if Enabled is set to true. The default value is 5 minutes. /// </summary> public TimeSpan? Timeout { get { return timeout; } set { timeout = value; } } /// <summary> /// The interval before retrying a TCP keep-alive packet that did not receive an acknowledgement. The /// interval must be greater than 0 seconds and not null if Enabled is set to true. The default value is 15 seconds. /// </summary> public TimeSpan? Interval { get { return interval; } set { interval = value; } } } }
59
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Amazon.Runtime { /// <summary> /// Interface for enumerables consumed by the customer /// to read responses or result keys /// </summary> /// <typeparam name="TResult"></typeparam> public interface IPaginatedEnumerable<TResult> #if BCL : IEnumerable<TResult> #elif AWS_ASYNC_ENUMERABLES_API : IAsyncEnumerable<TResult> #endif { } }
24
aws-sdk-net
aws
C#
 using System.Collections.Generic; using System.Threading; namespace Amazon.Runtime { /// <summary> /// Interface for operation paginators /// </summary> /// <typeparam name="TResponse"></typeparam> public interface IPaginator<TResponse> { #if BCL IEnumerable<TResponse> Paginate(); #endif #if AWS_ASYNC_ENUMERABLES_API IAsyncEnumerable<TResponse> PaginateAsync(CancellationToken cancellationToken = default); #endif } }
21
aws-sdk-net
aws
C#
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Amazon.Runtime { /// <summary> /// An enumerable containing all of the responses for a paginated /// operation /// </summary> /// <typeparam name="TResponse"></typeparam> public class PaginatedResponse<TResponse> : IPaginatedEnumerable<TResponse> { private readonly IPaginator<TResponse> _paginator; /// <summary> /// Create a PaginatedResponse object by providing /// any operation paginator /// </summary> /// <param name="paginator"></param> public PaginatedResponse(IPaginator<TResponse> paginator) { this._paginator = paginator; } #if AWS_ASYNC_ENUMERABLES_API /// <summary> /// Get responses asynchronously /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public async IAsyncEnumerator<TResponse> GetAsyncEnumerator(CancellationToken cancellationToken = default) { await foreach (var response in _paginator.PaginateAsync().WithCancellation(cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); yield return response; } } #endif #if BCL /// <summary> /// Get responses synchronously /// </summary> /// <returns></returns> public IEnumerator<TResponse> GetEnumerator() { return _paginator.Paginate().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endif } }
59
aws-sdk-net
aws
C#
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Amazon.Runtime { /// <summary> /// An enumerable containing all of the Result Keys for a paginator /// </summary> /// <typeparam name="TResponse"></typeparam> /// <typeparam name="TResultKey"></typeparam> public class PaginatedResultKeyResponse<TResponse, TResultKey> : IPaginatedEnumerable<TResultKey> { private readonly IPaginator<TResponse> _paginator; private readonly Func<TResponse, IEnumerable<TResultKey>> _resultKeySelector; /// <summary> /// Create a PaginatedResultKeyResponse by providing any operation paginator /// and a selector function for the result key /// </summary> /// <param name="paginator"></param> /// <param name="resultKeySelector"></param> public PaginatedResultKeyResponse(IPaginator<TResponse> paginator, Func<TResponse, IEnumerable<TResultKey>> resultKeySelector) { this._paginator = paginator; this._resultKeySelector = resultKeySelector; } #if AWS_ASYNC_ENUMERABLES_API /// <summary> /// Get the result keys asynchronously /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public async IAsyncEnumerator<TResultKey> GetAsyncEnumerator(CancellationToken cancellationToken = default) { await foreach (var parent in _paginator.PaginateAsync().WithCancellation(cancellationToken).ConfigureAwait(false)) { foreach (var resultKey in _resultKeySelector(parent)) { cancellationToken.ThrowIfCancellationRequested(); yield return resultKey; } } } #endif #if BCL /// <summary> /// Get the result keys synchronously /// </summary> /// <returns></returns> public IEnumerator<TResultKey> GetEnumerator() { foreach (var parent in _paginator.Paginate()) { foreach (var i in _resultKeySelector(parent)) { yield return i; } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endif } }
73
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Runtime { public static class PaginatorUtils { public static void SetUserAgentAdditionOnRequest(AmazonWebServiceRequest request) { request.UserAgentAddition = $" Paginator"; } } }
15
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Runtime.CredentialManagement; using Amazon.Runtime.Credentials.Internal; using Amazon.Util; using Amazon.Util.Internal; #if AWS_ASYNC_API using System.Threading; using System.Threading.Tasks; #endif namespace Amazon.Runtime { /// <summary> /// Looks for a AWS Profile and then passes token resolution /// to <see cref="SSOTokenProvider"/>. /// <para /> /// This provider requires .NET 4.5 or newer. /// </summary> public class ProfileTokenProvider : IAWSTokenProvider { private readonly ISSOTokenProviderFactory _ssoTokenProviderFactory; private readonly ICredentialProfileSource _credentialProfileSource; private readonly string _profileName; public ProfileTokenProvider( ISSOTokenProviderFactory ssoTokenProviderFactory, ICredentialProfileSource credentialProfileSource, string profileName = null) { _ssoTokenProviderFactory = ssoTokenProviderFactory; _credentialProfileSource = credentialProfileSource; _profileName = profileName; } public ProfileTokenProvider(string profileName = null) : this( new SSOTokenProviderFactory( new SSOTokenFileCache( CryptoUtilFactory.CryptoInstance, new FileRetriever(), new DirectoryRetriever())), new CredentialProfileStoreChain(), profileName) { } #if BCL public bool TryResolveToken(out AWSToken token) { if (LoadAndValidateProfile(out var profile)) { return _ssoTokenProviderFactory.Build(profile).TryResolveToken(out token); } else { token = null; return false; } } #endif #if AWS_ASYNC_API public Task<TryResponse<AWSToken>> TryResolveTokenAsync(CancellationToken cancellationToken = default) { if (LoadAndValidateProfile(out var profile)) { return _ssoTokenProviderFactory.Build(profile).TryResolveTokenAsync(cancellationToken); } else { return Task.FromResult(TryResponse<AWSToken>.Failure); } } #endif /// <summary> /// Loads the <see cref="CredentialProfile"/> from <see cref="_credentialProfileSource"/> /// and runs some validation logic. /// <para /> /// NOTE: Per the Spec, this method can throw exceptions that should bubble up through /// <see cref="IAWSTokenProvider.TryResolveToken"/>. /// </summary> /// <returns> /// True if the profile has all necessary data points and should be further processed by /// <see cref="SSOTokenProvider"/>. /// </returns> private bool LoadAndValidateProfile(out CredentialProfile profile) { var profileName = !string.IsNullOrEmpty(_profileName) ? _profileName : FallbackCredentialsFactory.GetProfileName(); if (!_credentialProfileSource.TryGetProfile(profileName, out profile)) return false; if (string.IsNullOrEmpty(profile.Options.SsoSession)) // not a valid sso profile, it will be skipped return false; if (string.IsNullOrEmpty(profile.Options.SsoStartUrl)) { throw new AmazonClientException( $"Invalid Configuration. SSO Session [{profile.Options.SsoSession}] is missing sso_start_url."); } if (string.IsNullOrEmpty(profile.Options.SsoRegion)) { throw new AmazonClientException( $"Invalid Configuration. SSO Session [{profile.Options.SsoSession}] is missing sso_region."); } return true; } } }
129
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using Amazon.Runtime.Credentials.Internal; using Amazon.Runtime.Internal.Util; #if AWS_ASYNC_API using System.Threading; using System.Threading.Tasks; #endif namespace Amazon.Runtime { /// <summary> /// Looks in <see cref="_ssoCacheDirectory"/> for a file that matches /// <see cref="_sessionName"/> and then loads the SSO Token from that file. /// </summary> public class SSOTokenProvider : IAWSTokenProvider { private readonly ILogger _logger = Logger.GetLogger(typeof(SSOTokenProvider)); private readonly ISSOTokenManager _ssoTokenManager; private readonly string _sessionName; private readonly string _startUrl; private readonly string _region; private readonly string _ssoCacheDirectory; public SSOTokenProvider( ISSOTokenManager ssoTokenManager, string sessionName, string startUrl, string region, string ssoCacheDirectory = null) { if (string.IsNullOrWhiteSpace(sessionName)) throw new ArgumentNullException(nameof(sessionName)); if (string.IsNullOrWhiteSpace(startUrl)) throw new ArgumentNullException(nameof(startUrl)); if (string.IsNullOrEmpty(region)) throw new ArgumentNullException(nameof(region)); _ssoTokenManager = ssoTokenManager; _sessionName = sessionName; _startUrl = startUrl; _region = region; _ssoCacheDirectory = ssoCacheDirectory; } #if BCL public bool TryResolveToken(out AWSToken token) { token = null; try { var requestOptions = BuildSsoTokenManagerGetTokenOptions(); var ssoToken = _ssoTokenManager.GetToken(requestOptions); token = MapSsoTokenToAwsToken(ssoToken); return true; } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception e) #pragma warning restore CA1031 // Do not catch general exception types { _logger.Error(e, "Exception trying to resolve SSO Token"); // per the spec, rethrow SSOTokeManager exceptions so users // know if there is a problem with the cached sso token throw; } } #endif #if AWS_ASYNC_API public async Task<TryResponse<AWSToken>> TryResolveTokenAsync(CancellationToken cancellationToken = default) { try { var requestOptions = BuildSsoTokenManagerGetTokenOptions(); var ssoToken = await _ssoTokenManager.GetTokenAsync(requestOptions, cancellationToken).ConfigureAwait(false); return new TryResponse<AWSToken> { Success = true, Value = MapSsoTokenToAwsToken(ssoToken) }; } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception e) #pragma warning restore CA1031 // Do not catch general exception types { _logger.Error(e, "Exception trying to resolve SSO Token"); // per the spec, rethrow SSOTokeManager exceptions so users // know if there is a problem with the cached sso token throw; } } #endif private SSOTokenManagerGetTokenOptions BuildSsoTokenManagerGetTokenOptions() { var requestOptions = new SSOTokenManagerGetTokenOptions { Session = _sessionName, StartUrl = _startUrl, Region = _region, SupportsGettingNewToken = false }; if (!string.IsNullOrEmpty(_ssoCacheDirectory)) requestOptions.CacheFolderLocation = _ssoCacheDirectory; return requestOptions; } private AWSToken MapSsoTokenToAwsToken(SsoToken token) { return new AWSToken { Token = token.AccessToken, ExpiresAt = token.ExpiresAt }; } } }
144
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Runtime.CredentialManagement; using Amazon.Runtime.Credentials.Internal; using Amazon.Runtime.Internal; namespace Amazon.Runtime { /// <inheritdoc cref="Build"/> public interface ISSOTokenProviderFactory { /// <summary> /// Constructs a new <see cref="SSOTokenProvider"/> initialized by the passed <paramref name="profile"/>. /// </summary> SSOTokenProvider Build(CredentialProfile profile); } /// <inheritdoc /> public class SSOTokenProviderFactory : ISSOTokenProviderFactory { private readonly ISSOTokenFileCache _ssoTokenFileCache; public SSOTokenProviderFactory(ISSOTokenFileCache ssoTokenFileCache) { _ssoTokenFileCache = ssoTokenFileCache; } /// <inheritdoc /> public SSOTokenProvider Build(CredentialProfile profile) { return new SSOTokenProvider( new SSOTokenManager( SSOServiceClientHelpers.BuildSSOIDCClient( profile.Region), _ssoTokenFileCache), profile.Options.SsoSession, profile.Options.SsoStartUrl, profile.Options.SsoRegion); } } }
54
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Net; using Amazon.Util; using System.Globalization; using Amazon.Runtime.Internal.Util; using System.Net.Http; namespace Amazon.Runtime { /// <summary> /// This class is the base class of all the configurations settings to connect /// to a service. /// </summary> [CLSCompliant(false)] public abstract partial class ClientConfig { private IWebProxy proxy = null; private string proxyHost; private int proxyPort = -1; private static RegionEndpoint GetDefaultRegionEndpoint() { return FallbackRegionFactory.GetRegionEndpoint(); } /// <summary> /// Returns a WebProxy instance configured to match the proxy settings /// in the client configuration. /// </summary> public IWebProxy GetWebProxy() { return proxy; } /// <summary> /// Unpacks the host, port and any credentials info into the instance's /// proxy-related fields. /// Unlike the SetWebProxy implementation on .NET 3.5/4.5,the Host and the Port are not reconstructed from the /// input proxyuri /// </summary> /// <param name="proxy">The proxy details</param> public void SetWebProxy(IWebProxy proxy) { this.proxy = proxy; } /// <summary> /// Gets and sets of the ProxyHost property. /// </summary> public string ProxyHost { get { if (string.IsNullOrEmpty(this.proxyHost)) return AWSConfigs.ProxyConfig.Host; return this.proxyHost; } set { this.proxyHost = value; if (this.ProxyPort>0) { this.proxy = new Amazon.Runtime.Internal.Util.WebProxy(ProxyHost, ProxyPort); } } } /// <summary> /// Gets and sets of the ProxyPort property. /// </summary> public int ProxyPort { get { if (this.proxyPort <= 0) return AWSConfigs.ProxyConfig.Port.GetValueOrDefault(); return this.proxyPort; } set { this.proxyPort = value; if (this.ProxyHost!=null) { this.proxy = new Amazon.Runtime.Internal.Util.WebProxy(ProxyHost, ProxyPort); } } } /// <summary> /// Get or set the value to use for <see cref="HttpClientHandler.MaxConnectionsPerServer"/> on requests. /// If this property is null, <see cref="HttpClientHandler.MaxConnectionsPerServer"/> /// will be left at its default value of <see cref="int.MaxValue"/>. /// </summary> public int? MaxConnectionsPerServer { get; set; } /// <summary> /// HttpClientFactory used to create new HttpClients. /// If null, an HttpClient will be created by the SDK. /// Note that IClientConfig members such as ProxyHost, ProxyPort, GetWebProxy, and AllowAutoRedirect /// will have no effect unless they're used explicitly by the HttpClientFactory implementation. /// /// See https://docs.microsoft.com/en-us/xamarin/cross-platform/macios/http-stack?context=xamarin/ios and /// https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/http-stack?context=xamarin%2Fcross-platform&tabs=macos#ssltls-implementation-build-option /// for guidance on creating HttpClients for your platform. /// </summary> public HttpClientFactory HttpClientFactory { get; set; } = AWSConfigs.HttpClientFactory; /// <summary> /// Returns true if the clients should be cached by HttpRequestMessageFactory, false otherwise. /// </summary> /// <param name="clientConfig"></param> /// <returns></returns> internal static bool CacheHttpClients(IClientConfig clientConfig) { if (clientConfig.HttpClientFactory == null) return clientConfig.CacheHttpClient; else return clientConfig.HttpClientFactory.UseSDKHttpClientCaching(clientConfig); } /// <summary> /// Returns true if the SDK should dispose HttpClients after one use, false otherwise. /// </summary> /// <param name="clientConfig"></param> /// <returns></returns> internal static bool DisposeHttpClients(IClientConfig clientConfig) { if (clientConfig.HttpClientFactory == null) return !clientConfig.CacheHttpClient; else return clientConfig.HttpClientFactory.DisposeHttpClientsAfterUse(clientConfig); } /// <summary> /// Create a unique string used for caching the HttpClient based on the settings that are used from the ClientConfig that are set on the HttpClient. /// </summary> /// <param name="clientConfig"></param> /// <returns></returns> internal static string CreateConfigUniqueString(IClientConfig clientConfig) { if (clientConfig.HttpClientFactory != null) { return clientConfig.HttpClientFactory.GetConfigUniqueString(clientConfig); } string uniqueString = string.Empty; uniqueString = string.Concat("AllowAutoRedirect:", clientConfig.AllowAutoRedirect.ToString(), "CacheSize:", clientConfig.HttpClientCacheSize); if (clientConfig.Timeout.HasValue) uniqueString = string.Concat(uniqueString, "Timeout:", clientConfig.Timeout.Value.ToString()); if (clientConfig.MaxConnectionsPerServer.HasValue) uniqueString = string.Concat(uniqueString, "MaxConnectionsPerServer:", clientConfig.MaxConnectionsPerServer.Value.ToString()); return uniqueString; } /// <summary> /// Determines if HttpClients created with the given IClientConfig should be cached at the SDK /// client level, or cached globally. /// /// If there is no HttpClientFactory assigned and proxy or proxy credentials are set /// this returns false because those properties can't be serialized as part of the key in the global http client cache. /// </summary> internal static bool UseGlobalHttpClientCache(IClientConfig clientConfig) { if (clientConfig.HttpClientFactory == null) return clientConfig.ProxyCredentials == null && clientConfig.GetWebProxy() == null; else return clientConfig.HttpClientFactory.GetConfigUniqueString(clientConfig) != null; return clientConfig.ProxyCredentials == null; } } }
193
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Text; using Amazon.Util; using Amazon.Runtime.Internal.Auth; using System.Net.Http; namespace Amazon.Runtime { [CLSCompliant(false)] public partial interface IClientConfig { /// <summary> /// Gets the ProxyHost property. /// </summary> string ProxyHost { get; } /// <summary> /// Gets the ProxyPort property. /// </summary> int ProxyPort { get; } /// <summary> /// Returns a WebProxy instance configured to match the proxy settings /// in the client configuration. /// </summary> IWebProxy GetWebProxy(); /// <summary> /// HttpClientFactory used to create new HttpClients. /// If null, an HttpClient will be created by the SDK. /// Note that IClientConfig members such as ProxyHost, ProxyPort, GetWebProxy, and AllowAutoRedirect /// will have no effect unless they're used explicitly by the HttpClientFactory implementation. /// /// See https://docs.microsoft.com/en-us/xamarin/cross-platform/macios/http-stack?context=xamarin/ios and /// https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/http-stack?context=xamarin%2Fcross-platform&tabs=macos#ssltls-implementation-build-option /// for guidance on creating HttpClients for your platform. /// </summary> HttpClientFactory HttpClientFactory { get; } } }
58
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * */ using System; using System.Collections.Generic; using System.Xml.Linq; namespace Amazon.Util { #region Basic sections /// <summary> /// Settings for configuring a proxy for the SDK to use. /// </summary> public partial class ProxyConfig { /// <summary> /// The host name or IP address of the proxy server. /// </summary> public string Host { get; set; } /// <summary> /// The port number of the proxy. /// </summary> public int? Port { get; set; } /// <summary> /// The username to authenticate with the proxy server. /// </summary> public string Username { get; set; } /// <summary> /// The password to authenticate with the proxy server. /// </summary> public string Password { get; set; } /// <summary> /// Collection of one or more regular expressions denoting addresses /// for which the proxy will not be used. /// </summary> /// <remarks> /// For more information on bypass lists /// see https://msdn.microsoft.com/en-us/library/system.net.webproxy.bypasslist%28v=vs.110%29.aspx. /// </remarks> public List<string> BypassList { get; set; } /// <summary> /// If true requests to local addresses bypass the configured /// proxy. /// </summary> public bool BypassOnLocal { get; set; } internal ProxyConfig() { } } /// <summary> /// Settings for logging in the SDK. /// </summary> public partial class LoggingConfig { // Default limit for response logging is 1 KB. public static readonly int DefaultLogResponsesSizeLimit = 1024; private LoggingOptions _logTo; /// <summary> /// Logging destination. /// </summary> public LoggingOptions LogTo { get { return _logTo; } set { _logTo = value; AWSConfigs.OnPropertyChanged(AWSConfigs.LoggingDestinationProperty); } } /// <summary> /// When to log responses. /// </summary> public ResponseLoggingOption LogResponses { get; set; } /// <summary> /// Gets or sets the size limit in bytes for logged responses. /// If logging for response body is enabled, logged response /// body is limited to this size. The default limit is 1KB. /// </summary> public int LogResponsesSizeLimit { get; set; } /// <summary> /// Whether or not to log SDK metrics. /// </summary> public bool LogMetrics { get; set; } public LogMetricsFormatOption LogMetricsFormat { get; set; } /// <summary> /// A custom formatter added through Configuration /// </summary> public Amazon.Runtime.IMetricsFormatter LogMetricsCustomFormatter { get; set; } internal LoggingConfig() { LogTo = AWSConfigs._logging; LogResponses = AWSConfigs._responseLogging; LogResponsesSizeLimit = DefaultLogResponsesSizeLimit; LogMetrics = AWSConfigs._logMetrics; } } public partial class CSMConfig { internal const string DEFAULT_HOST = "127.0.0.1"; internal const int DEFAULT_PORT = 31000; public string CSMHost { get; set; } = DEFAULT_HOST; public int CSMPort { get; set; } = DEFAULT_PORT; public string CSMClientId { get; set; } public bool? CSMEnabled { get; set; } } #endregion }
148
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using Amazon.Runtime; using ThirdParty.Json.LitJson; namespace Amazon.Util { /// <summary> /// This class can be used to discover the public address ranges for AWS. The /// information is retrieved from the publicly accessible /// https://ip-ranges.amazonaws.com/ip-ranges.json file. /// </summary> /// <remarks> /// The information in this file is generated from our internal system-of-record and /// is authoritative. You can expect it to change several times per week and should /// poll accordingly. /// </remarks> public class AWSPublicIpAddressRanges { // The known-in-use service keys; the actual keys can be extended // over time. public const string AmazonServiceKey = "AMAZON"; public const string EC2ServiceKey = "EC2"; public const string CloudFrontServiceKey = "CLOUDFRONT"; public const string Route53ServiceKey = "ROUTE53"; public const string Route53HealthChecksServiceKey = "ROUTE53_HEALTHCHECKS"; /// <summary> /// Region identifier string for ROUTE53 and CLOUDFRONT ranges /// </summary> public const string GlobalRegionIdentifier = "GLOBAL"; #region Json parse keys const string createDateKey = "createDate"; const string ipv4PrefixesKey = "prefixes"; const string ipv4PrefixKey = "ip_prefix"; const string ipv6PrefixesKey = "ipv6_prefixes"; const string ipv6PrefixKey = "ipv6_prefix"; const string regionKey = "region"; const string serviceKey = "service"; private const string networkBorderGroupKey = "network_border_group"; const string createDateFormatString = "yyyy-MM-dd-HH-mm-ss"; #endregion /// <summary> /// Collection of service keys found in the data file. /// </summary> public IEnumerable<string> ServiceKeys { get { var keyHash = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var range in AllAddressRanges) { keyHash.Add(range.Service); } return keyHash; } } /// <summary> /// The publication date and time of the file that was downloaded and parsed. /// </summary> public DateTime CreateDate { get; private set; } /// <summary> /// Collection of all public IP ranges. /// </summary> public IEnumerable<AWSPublicIpAddressRange> AllAddressRanges { get; private set; } /// <summary> /// Filtered collection of public IP ranges for the given service key /// </summary> public IEnumerable<AWSPublicIpAddressRange> AddressRangesByServiceKey(string serviceKey) { if (!AllAddressRanges.Any()) throw new InvalidOperationException("No address range data has been loaded and parsed."); return AllAddressRanges.Where(ar => ar.Service.Equals(serviceKey, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Filtered collection of public IP ranges for the given region (us-east-1 etc) or GLOBAL. /// </summary> public IEnumerable<AWSPublicIpAddressRange> AddressRangesByRegion(string regionIdentifier) { if (!AllAddressRanges.Any()) throw new InvalidOperationException("No address range data has been loaded and parsed."); return AllAddressRanges.Where(ar => ar.Region.Equals(regionIdentifier, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Filtered collection of public IP ranges for the given network border group. /// </summary> public IEnumerable<AWSPublicIpAddressRange> AddressRangesByNetworkBorderGroup(string networkBorderGroup) { if (!AllAddressRanges.Any()) throw new InvalidOperationException("No address range data has been loaded and parsed."); return AllAddressRanges.Where(ar => ar.NetworkBorderGroup.Equals(networkBorderGroup, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Downloads the most recent copy of the endpoint address file and /// parses it to a collection of address range objects. /// </summary> public static AWSPublicIpAddressRanges Load() { return Load(null); } /// <summary> /// Downloads the most recent copy of the endpoint address file and /// parses it to a collection of address range objects. /// </summary> public static AWSPublicIpAddressRanges Load(IWebProxy proxy) { const int maxDownloadRetries = 3; var retries = 0; while (retries < maxDownloadRetries) { try { var content = AWSSDKUtils.DownloadStringContent(IpAddressRangeEndpoint, proxy); AWSPublicIpAddressRanges instance = Parse(content); return instance; } catch (Exception e) { retries++; if (retries == maxDownloadRetries) throw new AmazonServiceException( string.Format(CultureInfo.InvariantCulture, "Error downloading public IP address ranges file from {0}.", IpAddressRangeEndpoint), e); } var delay = (int) (Math.Pow(4, retries) * 100); delay = Math.Min(delay, 30 * 1000); AWSSDKUtils.Sleep(delay); } return null; } private static AWSPublicIpAddressRanges Parse(string fileContent) { try { var instance = new AWSPublicIpAddressRanges(); var json = JsonMapper.ToObject(new JsonReader(fileContent)); DateTime? creationDateTime = null; try { var createdAt = (string) json[createDateKey]; creationDateTime = DateTime.ParseExact(createdAt, createDateFormatString, null); } catch (FormatException) { } catch (ArgumentNullException) { } #pragma warning disable CS0612 // Type or member is obsolete instance.CreateDate = creationDateTime.GetValueOrDefault(AWSSDKUtils.CorrectedUtcNow); #pragma warning restore CS0612 // Type or member is obsolete // ipv4 and v6 addresses occupy different keys in the data file and can't easily be merged // so process each subset separately var parsedRanges = new List<AWSPublicIpAddressRange>(); var ipv4Ranges = json[ipv4PrefixesKey]; var ipv6Ranges = json[ipv6PrefixesKey]; if (!ipv4Ranges.IsArray || !ipv6Ranges.IsArray) throw new InvalidDataException("Expected array content for ip_prefixes and/or ipv6_prefixes keys."); parsedRanges.AddRange(ParseRange(ipv4Ranges, AWSPublicIpAddressRange.AddressFormat.Ipv4)); parsedRanges.AddRange(ParseRange(ipv6Ranges, AWSPublicIpAddressRange.AddressFormat.Ipv6)); instance.AllAddressRanges = parsedRanges; return instance; } catch (Exception e) { throw new InvalidDataException("IP address ranges content in unexpected/invalid format.", e); } } private static IEnumerable<AWSPublicIpAddressRange> ParseRange(JsonData ranges, AWSPublicIpAddressRange.AddressFormat addressFormat) { var prefixKey = addressFormat == AWSPublicIpAddressRange.AddressFormat.Ipv4 ? ipv4PrefixKey : ipv6PrefixKey; var parsedRanges = new List<AWSPublicIpAddressRange>(); parsedRanges.AddRange(from JsonData range in ranges select new AWSPublicIpAddressRange { IpAddressFormat = addressFormat, IpPrefix = (string) range[prefixKey], Region = (string) range[regionKey], Service = (string) range[serviceKey], NetworkBorderGroup = (string) range[networkBorderGroupKey] }); return parsedRanges; } private AWSPublicIpAddressRanges() { } private static readonly Uri IpAddressRangeEndpoint = new Uri("https://ip-ranges.amazonaws.com/ip-ranges.json"); } /// <summary> /// Represents the IP address range for a single region and service key. /// </summary> public class AWSPublicIpAddressRange { /// <summary> /// The public IPv4 or Ipv6 address range, in CIDR notation. /// </summary> public string IpPrefix { get; internal set; } public enum AddressFormat { Ipv4, Ipv6 } /// <summary> /// Indicates ipv4 or v6 format of the address /// </summary> public AddressFormat IpAddressFormat { get; internal set; } /// <summary> /// The AWS region or GLOBAL for edge locations. Note that the CLOUDFRONT and ROUTE53 /// ranges are GLOBAL. /// </summary> public string Region { get; internal set; } /// <summary> /// The subset of IP address ranges. Specify AMAZON to get all IP address ranges /// (for example, the ranges in the EC2 subset are also in the AMAZON subset). Note /// that some IP address ranges are only in the AMAZON subset. /// </summary> /// <remarks> /// Valid values for the service key include "AMAZON", "EC2", "ROUTE53", /// "ROUTE53_HEALTHCHECKS", and "CLOUDFRONT." If you need to know all of /// the ranges and don't care about the service, use the "AMAZON" entries. /// The other entries are subsets of this one. Also, some of the services, /// such as S3, are represented in "AMAZON" and do not have an entry that /// is specific to the service. We plan to add additional values over time; /// code accordingly! /// </remarks> public string Service { get; internal set; } /// <summary> /// The network border group the IP address range belongs to. /// </summary> /// <remarks> /// AWS Local Zones allow you to seamlessly connect to the full range of services in the AWS Region such /// as Amazon Simple Storage Service and Amazon DynamoDB through the same APIs and tool sets. You can extend /// your VPC Region by creating a new subnet that has a Local Zone assignment. When you create a subnet in /// a Local Zone, the VPC is also extended to that Local Zone. /// /// A network border group is a unique set of Availability Zones or Local Zones from where AWS advertises /// public IP addresses. /// /// When you create a VPC that has IPv6 addresses, you can choose to assign a set of Amazon-provided public /// IP addresses to the VPC and also set a network border group for the addresses that limits the addresses /// to the group. When you set a network border group, the IP addresses cannot move between network /// border groups. The us-west-2 network border group contains the four US West (Oregon) Availability Zones. /// The us-west-2-lax-1 network border group contains the Los Angeles Local Zones. /// </remarks> public string NetworkBorderGroup { get; internal set; } } }
293
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using Amazon.Runtime.Internal.Util; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Linq; using System.Net; using Amazon.Runtime.Internal; using Amazon.Runtime; using Amazon.Util.Internal; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Threading; #if AWS_ASYNC_API using System.Threading.Tasks; #endif #if NETSTANDARD using System.Net.Http; using System.Runtime.InteropServices; #endif namespace Amazon.Util { /// <summary> /// This class defines utilities and constants that can be used by /// all the client libraries of the SDK. /// </summary> public static partial class AWSSDKUtils { #region Internal Constants internal const string DefaultRegion = "us-east-1"; internal const string DefaultGovRegion = "us-gov-west-1"; private const char WindowsDirectorySeparatorChar = '\\'; private const char WindowsAltDirectorySeparatorChar = '/'; private const char WindowsVolumeSeparatorChar = ':'; private const char SlashChar = '/'; private const string Slash = "/"; private const string EncodedSlash = "%2F"; internal const int DefaultMaxRetry = 3; private const int DefaultConnectionLimit = 50; private const int DefaultMaxIdleTime = 50 * 1000; // 50 seconds private const int MaxIsSetMethodsCacheSize = 50; public static readonly DateTime EPOCH_START = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public const int DefaultBufferSize = 8192; // Default value of progress update interval for streaming is 100KB. public const long DefaultProgressUpdateInterval = 102400; internal static Dictionary<int, string> RFCEncodingSchemes = new Dictionary<int, string> { { 3986, ValidUrlCharacters }, { 1738, ValidUrlCharactersRFC1738 } }; internal const string S3Accelerate = "s3-accelerate"; internal const string S3Control = "s3-control"; private const int DefaultMarshallerVersion = 2; private static readonly string _userAgent = InternalSDKUtils.BuildUserAgentString(string.Empty); #endregion #region Public Constants /// <summary> /// The user agent string header /// </summary> public const string UserAgentHeader = "User-Agent"; /// <summary> /// The Set of accepted and valid Url characters per RFC3986. /// Characters outside of this set will be encoded. /// </summary> public const string ValidUrlCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; /// <summary> /// The Set of accepted and valid Url characters per RFC1738. /// Characters outside of this set will be encoded. /// </summary> public const string ValidUrlCharactersRFC1738 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_."; /// <summary> /// The set of accepted and valid Url path characters per RFC3986. /// </summary> private static string ValidPathCharacters = DetermineValidPathCharacters(); /// <summary> /// The set of characters which are not to be encoded as part of the X-Amzn-Trace-Id header values /// </summary> public const string ValidTraceIdHeaderValueCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=;:+&[]{}\"',"; // Checks which path characters should not be encoded // This set will be different for .NET 4 and .NET 4.5, as // per http://msdn.microsoft.com/en-us/library/hh367887%28v=vs.110%29.aspx private static string DetermineValidPathCharacters() { const string basePathCharacters = "/:'()!*[]$"; var sb = new StringBuilder(); foreach (var c in basePathCharacters) { var escaped = Uri.EscapeUriString(c.ToString()); if (escaped.Length == 1 && escaped[0] == c) sb.Append(c); } return sb.ToString(); } /// <summary> /// The string representing Url Encoded Content in HTTP requests /// </summary> public const string UrlEncodedContent = "application/x-www-form-urlencoded; charset=utf-8"; /// <summary> /// The GMT Date Format string. Used when parsing date objects /// </summary> public const string GMTDateFormat = "ddd, dd MMM yyyy HH:mm:ss \\G\\M\\T"; /// <summary> /// The ISO8601Date Format string. Used when parsing date objects /// </summary> public const string ISO8601DateFormat = "yyyy-MM-dd\\THH:mm:ss.fff\\Z"; /// <summary> /// The ISO8601Date Format string. Used when parsing date objects /// </summary> public const string ISO8601DateFormatNoMS = "yyyy-MM-dd\\THH:mm:ss\\Z"; /// <summary> /// The ISO8601 Basic date/time format string. Used when parsing date objects /// </summary> public const string ISO8601BasicDateTimeFormat = "yyyyMMddTHHmmssZ"; /// <summary> /// The ISO8601 basic date format. Used during AWS4 signature computation. /// </summary> public const string ISO8601BasicDateFormat = "yyyyMMdd"; /// <summary> /// The RFC822Date Format string. Used when parsing date objects /// </summary> public const string RFC822DateFormat = "ddd, dd MMM yyyy HH:mm:ss \\G\\M\\T"; #endregion #region Internal Methods /// <summary> /// Returns an extension of a path. /// This has the same behavior as System.IO.Path.GetExtension, but does not /// check the path for invalid characters. /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetExtension(string path) { if (path == null) return null; int length = path.Length; int index = length; while (--index >= 0) { char ch = path[index]; if (ch == '.') { if (index != length - 1) return path.Substring(index, length - index); else return string.Empty; } else if (IsPathSeparator(ch)) break; } return string.Empty; } // Checks if the character is one \ / : private static bool IsPathSeparator(char ch) { return (ch == '\\' || ch == '/' || ch == ':'); } /* * Determines the string to be signed based on the input parameters for * AWS Signature Version 2 */ internal static string CalculateStringToSignV2(ParameterCollection parameterCollection, string serviceUrl) { StringBuilder data = new StringBuilder("POST\n", 512); var sortedParameters = parameterCollection.GetSortedParametersList(); Uri endpoint = new Uri(serviceUrl); data.Append(endpoint.Host); data.Append("\n"); string uri = endpoint.AbsolutePath; if (uri == null || uri.Length == 0) { uri = "/"; } data.Append(AWSSDKUtils.UrlEncode(uri, true)); data.Append("\n"); foreach (KeyValuePair<string, string> pair in sortedParameters) { if (pair.Value != null) { data.Append(AWSSDKUtils.UrlEncode(pair.Key, false)); data.Append("="); data.Append(AWSSDKUtils.UrlEncode(pair.Value, false)); data.Append("&"); } } string result = data.ToString(); return result.Remove(result.Length - 1); } /** * Convert request parameters to Url encoded query string */ internal static string GetParametersAsString(IRequest request) { return GetParametersAsString(request.ParameterCollection); } /** * Convert Dictionary of parameters to Url encoded query string */ internal static string GetParametersAsString(ParameterCollection parameterCollection) { var sortedParameters = parameterCollection.GetSortedParametersList(); StringBuilder data = new StringBuilder(512); foreach (var kvp in sortedParameters) { var key = kvp.Key; var value = kvp.Value; if (value != null) { data.Append(key); data.Append('='); data.Append(AWSSDKUtils.UrlEncode(value, false)); data.Append('&'); } } string result = data.ToString(); if (result.Length == 0) return string.Empty; return result.Remove(result.Length - 1); } /// <summary> /// Returns the canonicalized resource path for the service endpoint with single URL encoded path segments. /// </summary> /// <param name="endpoint">Endpoint URL for the request</param> /// <param name="resourcePath">Resource path for the request</param> /// <remarks> /// If resourcePath begins or ends with slash, the resulting canonicalized /// path will follow suit. /// </remarks> /// <returns>Canonicalized resource path for the endpoint</returns> [Obsolete("Use CanonicalizeResourcePathV2 instead")] public static string CanonicalizeResourcePath(Uri endpoint, string resourcePath) { // This overload is kept for backward compatibility in existing code bases. return CanonicalizeResourcePath(endpoint, resourcePath, false, null, DefaultMarshallerVersion); } /// <summary> /// Returns the canonicalized resource path for the service endpoint /// </summary> /// <param name="endpoint">Endpoint URL for the request</param> /// <param name="resourcePath">Resource path for the request</param> /// <param name="detectPreEncode">If true pre URL encode path segments if necessary. /// S3 is currently the only service that does not expect pre URL encoded segments.</param> /// <remarks> /// If resourcePath begins or ends with slash, the resulting canonicalized /// path will follow suit. /// </remarks> /// <returns>Canonicalized resource path for the endpoint</returns> [Obsolete("Use CanonicalizeResourcePathV2 instead")] public static string CanonicalizeResourcePath(Uri endpoint, string resourcePath, bool detectPreEncode) { // This overload is kept for backward compatibility in existing code bases. return CanonicalizeResourcePath(endpoint, resourcePath, detectPreEncode, null, DefaultMarshallerVersion); } /// <summary> /// Returns the canonicalized resource path for the service endpoint /// </summary> /// <param name="endpoint">Endpoint URL for the request</param> /// <param name="resourcePath">Resource path for the request</param> /// <param name="detectPreEncode">If true pre URL encode path segments if necessary. /// S3 is currently the only service that does not expect pre URL encoded segments.</param> /// <param name="pathResources">Dictionary of key/value parameters containing the values for the ResourcePath key replacements</param> /// <param name="marshallerVersion">The version of the marshaller that constructed the request object.</param> /// <remarks> /// If resourcePath begins or ends with slash, the resulting canonicalized /// path will follow suit. /// </remarks> /// <returns>Canonicalized resource path for the endpoint</returns> [Obsolete("Use CanonicalizeResourcePathV2 instead")] public static string CanonicalizeResourcePath(Uri endpoint, string resourcePath, bool detectPreEncode, IDictionary<string, string> pathResources, int marshallerVersion) { if (endpoint != null) { var path = endpoint.AbsolutePath; if (string.IsNullOrEmpty(path) || string.Equals(path, Slash, StringComparison.Ordinal)) path = string.Empty; if (!string.IsNullOrEmpty(resourcePath) && resourcePath.StartsWith(Slash, StringComparison.Ordinal)) resourcePath = resourcePath.Substring(1); if (!string.IsNullOrEmpty(resourcePath)) path = path + Slash + resourcePath; resourcePath = path; } if (string.IsNullOrEmpty(resourcePath)) return Slash; IEnumerable<string> encodedSegments = AWSSDKUtils.SplitResourcePathIntoSegments(resourcePath, pathResources); var pathWasPreEncoded = false; if (detectPreEncode) { if (endpoint == null) throw new ArgumentNullException(nameof(endpoint), "A non-null endpoint is necessary to decide whether or not to pre URL encode."); // S3 is a special case. For S3 skip the pre encode. // For everything else URL pre encode the resource path segments. if (!S3Uri.IsS3Uri(endpoint)) { encodedSegments = encodedSegments.Select(segment => UrlEncode(segment, true).Replace(Slash, EncodedSlash)); pathWasPreEncoded = true; } } var canonicalizedResourcePath = AWSSDKUtils.JoinResourcePathSegments(encodedSegments, false); // Get the logger each time (it's cached) because we shouldn't store it in a static variable. Logger.GetLogger(typeof(AWSSDKUtils)).DebugFormat("{0} encoded {1}{2} for canonicalization: {3}", pathWasPreEncoded ? "Double" : "Single", resourcePath, endpoint == null ? "" : " with endpoint " + endpoint.AbsoluteUri, canonicalizedResourcePath); return canonicalizedResourcePath; } /// <summary> /// Returns the canonicalized resource path for the service endpoint. /// </summary> /// <param name="endpoint">Endpoint URL for the request.</param> /// <param name="resourcePath">Resource path for the request.</param> /// <param name="encode">If true will URL-encode path segments including "/". "S3" is currently the only service that does not expect pre URL-encoded segments.</param> /// <param name="pathResources">Dictionary of key/value parameters containing the values for the ResourcePath key replacements.</param> /// <remarks>If resourcePath begins or ends with slash, the resulting canonicalized path will follow suit.</remarks> /// <returns>Canonicalized resource path for the endpoint.</returns> public static string CanonicalizeResourcePathV2(Uri endpoint, string resourcePath, bool encode, IDictionary<string, string> pathResources) { if (endpoint != null) { var path = endpoint.AbsolutePath; if (string.IsNullOrEmpty(path) || string.Equals(path, Slash, StringComparison.Ordinal)) path = string.Empty; if (!string.IsNullOrEmpty(resourcePath) && resourcePath.StartsWith(Slash, StringComparison.Ordinal)) resourcePath = resourcePath.Substring(1); if (!string.IsNullOrEmpty(resourcePath)) path = path + Slash + resourcePath; resourcePath = path; } if (string.IsNullOrEmpty(resourcePath)) return Slash; IEnumerable<string> encodedSegments = AWSSDKUtils.SplitResourcePathIntoSegments(resourcePath, pathResources); var pathWasPreEncoded = false; if (encode) { if (endpoint == null) throw new ArgumentNullException(nameof(endpoint), "A non-null endpoint is necessary to decide whether or not to pre URL encode."); encodedSegments = encodedSegments.Select(segment => UrlEncode(segment, true).Replace(Slash, EncodedSlash)); pathWasPreEncoded = true; } var canonicalizedResourcePath = AWSSDKUtils.JoinResourcePathSegments(encodedSegments, false); // Get the logger each time (it's cached) because we shouldn't store it in a static variable. Logger.GetLogger(typeof(AWSSDKUtils)).DebugFormat("{0} encoded {1}{2} for canonicalization: {3}", pathWasPreEncoded ? "Double" : "Single", resourcePath, endpoint == null ? "" : " with endpoint " + endpoint.AbsoluteUri, canonicalizedResourcePath); return canonicalizedResourcePath; } /// <summary> /// Splits the resourcePath at / into segments then resolves any keys with the path resource values. Greedy /// key values will be split into multiple segments at each /. /// </summary> /// <param name="resourcePath">The patterned resourcePath</param> /// <param name="pathResources">The key/value lookup for the patterned resourcePath</param> /// <returns>A list of path segments where all keys in the resourcePath have been resolved to one or more path segment values</returns> public static IEnumerable<string> SplitResourcePathIntoSegments(string resourcePath, IDictionary<string, string> pathResources) { var splitChars = new char[] { SlashChar }; var pathSegments = resourcePath.Split(splitChars, StringSplitOptions.None); if(pathResources == null || pathResources.Count == 0) { return pathSegments; } //Otherwise there are key/values that need to be resolved var resolvedSegments = new List<string>(); foreach(var segment in pathSegments) { if (!pathResources.ContainsKey(segment)) { resolvedSegments.Add(segment); continue; } //Determine if the path is greedy. If greedy the segment will be split at each / into multiple segments. if (segment.EndsWith("+}", StringComparison.Ordinal)) { resolvedSegments.AddRange(pathResources[segment].Split(splitChars, StringSplitOptions.None)); } else { resolvedSegments.Add(pathResources[segment]); } } return resolvedSegments; } /// <summary> /// Joins all path segments with the / character and encodes each segment before joining. /// </summary> /// <param name="pathSegments">The segments of a URL path split at each / character</param> /// <param name="path">If the path property is specified, /// the accepted path characters {/+:} are not encoded.</param> /// <returns>A joined URL with encoded segments</returns> public static string JoinResourcePathSegments(IEnumerable<string> pathSegments, bool path) { // Encode for canonicalization pathSegments = pathSegments.Select(segment => UrlEncode(segment, path)); if (path) { pathSegments = pathSegments.Select(segment => segment.Replace(Slash, EncodedSlash)); } // join the encoded segments with / return string.Join(Slash, pathSegments.ToArray()); } /// <summary> /// Takes a patterned resource path and resolves it using the key/value path resources into /// a segmented encoded URL. /// </summary> /// <param name="resourcePath">The patterned resourcePath</param> /// <param name="pathResources">The key/value lookup for the patterned resourcePath</param> /// <returns>A segmented encoded URL</returns> public static string ResolveResourcePath(string resourcePath, IDictionary<string, string> pathResources) { return ResolveResourcePath(resourcePath, pathResources, true); } /// <summary> /// Takes a patterned resource path and resolves it using the key/value path resources into /// a segmented encoded URL. /// </summary> /// <param name="resourcePath">The patterned resourcePath</param> /// <param name="pathResources">The key/value lookup for the patterned resourcePath</param> /// <param name="skipEncodingValidPathChars">If true valid path characters {/+:} are not encoded</param> /// <returns>A segmented encoded URL</returns> public static string ResolveResourcePath(string resourcePath, IDictionary<string, string> pathResources, bool skipEncodingValidPathChars) { if (string.IsNullOrEmpty(resourcePath)) { return resourcePath; } return JoinResourcePathSegments(SplitResourcePathIntoSegments(resourcePath, pathResources), skipEncodingValidPathChars); } /// <summary> /// Returns a new string created by joining each of the strings in the /// specified list together, with a comma between them. /// </summary> /// <parma name="strings">The list of strings to join into a single, comma delimited /// string list.</parma> /// <returns> A new string created by joining each of the strings in the /// specified list together, with a comma between strings.</returns> public static String Join(List<String> strings) { StringBuilder result = new StringBuilder(); Boolean first = true; foreach (String s in strings) { if (!first) result.Append(", "); result.Append(s); first = false; } return result.ToString(); } /// <summary> /// Attempt to infer the region for a service request based on the endpoint /// </summary> /// <param name="url">Endpoint to the service to be called</param> /// <returns> /// Region parsed from the endpoint; DefaultRegion (or DefaultGovRegion) /// if it cannot be determined/is not explicit /// </returns> public static string DetermineRegion(string url) { var regionEndpoint = RegionFinder.Instance.FindRegion(url); return regionEndpoint?.RegionName; } /// <summary> /// Attempt to infer the service name for a request (in short form, eg 'iam') from the /// service endpoint. /// </summary> /// <param name="url">Endpoint to the service to be called</param> /// <returns> /// Short-form name of the service parsed from the endpoint; empty string if it cannot /// be determined /// </returns> public static string DetermineService(string url) { int delimIndex = url.IndexOf("//", StringComparison.Ordinal); if (delimIndex >= 0) url = url.Substring(delimIndex + 2); string[] urlParts = url.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (urlParts == null || urlParts.Length == 0) return string.Empty; string servicePart = urlParts[0]; int hyphenated = servicePart.IndexOf('-'); string service; if (hyphenated < 0) { service = servicePart; } else { service = servicePart.Substring(0, hyphenated); } // Check for SQS : return "sqs" incase service is determined to be "queue" as per the URL. if (service.Equals("queue")) { return "sqs"; } else { return service; } } /// <summary> /// Utility method for converting Unix epoch seconds to DateTime structure. /// </summary> /// <param name="seconds">The number of seconds since January 1, 1970.</param> /// <returns>Converted DateTime structure</returns> public static DateTime ConvertFromUnixEpochSeconds(int seconds) { return new DateTime(seconds * 10000000L + EPOCH_START.Ticks, DateTimeKind.Utc).ToLocalTime(); } /// <summary> /// Utility method for converting Unix epoch milliseconds to DateTime structure. /// </summary> /// <param name="milliseconds">The number of milliseconds since January 1, 1970.</param> /// <returns>Converted DateTime structure</returns> public static DateTime ConvertFromUnixEpochMilliseconds(long milliseconds) { return new DateTime(milliseconds * 10000L + EPOCH_START.Ticks, DateTimeKind.Utc).ToLocalTime(); } public static int ConvertToUnixEpochSeconds(DateTime dateTime) { return Convert.ToInt32(GetTimeSpanInTicks(dateTime).TotalSeconds); } public static string ConvertToUnixEpochSecondsString(DateTime dateTime) { return Convert.ToInt64(GetTimeSpanInTicks(dateTime).TotalSeconds).ToString(CultureInfo.InvariantCulture); } [Obsolete("This method isn't named correctly: it returns seconds instead of milliseconds. Use ConvertToUnixEpochSecondsDouble instead.", false)] public static double ConvertToUnixEpochMilliSeconds(DateTime dateTime) { return ConvertToUnixEpochSecondsDouble(dateTime); } public static double ConvertToUnixEpochSecondsDouble(DateTime dateTime) { return Math.Round(GetTimeSpanInTicks(dateTime).TotalMilliseconds, 0) / 1000.0; } public static TimeSpan GetTimeSpanInTicks(DateTime dateTime) { return new TimeSpan(dateTime.ToUniversalTime().Ticks - EPOCH_START.Ticks); } public static long ConvertDateTimetoMilliseconds(DateTime dateTime) { return ConvertTimeSpanToMilliseconds(GetTimeSpanInTicks(dateTime)); } public static long ConvertTimeSpanToMilliseconds(TimeSpan timeSpan) { return timeSpan.Ticks / TimeSpan.TicksPerMillisecond; } /// <summary> /// Helper function to format a byte array into string /// </summary> /// <param name="data">The data blob to process</param> /// <param name="lowercase">If true, returns hex digits in lower case form</param> /// <returns>String version of the data</returns> public static string ToHex(byte[] data, bool lowercase) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sb.Append(data[i].ToString(lowercase ? "x2" : "X2", CultureInfo.InvariantCulture)); } return sb.ToString(); } /// <summary> /// Calls a specific EventHandler in a background thread /// </summary> /// <param name="handler"></param> /// <param name="args"></param> /// <param name="sender"></param> public static void InvokeInBackground<T>(EventHandler<T> handler, T args, object sender) where T : EventArgs { if (handler == null) return; var list = handler.GetInvocationList(); foreach (var call in list) { var eventHandler = ((EventHandler<T>)call); if (eventHandler != null) { Dispatcher.Dispatch(() => eventHandler(sender, args)); } } } private static BackgroundInvoker _dispatcher; private static BackgroundInvoker Dispatcher { get { if (_dispatcher == null) { _dispatcher = new BackgroundInvoker(); } return _dispatcher; } } /// <summary> /// Parses a query string of a URL and returns the parameters as a string-to-string dictionary. /// </summary> /// <param name="url"></param> /// <returns></returns> public static Dictionary<string, string> ParseQueryParameters(string url) { Dictionary<string, string> parameters = new Dictionary<string, string>(); if (!string.IsNullOrEmpty(url)) { int queryIndex = url.IndexOf('?'); if (queryIndex >= 0) { string queryString = url.Substring(queryIndex + 1); string[] kvps = queryString.Split(new char[] { '&' }, StringSplitOptions.None); foreach (string kvp in kvps) { if (string.IsNullOrEmpty(kvp)) continue; string[] nameValuePair = kvp.Split(new char[] { '=' }, 2); string name = nameValuePair[0]; string value = nameValuePair.Length == 1 ? null : nameValuePair[1]; parameters[name] = value; } } } return parameters; } internal static bool AreEqual(object[] itemsA, object[] itemsB) { if (itemsA == null || itemsB == null) return (itemsA == itemsB); if (itemsA.Length != itemsB.Length) return false; var length = itemsA.Length; for (int i = 0; i < length; i++) { var a = itemsA[i]; var b = itemsB[i]; if (!AreEqual(a, b)) return false; } return true; } internal static bool AreEqual(object a, object b) { if (a == null || b == null) return (a == b); if (object.ReferenceEquals(a, b)) return true; return (a.Equals(b)); } internal static bool DictionariesAreEqual<K,V>(Dictionary<K, V> a, Dictionary<K, V> b) { if (a == null || b == null) return (a == b); if (object.ReferenceEquals(a, b)) return true; return a.Count == b.Count && !a.Except(b).Any(); } /// <summary> /// Utility method for converting a string to a MemoryStream. /// </summary> /// <param name="s"></param> /// <returns></returns> public static MemoryStream GenerateMemoryStreamFromString(string s) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(s); writer.Flush(); stream.Position = 0; return stream; } /// <summary> /// Utility method for copy the contents of the source stream to the destination stream. /// </summary> /// <param name="source"></param> /// <param name="destination"></param> public static void CopyStream(Stream source, Stream destination) { CopyStream(source, destination, DefaultBufferSize); } /// <summary> /// Utility method for copy the contents of the source stream to the destination stream. /// </summary> /// <param name="source"></param> /// <param name="destination"></param> /// <param name="bufferSize"></param> public static void CopyStream(Stream source, Stream destination, int bufferSize) { if (source == null) throw new ArgumentNullException("source"); if (destination == null) throw new ArgumentNullException("destination"); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize"); byte[] array = new byte[bufferSize]; int count; while ((count = source.Read(array, 0, array.Length)) != 0) { destination.Write(array, 0, count); } } #endregion #region Public Methods and Properties /// <summary> /// Formats the current date as a GMT timestamp /// </summary> /// <returns>A GMT formatted string representation /// of the current date and time /// </returns> public static string FormattedCurrentTimestampGMT { get { #pragma warning disable CS0618 // Type or member is obsolete DateTime dateTime = AWSSDKUtils.CorrectedUtcNow; #pragma warning restore CS0618 // Type or member is obsolete return dateTime.ToString(GMTDateFormat, CultureInfo.InvariantCulture); } } /// <summary> /// Formats the current date as ISO 8601 timestamp /// </summary> /// <returns>An ISO 8601 formatted string representation /// of the current date and time /// </returns> public static string FormattedCurrentTimestampISO8601 { get { return GetFormattedTimestampISO8601(0); } } /// <summary> /// Gets the ISO8601 formatted timestamp that is minutesFromNow /// in the future. /// </summary> /// <param name="minutesFromNow">The number of minutes from the current instant /// for which the timestamp is needed.</param> /// <returns>The ISO8601 formatted future timestamp.</returns> public static string GetFormattedTimestampISO8601(int minutesFromNow) { #pragma warning disable CS0618 // Type or member is obsolete return GetFormattedTimestampISO8601(AWSSDKUtils.CorrectedUtcNow.AddMinutes(minutesFromNow)); #pragma warning restore CS0618 // Type or member is obsolete } internal static string GetFormattedTimestampISO8601(IClientConfig config) { return GetFormattedTimestampISO8601(config.CorrectedUtcNow); } private static string GetFormattedTimestampISO8601(DateTime dateTime) { DateTime formatted = new DateTime( dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, DateTimeKind.Local ); return formatted.ToString( AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture ); } /// <summary> /// Formats the current date as ISO 8601 timestamp /// </summary> /// <returns>An ISO 8601 formatted string representation /// of the current date and time /// </returns> public static string FormattedCurrentTimestampRFC822 { get { return GetFormattedTimestampRFC822(0); } } /// <summary> /// Gets the RFC822 formatted timestamp that is minutesFromNow /// in the future. /// </summary> /// <param name="minutesFromNow">The number of minutes from the current instant /// for which the timestamp is needed.</param> /// <returns>The ISO8601 formatted future timestamp.</returns> public static string GetFormattedTimestampRFC822(int minutesFromNow) { #pragma warning disable CS0612 // Type or member is obsolete DateTime dateTime = AWSSDKUtils.CorrectedUtcNow.AddMinutes(minutesFromNow); #pragma warning restore CS0612 // Type or member is obsolete return dateTime.ToString(AWSSDKUtils.RFC822DateFormat, CultureInfo.InvariantCulture); } /// <summary> /// Determines whether the given string is an absolute path to a root. /// </summary> /// <param name="path">The hypothetical absolute path.</param> /// <returns>True if <paramref name="path"/> is an absolute path.</returns> public static bool IsAbsolutePath(string path) { return IsWindows() ? !IsPartiallyQualifiedForWindows(path) : Path.IsPathRooted(path); } private static bool IsWindows() { #if NETSTANDARD return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); #endif return true; } #region The code in this region has been minimally adapted from Microsoft's PathInternal.Windows.cs class as of 11/19/2019. The logic remains the same. /// <summary> /// Returns true if the path specified is relative to the current drive or working directory. /// Returns false if the path is fixed to a specific drive or UNC path. This method does no /// validation of the path (URIs will be returned as relative as a result). /// </summary> /// <remarks> /// Handles paths that use the alternate directory separator. It is a frequent mistake to /// assume that rooted paths (Path.IsPathRooted) are not relative. This isn't the case. /// "C:a" is drive relative- meaning that it will be resolved against the current directory /// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory /// will not be used to modify the path). /// </remarks> private static bool IsPartiallyQualifiedForWindows(string path) { if (path.Length < 2) { // It isn't fixed, it must be relative. There is no way to specify a fixed // path with one character (or less). return true; } if (IsWindowsDirectorySeparator(path[0])) { // There is no valid way to specify a relative path with two initial slashes or // \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\ return !(path[1] == '?' || IsWindowsDirectorySeparator(path[1])); } // The only way to specify a fixed path that doesn't begin with two slashes // is the drive, colon, slash format- i.e. C:\ return !((path.Length >= 3) && (path[1] == WindowsVolumeSeparatorChar) && IsWindowsDirectorySeparator(path[2]) // To match old behavior we'll check the drive character for validity as the path is technically // not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream. && IsValidWindowsDriveChar(path[0])); } /// <summary> /// True if the given character is a directory separator. /// </summary> private static bool IsWindowsDirectorySeparator(char c) { return c == WindowsDirectorySeparatorChar || c == WindowsAltDirectorySeparatorChar; } /// <summary> /// Returns true if the given character is a valid drive letter /// </summary> private static bool IsValidWindowsDriveChar(char value) { return (value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z'); } #endregion The code in this region has been minimally adapted from Microsoft's PathInternal.Windows.cs class as of 11/19/2019. The logic remains the same. /// <summary> /// URL encodes a string per RFC3986. If the path property is specified, /// the accepted path characters {/+:} are not encoded. /// </summary> /// <param name="data">The string to encode</param> /// <param name="path">Whether the string is a URL path or not</param> /// <returns>The encoded string</returns> public static string UrlEncode(string data, bool path) { return UrlEncode(3986, data, path); } /// <summary> /// URL encodes a string per the specified RFC. If the path property is specified, /// the accepted path characters {/+:} are not encoded. /// </summary> /// <param name="rfcNumber">RFC number determing safe characters</param> /// <param name="data">The string to encode</param> /// <param name="path">Whether the string is a URL path or not</param> /// <returns>The encoded string</returns> /// <remarks> /// Currently recognised RFC versions are 1738 (Dec '94) and 3986 (Jan '05). /// If the specified RFC is not recognised, 3986 is used by default. /// </remarks> public static string UrlEncode(int rfcNumber, string data, bool path) { StringBuilder encoded = new StringBuilder(data.Length * 2); string validUrlCharacters; if (!RFCEncodingSchemes.TryGetValue(rfcNumber, out validUrlCharacters)) validUrlCharacters = ValidUrlCharacters; string unreservedChars = String.Concat(validUrlCharacters, (path ? ValidPathCharacters : "")); foreach (char symbol in System.Text.Encoding.UTF8.GetBytes(data)) { if (unreservedChars.IndexOf(symbol) != -1) { encoded.Append(symbol); } else { encoded.Append("%").Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)symbol)); } } return encoded.ToString(); } internal static string UrlEncodeSlash(string data) { if (string.IsNullOrEmpty(data)) { return data; } return data.Replace("/", EncodedSlash); } /// <summary> /// Percent encodes the X-Amzn-Trace-Id header value skipping any characters within the /// ValidTraceIdHeaderValueCharacters character set. /// </summary> /// <param name="value">The X-Amzn-Trace-Id header value to encode.</param> /// <returns>An encoded X-Amzn-Trace-Id header value.</returns> internal static string EncodeTraceIdHeaderValue(string value) { var encoded = new StringBuilder(value.Length * 2); foreach (char symbol in System.Text.Encoding.UTF8.GetBytes(value)) { if (ValidTraceIdHeaderValueCharacters.IndexOf(symbol) != -1) { encoded.Append(symbol); } else { encoded.Append("%").Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)symbol)); } } return encoded.ToString(); } /// <summary> /// URL encodes a string per the specified RFC with the exception of preserving the encoding of previously encoded slashes. /// If the path property is specified, the accepted path characters {/+:} are not encoded. /// </summary> /// <param name="data">The string to encode</param> /// <param name="path">Whether the string is a URL path or not</param> /// <returns>The encoded string with any previously encoded %2F preserved</returns> [Obsolete("This method is not supported in AWSSDK 3.5")] public static string ProtectEncodedSlashUrlEncode(string data, bool path) { if (string.IsNullOrEmpty(data)) { return data; } var index = 0; var sb = new StringBuilder(); var findIndex = data.IndexOf(EncodedSlash, index, StringComparison.OrdinalIgnoreCase); while (findIndex != -1) { sb.Append(UrlEncode(data.Substring(index, findIndex - index), path)); sb.Append(EncodedSlash); index = findIndex + EncodedSlash.Length; findIndex = data.IndexOf(EncodedSlash, index, StringComparison.OrdinalIgnoreCase); } //If encoded slash was not found return the original data if(index == 0) { return UrlEncode(data, path); } if(data.Length > index) { sb.Append(UrlEncode(data.Substring(index), path)); } return sb.ToString(); } /// <summary> /// Generates an MD5 Digest for the stream specified /// </summary> /// <param name="input">The Stream for which the MD5 Digest needs /// to be computed.</param> /// <returns>A string representation of the hash with base64 encoding /// </returns> public static string GenerateMD5ChecksumForStream(Stream input) { string hash = null; if (!input.CanSeek) throw new InvalidOperationException("Input stream must be seekable"); // Use an MD5 instance to compute the hash for the stream byte[] hashed = CryptoUtilFactory.CryptoInstance.ComputeMD5Hash(input); // Convert the hash to a Base64 Encoded string and return it hash = Convert.ToBase64String(hashed); // Now that the hash has been generated, reset the stream to its origin so that the stream's data can be processed input.Position = 0; return hash; } /// <summary> /// Generates an MD5 Digest for the string-based content /// </summary> /// <param name="content">The content for which the MD5 Digest needs /// to be computed. /// </param> /// <param name="fBase64Encode">Whether the returned checksum should be /// base64 encoded. /// </param> /// <returns>A string representation of the hash with or w/o base64 encoding /// </returns> public static string GenerateChecksumForContent(string content, bool fBase64Encode) { // Convert the input string to a byte array and compute the hash. return GenerateChecksumForBytes(Encoding.UTF8.GetBytes(content), fBase64Encode); } /// <summary> /// Generates an MD5 Digest for the given byte array /// </summary> /// <param name="content">The content for which the MD5 Digest needs /// to be computed. /// </param> /// <param name="fBase64Encode">Whether the returned checksum should be /// base64 encoded. /// </param> /// <returns>A string representation of the hash with or w/o base64 encoding /// </returns> public static string GenerateChecksumForBytes(byte[] content, bool fBase64Encode) { var hashed = content != null ? CryptoUtilFactory.CryptoInstance.ComputeMD5Hash(content) : CryptoUtilFactory.CryptoInstance.ComputeMD5Hash(ArrayEx.Empty<byte>()); if (fBase64Encode) { // Convert the hash to a Base64 Encoded string and return it return Convert.ToBase64String(hashed); } else { return BitConverter.ToString(hashed).Replace("-", String.Empty); } } public static void Sleep(TimeSpan ts) { Sleep((int)ts.TotalMilliseconds); } /// <summary> /// Convert bytes to a hex string /// </summary> /// <param name="value">Bytes to convert.</param> /// <returns>Hexadecimal string representing the byte array.</returns> public static string BytesToHexString(byte[] value) { string hex = BitConverter.ToString(value); hex = hex.Replace("-", string.Empty); return hex; } /// <summary> /// Convert a hex string to bytes /// </summary> /// <param name="hex">Hexadecimal string</param> /// <returns>Byte array corresponding to the hex string.</returns> public static byte[] HexStringToBytes(string hex) { if (string.IsNullOrEmpty(hex) || hex.Length % 2 == 1) throw new ArgumentOutOfRangeException("hex"); int count = 0; byte[] buffer = new byte[hex.Length / 2]; for (int i = 0; i < hex.Length; i += 2) { string sub = hex.Substring(i, 2); byte b = Convert.ToByte(sub, 16); buffer[count] = b; count++; } return buffer; } /// <summary> /// Returns DateTime.UtcNow + ManualClockCorrection when /// <seealso cref="AWSConfigs.ManualClockCorrection"/> is set. /// This value should be used instead of DateTime.UtcNow to factor in manual clock correction /// </summary> [Obsolete("This property does not account for endpoint specific clock skew. Use CorrectClockSkew.GetCorrectedUtcNowForEndpoint() instead.")] public static DateTime CorrectedUtcNow { get { var now = AWSConfigs.utcNowSource(); if (AWSConfigs.ManualClockCorrection.HasValue) now += AWSConfigs.ManualClockCorrection.Value; return now; } } /// <summary> /// Returns true if the string has any bidirectional control characters. /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool HasBidiControlCharacters(string input) { if (string.IsNullOrEmpty(input)) return false; foreach (var c in input) { if (IsBidiControlChar(c)) return true; } return false; } private static bool IsBidiControlChar(char c) { // check general range if (c < '\u200E' || c > '\u202E') return false; // check specific characters return ( c == '\u200E' || // LRM c == '\u200F' || // RLM c == '\u202A' || // LRE c == '\u202B' || // RLE c == '\u202C' || // PDF c == '\u202D' || // LRO c == '\u202E' // RLO ); } public static string DownloadStringContent(Uri uri) { return DownloadStringContent(uri, TimeSpan.Zero, null); } public static string DownloadStringContent(Uri uri, TimeSpan timeout) { return DownloadStringContent(uri, timeout, null); } public static string DownloadStringContent(Uri uri, IWebProxy proxy) { return DownloadStringContent(uri, TimeSpan.Zero, proxy); } public static string DownloadStringContent(Uri uri, TimeSpan timeout, IWebProxy proxy) { #if NETSTANDARD using (var client = CreateClient(uri, timeout, proxy, null)) { return AsyncHelpers.RunSync<string>(() => { return client.GetStringAsync(uri); }); } #else var request = CreateClient(uri, timeout, proxy, null); using (var response = request.GetResponse() as HttpWebResponse) using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } #endif } /// <summary> /// Executes an HTTP request and returns the response as a string. This method /// throws WebException and HttpRequestException. In the event HttpRequestException /// is thrown the StatusCode is sent as user defined data on the exception under /// the key "StatusCode". /// </summary> /// <param name="uri">The URI to make the request to</param> /// <param name="requestType">The request type: GET, PUT, POST</param> /// <param name="content">null or the content to send with the request</param> /// <param name="timeout">Timeout for the request</param> /// <param name="proxy">Proxy for the request</param> /// <param name="headers">null or any headers to send with the request</param> /// <returns>The response as a string.</returns> public static string ExecuteHttpRequest(Uri uri, string requestType, string content, TimeSpan timeout, IWebProxy proxy, IDictionary<string, string> headers) { #if NETSTANDARD using (var client = CreateClient(uri, timeout, proxy, headers)) { var response = AsyncHelpers.RunSync<HttpResponseMessage>(() => { var requestMessage = new HttpRequestMessage(new HttpMethod(requestType), uri); if(!string.IsNullOrEmpty(content)) { requestMessage.Content = new StringContent(content); } return client.SendAsync(requestMessage); }); try { response.EnsureSuccessStatusCode(); } catch(HttpRequestException e) { var httpRequestException = new HttpRequestException(e.Message, e); httpRequestException.Data.Add(nameof(response.StatusCode), response.StatusCode); response.Dispose(); throw httpRequestException; } try { return AsyncHelpers.RunSync<string>(() => { return response.Content.ReadAsStringAsync(); }); } finally { response.Dispose(); } } #else var request = CreateClient(uri, timeout, proxy, headers); request.Method = requestType; request.ContentLength = 0; if (!string.IsNullOrEmpty(content)) { var contentBytes = Encoding.UTF8.GetBytes(content); request.ContentLength = contentBytes.Length; using (var requestStream = request.GetRequestStream()) { requestStream.Write(contentBytes, 0, contentBytes.Length); } } using (var response = request.GetResponse() as HttpWebResponse) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } #endif } #if NETSTANDARD private static HttpClient CreateClient(Uri uri, TimeSpan timeout, IWebProxy proxy, IDictionary<string, string> headers) { var client = new HttpClient(new System.Net.Http.HttpClientHandler() { Proxy = proxy }); if (timeout > TimeSpan.Zero) { client.Timeout = timeout; } //DefaultRequestHeaders should not be used if we reuse the HttpClient. It is currently created for each request. client.DefaultRequestHeaders.TryAddWithoutValidation(UserAgentHeader, _userAgent); if(headers != null) { foreach(var nameValue in headers) { client.DefaultRequestHeaders.TryAddWithoutValidation(nameValue.Key, nameValue.Value); } } return client; } #else private static HttpWebRequest CreateClient(Uri uri, TimeSpan timeout, IWebProxy proxy, IDictionary<string, string> headers) { HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest; request.Proxy = proxy ?? WebRequest.DefaultWebProxy; if (timeout > TimeSpan.Zero) { request.Timeout = (int)timeout.TotalMilliseconds; } request.UserAgent = _userAgent; if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } return request; } #endif public static Stream OpenStream(Uri uri) { return OpenStream(uri, null); } public static Stream OpenStream(Uri uri, IWebProxy proxy) { #if NETSTANDARD using (var client = new System.Net.Http.HttpClient(new System.Net.Http.HttpClientHandler() { Proxy = proxy })) { var task = client.GetStreamAsync(uri); return task.Result; } #else HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; request.Proxy = proxy ?? WebRequest.DefaultWebProxy; var asynResult = request.BeginGetResponse(null, null); HttpWebResponse response = request.EndGetResponse(asynResult) as HttpWebResponse; return response.GetResponseStream(); #endif } /// <summary> /// Utility method that accepts a string and replaces white spaces with a space. /// </summary> /// <param name="data"></param> /// <returns></returns> public static string CompressSpaces(string data) { if (data == null) { return null; } if (data.Length == 0) { return string.Empty; } var stringBuilder = new StringBuilder(); var isWhiteSpace = false; foreach (var character in data) { if (!isWhiteSpace | !(isWhiteSpace = char.IsWhiteSpace(character))) { stringBuilder.Append(isWhiteSpace ? ' ' : character); } } return stringBuilder.ToString(); } /// <summary> /// Runs a process with the below input parameters. /// </summary> /// <param name="processStartInfo"></param> /// <returns></returns> [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] public static ProcessExecutionResult RunProcess(ProcessStartInfo processStartInfo) { using (var process = new Process { StartInfo = processStartInfo }) { var logger = Logger.GetLogger(typeof(AWSSDKUtils)); logger.InfoFormat("Starting a process with the following ProcessInfo: UseShellExecute - {0} RedirectStandardError - {1}, RedirectStandardOutput - {2}, CreateNoWindow - {3}", processStartInfo.UseShellExecute, processStartInfo.RedirectStandardError, processStartInfo.RedirectStandardOutput, processStartInfo.CreateNoWindow); process.Start(); logger.InfoFormat("Process started"); string standardOutput = null; var thread = new Thread(() => standardOutput = process.StandardOutput.ReadToEnd()); thread.Start(); var standardError = process.StandardError.ReadToEnd(); thread.Join(); process.WaitForExit(); return new ProcessExecutionResult { ExitCode = process.ExitCode, StandardError = standardError, StandardOutput = standardOutput }; } } #if AWS_ASYNC_API [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] public static async Task<ProcessExecutionResult> RunProcessAsync(ProcessStartInfo processStartInfo) { var logger = Logger.GetLogger(typeof(AWSSDKUtils)); using (var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }) { var tcs = new TaskCompletionSource<object>(); process.Exited += (s, ea) => tcs.SetResult(null); logger.InfoFormat("Starting a process with the following ProcessInfo: UseShellExecute - {0} RedirectStandardError - {1}, RedirectStandardOutput - {2}, CreateNoWindow - {3}", processStartInfo.UseShellExecute, processStartInfo.RedirectStandardError, processStartInfo.RedirectStandardOutput, processStartInfo.CreateNoWindow); process.Start(); logger.InfoFormat("Process started"); var standardErrorTask = process.StandardError.ReadToEndAsync(); var standardOutputTask = process.StandardOutput.ReadToEndAsync(); await Task.WhenAll(tcs.Task, standardErrorTask, standardOutputTask).ConfigureAwait(false); return new ProcessExecutionResult { ExitCode = process.ExitCode, StandardError = standardErrorTask.Result, StandardOutput = standardOutputTask.Result }; } } #endif /// <summary> /// This method allows to check whether a property of an object returned by a service call /// is set. This method is needed to discriminate whether a field is not set (not present in /// the service response) or if it is set to the default value for its type. Using this /// method is not required for nullable properties (non-ValueType and Nullable) because /// they will be simply set to null when not included in the service response. /// This method can also be used on objects used as part of service requests. /// This method doesn't support objects that are part of the S3 service model. /// </summary> /// <param name="awsServiceObject">An object that is used in an AWS service request or is /// returned as part of an AWS service response.</param> /// <param name="propertyName">The name of the property of awsServiceObject to check.</param> /// <returns>True if the property is set, otherwise false.</returns> public static bool IsPropertySet(object awsServiceObject, string propertyName) { var type = awsServiceObject.GetType(); var nameSpace = type.Namespace; if (!nameSpace.StartsWith("Amazon.", StringComparison.Ordinal) || !nameSpace.EndsWith(".Model", StringComparison.Ordinal)) { throw new ArgumentException("IsPropertySet can be used only on Amazon Model classes"); } else if (nameSpace == "Amazon.S3.Model") { throw new ArgumentException("IsPropertySet doesn't support S3"); } var key = new IsSetMethodsCacheKey(type, propertyName); //We cache the result of GetIsPropertySetMethodInfo even if it is null var method = IsSetMethodsCache.GetOrAdd(key, (k) => k.Type.GetMethod("IsSet" + k.PropertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], new ParameterModifier[0])); if (method == null) { throw new ArgumentException("Could not find an IsSet method for property " + key); } object result = method.Invoke(awsServiceObject, new object[0]); if (!(result is bool)) { throw new ArgumentException("The IsSet method for property " + key + " didn't return a bool"); } return (bool)result; } #endregion #region Private Methods, Static Fields and Classes private static LruCache<IsSetMethodsCacheKey, MethodInfo> IsSetMethodsCache = new LruCache<IsSetMethodsCacheKey, MethodInfo>(MaxIsSetMethodsCacheSize); private class IsSetMethodsCacheKey { public readonly Type Type; public readonly string PropertyName; public IsSetMethodsCacheKey(Type type, string propertyName) { Type = type; PropertyName = propertyName; } public override bool Equals(object other) { var otherKey = other as IsSetMethodsCacheKey; if (otherKey == null) { return false; } return Type == otherKey.Type && PropertyName == otherKey.PropertyName; } public override int GetHashCode() { return Type.GetHashCode() ^ PropertyName.GetHashCode(); } public override string ToString() { return Type.FullName + "." + PropertyName; } } #endregion } public class JitteredDelay { private TimeSpan _maxDelay; private TimeSpan _variance; private TimeSpan _baseIncrement; private Random _rand = null; private int _count = 0; public JitteredDelay(TimeSpan baseIncrement, TimeSpan variance) : this(baseIncrement, variance, new TimeSpan(0, 0, 30)) { } public JitteredDelay(TimeSpan baseIncrement, TimeSpan variance, TimeSpan maxDelay) { _baseIncrement = baseIncrement; _variance = variance; _maxDelay = maxDelay; _rand = new System.Random(); } public TimeSpan GetRetryDelay(int attemptCount) { long ticks = (_baseIncrement.Ticks * (long)Math.Pow(2, attemptCount) + (long)(_rand.NextDouble() * _variance.Ticks)); return new TimeSpan(ticks); } public TimeSpan Next() { long nextTick = GetRetryDelay(_count + 1).Ticks; if (nextTick < _maxDelay.Ticks) { _count++; } else { nextTick = _maxDelay.Ticks; } return new TimeSpan(nextTick); } public void Reset() { _count = 0; } } }
1,719
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Runtime; using Amazon.Runtime.Internal.Util; using Amazon.Util.Internal; using AWSSDK.Runtime.Internal.Util; using System.IO; using System.Security.Cryptography; using System.Text; using ThirdParty.MD5; namespace Amazon.Util { public static partial class CryptoUtilFactory { private const int SHA1_BASE64_LENGTH = 28; private const int SHA56_BASE64_LENGTH = 44; private const int CRC32_BASE64_LENGTH = 8; static CryptoUtil util = new CryptoUtil(); public static ICryptoUtil CryptoInstance { get { return util; } } /// <summary> /// Returns a new instance of the specified hashing algorithm /// </summary> /// <param name="algorithm">Hashing algorithm to instantiate</param> /// <returns>New instance of the given algorithm</returns> public static HashAlgorithm GetChecksumInstance(CoreChecksumAlgorithm algorithm) { switch (algorithm) { case CoreChecksumAlgorithm.SHA1: return new SHA1Managed(); case CoreChecksumAlgorithm.SHA256: return CryptoUtil.CreateSHA256Instance(); case CoreChecksumAlgorithm.CRC32: return new CrtCrc32(); case CoreChecksumAlgorithm.CRC32C: return new CrtCrc32c(); default: throw new AmazonClientException($"Unable to instantiate checksum algorithm {algorithm}"); } } /// <summary> /// Returns the length of the base64 encoded checksum of the specifed hashing algorithm /// </summary> /// <param name="algorithm">Hashing algorithm </param> /// <returns>Length of the base64 encoded checksum</returns> public static int GetChecksumBase64Length(CoreChecksumAlgorithm algorithm) { switch (algorithm) { case CoreChecksumAlgorithm.SHA1: return SHA1_BASE64_LENGTH; case CoreChecksumAlgorithm.SHA256: return SHA56_BASE64_LENGTH; case CoreChecksumAlgorithm.CRC32: case CoreChecksumAlgorithm.CRC32C: return CRC32_BASE64_LENGTH; default: throw new AmazonClientException($"Unable to determine the base64-encoded length of {algorithm}"); } } partial class CryptoUtil : ICryptoUtil { internal CryptoUtil() { } /// <summary> /// Computes a hash-based message authentication code /// </summary> /// <param name="data">Input to compute the hash code for</param> /// <param name="key">Signing key</param> /// <param name="algorithmName">Hashing algorithm to use</param> /// <returns>Computed hash code</returns> public string HMACSign(string data, string key, SigningAlgorithm algorithmName) { var binaryData = Encoding.UTF8.GetBytes(data); return HMACSign(binaryData, key, algorithmName); } /// <summary> /// Computes a SHA1 hash /// </summary> /// <param name="data">Input to compute the hash code for</param> /// <returns>Computed hash code</returns> public byte[] ComputeSHA1Hash(byte[] data) { using (var sha1 = new SHA1Managed()) { return sha1.ComputeHash(data); } } /// <summary> /// Computes a SHA256 hash /// </summary> /// <param name="data">Input to compute the hash code for</param> /// <returns>Computed hash code</returns> public byte[] ComputeSHA256Hash(byte[] data) { return SHA256HashAlgorithmInstance.ComputeHash(data); } /// <summary> /// Computes a SHA256 hash /// </summary> /// <param name="steam">Input to compute the hash code for</param> /// <returns>Computed hash code</returns> public byte[] ComputeSHA256Hash(Stream steam) { return SHA256HashAlgorithmInstance.ComputeHash(steam); } /// <summary> /// Computes an MD5 hash /// </summary> /// <param name="data">Input to compute the hash code for</param> /// <returns>Computed hash code</returns> public byte[] ComputeMD5Hash(byte[] data) { var hashed = new MD5Managed().ComputeHash(data); return hashed; } /// <summary> /// Computes an MD5 hash /// </summary> /// <param name="steam">Input to compute the hash code for</param> /// <returns>Computed hash code</returns> public byte[] ComputeMD5Hash(Stream steam) { var hashed = new MD5Managed().ComputeHash(steam); return hashed; } /// <summary> /// Computes a CRC32 hash /// </summary> /// <param name="data">Data to hash</param> /// <returns>CRC32 hash as a base64-encoded string</returns> public string ComputeCRC32Hash(byte[] data) { return ChecksumCRTWrapper.Crc32(data); } /// <summary> /// Computes a CRC32C hash /// </summary> /// <param name="data">Data to hash</param> /// <returns>CRC32C hash as a base64-encoded string</returns> public string ComputeCRC32CHash(byte[] data) { return ChecksumCRTWrapper.Crc32C(data); } } } }
182
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using Amazon.Runtime; using ThirdParty.Json.LitJson; using System.Globalization; using Amazon.Runtime.Internal.Util; using AWSSDK.Runtime.Internal.Util; using Amazon.Runtime.Internal; namespace Amazon.Util { /// <summary> /// Provides access to EC2 instance metadata when running on an EC2 instance. /// If this class is used on a non-EC2 instance, the properties in this class /// will return null. /// </summary> /// <remarks> /// <para> /// Amazon EC2 instances can access instance-specific metadata, as well as data supplied when launching the instances, using a specific URI. /// </para> /// <para> /// You can use this data to build more generic AMIs that can be modified by configuration files supplied at launch time. /// For example, if you run web servers for various small businesses, they can all use the same AMI and retrieve their content from the /// Amazon S3 bucket you specify at launch. To add a new customer at any time, simply create a bucket for the customer, add their content, /// and launch your AMI. /// </para> /// <para> /// More information about EC2 Metadata <see href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html"/> /// </para> /// </remarks> public static class EC2InstanceMetadata { [Obsolete("EC2_METADATA_SVC is obsolete, refer to ServiceEndpoint instead to respect environment and profile overrides.")] public static readonly string EC2_METADATA_SVC = "http://169.254.169.254"; [Obsolete("EC2_METADATA_ROOT is obsolete, refer to EC2MetadataRoot instead to respect environment and profile overrides.")] public static readonly string EC2_METADATA_ROOT = EC2_METADATA_SVC + LATEST + "/meta-data"; [Obsolete("EC2_USERDATA_ROOT is obsolete, refer to EC2UserDataRoot instead to respect environment and profile overrides.")] public static readonly string EC2_USERDATA_ROOT = EC2_METADATA_SVC + LATEST + "/user-data"; [Obsolete("EC2_DYNAMICDATA_ROOT is obsolete, refer to EC2DynamicDataRoot instead to respect environment and profile overrides.")] public static readonly string EC2_DYNAMICDATA_ROOT = EC2_METADATA_SVC + LATEST + "/dynamic"; [Obsolete("EC2_APITOKEN_URL is obsolete, refer to EC2ApiTokenUrl instead to respect environment and profile overrides.")] public static readonly string EC2_APITOKEN_URL = EC2_METADATA_SVC + LATEST + "/api/token"; public static readonly string LATEST = "/latest", AWS_EC2_METADATA_DISABLED = "AWS_EC2_METADATA_DISABLED"; private static int DEFAULT_RETRIES = 3, MIN_PAUSE_MS = 250, MAX_RETRIES = 3, DEFAULT_APITOKEN_TTL = 21600; private static Dictionary<string, string> _cache = new Dictionary<string, string>(); private static bool useNullToken = false; private static ReaderWriterLockSlim metadataLock = new ReaderWriterLockSlim(); // Lock to control getting metadata across multiple threads. private static readonly TimeSpan metadataLockTimeout = TimeSpan.FromMilliseconds(5000); /// <summary> /// Base endpoint of the instance metadata service. Returns the endpoint configured first /// via environment variable AWS_EC2_METADATA_SERVICE_ENDPOINT then the current profile's /// ec2_metadata_service_endpoint value. If a specific endpoint is not configured, it selects a pre-determined /// endpoint based on environment variable AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE then the /// current profile's ec2_metadata_service_endpoint_mode setting. /// </summary> public static string ServiceEndpoint { get { if (!string.IsNullOrEmpty(FallbackInternalConfigurationFactory.EC2MetadataServiceEndpoint)) { return FallbackInternalConfigurationFactory.EC2MetadataServiceEndpoint; } else if (FallbackInternalConfigurationFactory.EC2MetadataServiceEndpointMode == EC2MetadataServiceEndpointMode.IPv6) { return "http://[fd00:ec2::254]"; } else // either explicit IPv4 or default behavior { return "http://169.254.169.254"; } } } /// <summary> /// Root URI to retrieve instance metadata /// </summary> public static string EC2MetadataRoot => ServiceEndpoint + LATEST + "/meta-data"; /// <summary> /// Root URI to retrieve instance user data /// </summary> public static string EC2UserDataRoot => ServiceEndpoint + LATEST + "/user-data"; /// <summary> /// Root URI to retrieve dynamic instance data /// </summary> public static string EC2DynamicDataRoot => ServiceEndpoint + LATEST + "/dynamic"; /// <summary> /// URI to retrieve the IMDS API token /// </summary> public static string EC2ApiTokenUrl => ServiceEndpoint + LATEST + "/api/token"; /// <summary> /// Returns whether requesting the EC2 Instance Metadata Service is /// enabled via the AWS_EC2_METADATA_DISABLED environment variable. /// </summary> public static bool IsIMDSEnabled { get { const string True = "true"; string value = string.Empty; try { value = System.Environment.GetEnvironmentVariable(AWS_EC2_METADATA_DISABLED); } catch { }; return !True.Equals(value, StringComparison.OrdinalIgnoreCase); } } /// <summary> /// Allows to configure the proxy used for HTTP requests. The default value is null. /// </summary> public static IWebProxy Proxy { get; set; } /// <summary> /// The AMI ID used to launch the instance. /// </summary> public static string AmiId { get { return FetchData("/ami-id"); } } /// <summary> /// The index of this instance in the reservation. /// </summary> public static string AmiLaunchIndex { get { return FetchData("/ami-launch-index"); } } /// <summary> /// The manifest path of the AMI with which the instance was launched. /// </summary> public static string AmiManifestPath { get { return FetchData("/ami-manifest-path"); } } /// <summary> /// The AMI IDs of any instances that were rebundled to create this AMI. /// Will only exist if the AMI manifest file contained an ancestor-amis key. /// </summary> public static IEnumerable<string> AncestorAmiIds { get { return GetItems("/ancestor-ami-ids"); } } /// <summary> /// The private hostname of the instance. /// In cases where multiple network interfaces are present, /// this refers to the eth0 device (the device for which the device number is 0). /// </summary> public static string Hostname { get { return FetchData("/hostname"); } } /// <summary> /// Notifies the instance that it should reboot in preparation for bundling. /// Valid values: none | shutdown | bundle-pending. /// </summary> public static string InstanceAction { get { return FetchData("/instance-action"); } } /// <summary> /// The ID of this instance. /// </summary> public static string InstanceId { get { return FetchData("/instance-id"); } } /// <summary> /// The type of instance. /// </summary> public static string InstanceType { get { return FetchData("/instance-type"); } } /// <summary> /// The ID of the kernel launched with this instance, if applicable. /// </summary> public static string KernelId { get { return GetData("kernel-id"); } } /// <summary> /// The local hostname of the instance. In cases where multiple network interfaces are present, /// this refers to the eth0 device (the device for which device-number is 0). /// </summary> public static string LocalHostname { get { return FetchData("/local-hostname"); } } /// <summary> /// The instance's MAC address. In cases where multiple network interfaces are present, /// this refers to the eth0 device (the device for which device-number is 0). /// </summary> public static string MacAddress { get { return FetchData("/mac"); } } /// <summary> /// The private IP address of the instance. In cases where multiple network interfaces are present, /// this refers to the eth0 device (the device for which device-number is 0). /// </summary> public static string PrivateIpAddress { get { return FetchData("/local-ipv4"); } } /// <summary> /// The Availability Zone in which the instance launched. /// </summary> public static string AvailabilityZone { get { return FetchData("/placement/availability-zone"); } } /// <summary> /// Product codes associated with the instance, if any. /// </summary> public static IEnumerable<string> ProductCodes { get { return GetItems("/product-codes"); } } /// <summary> /// Public key. Only available if supplied at instance launch time. /// </summary> public static string PublicKey { get { return FetchData("/public-keys/0/openssh-key"); } } /// <summary> /// The ID of the RAM disk specified at launch time, if applicable. /// </summary> public static string RamdiskId { get { return FetchData("/ramdisk-id"); } } /// <summary> /// The region in which the instance is running, extracted from the identity /// document data. /// </summary> public static RegionEndpoint Region { get { var identityDocument = IdentityDocument; if (!string.IsNullOrEmpty(identityDocument)) { try { var jsonDocument = JsonMapper.ToObject(identityDocument.ToString()); var regionName = jsonDocument["region"]; if (regionName != null) return RegionEndpoint.GetBySystemName(regionName.ToString()); } catch (Exception e) { var logger = Logger.GetLogger(typeof(EC2InstanceMetadata)); logger.Error(e, "Error attempting to read region from instance metadata identity document"); } } return null; } } /// <summary> /// ID of the reservation. /// </summary> public static string ReservationId { get { return FetchData("/reservation-id"); } } /// <summary> /// The names of the security groups applied to the instance. /// </summary> public static IEnumerable<string> SecurityGroups { get { return GetItems("/security-groups"); } } /// <summary> /// Returns information about the last time the instance profile was updated, /// including the instance's LastUpdated date, InstanceProfileArn, and InstanceProfileId. /// </summary> public static IAMInstanceProfileMetadata IAMInstanceProfileInfo { get { var json = GetData("/iam/info"); if (null == json) return null; IAMInstanceProfileMetadata info; try { info = JsonMapper.ToObject<IAMInstanceProfileMetadata>(json); } catch { info = new IAMInstanceProfileMetadata { Code = "Failed", Message = "Could not parse response from metadata service." }; } return info; } } /// <summary> /// Returns the temporary security credentials (AccessKeyId, SecretAccessKey, SessionToken, and Expiration) /// associated with the IAM roles on the instance. /// </summary> public static IDictionary<string, IAMSecurityCredentialMetadata> IAMSecurityCredentials { get { var list = GetItems("/iam/security-credentials"); if (list == null) return null; var creds = new Dictionary<string, IAMSecurityCredentialMetadata>(); foreach (var item in list) { var json = GetData("/iam/security-credentials/" + item); try { var cred = JsonMapper.ToObject<IAMSecurityCredentialMetadata>(json); creds[item] = cred; } catch { creds[item] = new IAMSecurityCredentialMetadata { Code = "Failed", Message = "Could not parse response from metadata service." }; } } return creds; } } /// <summary> /// The virtual devices associated with the ami, root, ebs, and swap. /// </summary> public static IDictionary<string, string> BlockDeviceMapping { get { var keys = GetItems("/block-device-mapping"); if (keys == null) return null; var mapping = new Dictionary<string, string>(); foreach (var key in keys) { mapping[key] = GetData("/block-device-mapping/" + key); } return mapping; } } /// <summary> /// The network interfaces on the instance. /// </summary> public static IEnumerable<NetworkInterfaceMetadata> NetworkInterfaces { get { var macs = GetItems("/network/interfaces/macs/"); if (macs == null) return null; var interfaces = new List<NetworkInterfaceMetadata>(); foreach (var mac in macs) { interfaces.Add(new NetworkInterfaceMetadata(mac.Trim('/'))); } return interfaces; } } /// <summary> /// The metadata sent to the instance. /// </summary> public static string UserData { get { return GetData(EC2UserDataRoot); } } /// <summary> /// Value showing whether the customer has enabled detailed /// one-minute monitoring in CloudWatch. /// </summary> public static string InstanceMonitoring { get { return GetData(EC2DynamicDataRoot + "/fws/instance-monitoring"); } } /// <summary> /// JSON containing instance attributes, such as instance-id, private IP /// address, etc /// </summary> public static string IdentityDocument { get { return GetData(EC2DynamicDataRoot + "/instance-identity/document"); } } /// <summary> /// Data that can be used by other parties to verify its origin and authenticity. /// </summary> public static string IdentitySignature { get { return GetData(EC2DynamicDataRoot + "/instance-identity/signature"); } } /// <summary> /// Used to verify the document's authenticity and content against the signature. /// </summary> public static string IdentityPkcs7 { get { return GetData(EC2DynamicDataRoot + "/instance-identity/pkcs7"); } } /// <summary> /// Return the list of items in the metadata at path. /// </summary> /// <param name="path">Path at which to query the metadata; may be relative or absolute.</param> /// <returns>List of items returned by the metadata service</returns> public static IEnumerable<string> GetItems(string path) { return GetItems(path, DEFAULT_RETRIES, false); } /// <summary> /// Return the metadata at the path /// </summary> /// <param name="path">Path at which to query the metadata; may be relative or absolute.</param> /// <returns>Data returned by the metadata service</returns> public static string GetData(string path) { return GetData(path, DEFAULT_RETRIES); } /// <summary> /// Return the metadata at the path /// </summary> /// <param name="path">Path at which to query the metadata; may be relative or absolute.</param> /// <param name="tries">Number of attempts to make</param> /// <returns>Data returned by the metadata service</returns> public static string GetData(string path, int tries) { var items = GetItems(path, tries, true); if (items != null && items.Count > 0) return items[0]; return null; } /// <summary> /// Return the list of items in the metadata at path. /// </summary> /// <param name="path">Path at which to query the metadata; may be relative or absolute.</param> /// <param name="tries">Number of attempts to make</param> /// <returns>List of items returned by the metadata service</returns> public static IEnumerable<string> GetItems(string path, int tries) { return GetItems(path, tries, false); } private static string FetchData(string path) { return FetchData(path, false); } private static string FetchData(string path, bool force) { try { // Try to acquire read lock if there is no need to force get the metadata. The thread would be blocked if another thread has write lock. if (!force) { if (metadataLock.TryEnterReadLock(metadataLockTimeout)) { try { if (_cache.ContainsKey(path)) { return _cache[path]; } } finally { metadataLock.ExitReadLock(); } } else { Logger.GetLogger(typeof(EC2InstanceMetadata)).InfoFormat("Unable to acquire read lock to access cache."); } } // If there is no metadata cached or it needs to force get the metadata. Try to acquire write lock. if (metadataLock.TryEnterWriteLock(metadataLockTimeout)) { try { // Check if metadata is cached again in case other thread might have already fetched it. if (force || !_cache.ContainsKey(path)) { _cache[path] = GetData(path); } } finally { metadataLock.ExitWriteLock(); } } else { Logger.GetLogger(typeof(EC2InstanceMetadata)).InfoFormat("Unable to acquire write lock to modify cache."); } // Try to acquire read lock. The thread would be blocked if another thread has write lock. if (metadataLock.TryEnterReadLock(metadataLockTimeout)) { try { if (_cache.ContainsKey(path)) { return _cache[path]; } else { return null; } } finally { metadataLock.ExitReadLock(); } } else { Logger.GetLogger(typeof(EC2InstanceMetadata)).InfoFormat("Unable to acquire read lock to access cache."); return null; } } catch { return null; } } /// <summary> /// Fetches the api token to use with metadata requests. /// </summary> /// <returns>The API token or null</returns> public static string FetchApiToken() { return FetchApiToken(DEFAULT_RETRIES); } /// <summary> /// Fetches the api token to use with metadata requests. /// </summary> /// <param name="tries">The number of tries to fetch the api token before giving up and throwing the web exception</param> /// <returns>The API token or null if an API token couldn't be obtained and doesn't need to be used</returns> private static string FetchApiToken(int tries) { for (int retry = 1; retry <= tries; retry++) { if (!IsIMDSEnabled || useNullToken) { return null; } try { var uriForToken = new Uri(EC2ApiTokenUrl); var headers = new Dictionary<string, string>(); headers.Add(HeaderKeys.XAwsEc2MetadataTokenTtlSeconds, DEFAULT_APITOKEN_TTL.ToString(CultureInfo.InvariantCulture)); var content = AWSSDKUtils.ExecuteHttpRequest(uriForToken, "PUT", null, TimeSpan.FromSeconds(5), Proxy, headers); return content.Trim(); } catch (Exception e) { HttpStatusCode? httpStatusCode = ExceptionUtils.DetermineHttpStatusCode(e); if (httpStatusCode == HttpStatusCode.NotFound || httpStatusCode == HttpStatusCode.MethodNotAllowed || httpStatusCode == HttpStatusCode.Forbidden) { useNullToken = true; return null; } if (retry >= tries) { if (httpStatusCode == HttpStatusCode.BadRequest) { Logger.GetLogger(typeof(EC2InstanceMetadata)).Error(e, "Unable to contact EC2 Metadata service to obtain a metadata token."); throw; } Logger.GetLogger(typeof(EC2InstanceMetadata)).Error(e, "Unable to contact EC2 Metadata service to obtain a metadata token. Attempting to access IMDS without a token."); //If there isn't a status code, it was a failure to contact the server which would be //a request failure, a network issue, or a timeout. Cache this response and fallback //to IMDS flow without a token. If the non token IMDS flow returns unauthorized, the //useNullToken flag will be cleared and the IMDS flow will attempt to obtain another //token. if (httpStatusCode == null) { useNullToken = true; } //Return null to fallback to the IMDS flow without using a token. return null; } PauseExponentially(retry - 1); } } return null; } public static void ClearTokenFlag() { useNullToken = false; } private static List<string> GetItems(string relativeOrAbsolutePath, int tries, bool slurp) { return GetItems(relativeOrAbsolutePath, tries, slurp, null); } private static List<string> GetItems(string relativeOrAbsolutePath, int tries, bool slurp, string token) { var items = new List<string>(); //For all meta-data queries we need to fetch an api token to use. In the event a //token cannot be obtained we will fallback to not using a token. Dictionary<string, string> headers = null; if(token == null) { token = FetchApiToken(DEFAULT_RETRIES); } if (!string.IsNullOrEmpty(token)) { headers = new Dictionary<string, string>(); headers.Add(HeaderKeys.XAwsEc2MetadataToken, token); } try { if (!IsIMDSEnabled) { throw new IMDSDisabledException(); } // if we are given a relative path, we assume the data we need exists under the // main metadata root var uri = relativeOrAbsolutePath.StartsWith(ServiceEndpoint, StringComparison.Ordinal) ? new Uri(relativeOrAbsolutePath) : new Uri(EC2MetadataRoot + relativeOrAbsolutePath); var content = AWSSDKUtils.ExecuteHttpRequest(uri, "GET", null, TimeSpan.FromSeconds(5), Proxy, headers); using (var stream = new StringReader(content)) { if (slurp) items.Add(stream.ReadToEnd()); else { string line; do { line = stream.ReadLine(); if (line != null) items.Add(line.Trim()); } while (line != null); } } } catch (IMDSDisabledException) { // Keep this behavior identical to when HttpStatusCode.NotFound is returned. return null; } catch (Exception e) { HttpStatusCode? httpStatusCode = ExceptionUtils.DetermineHttpStatusCode(e); if (httpStatusCode == HttpStatusCode.NotFound) { return null; } else if (httpStatusCode == HttpStatusCode.Unauthorized) { ClearTokenFlag(); Logger.GetLogger(typeof(EC2InstanceMetadata)).Error(e, "EC2 Metadata service returned unauthorized for token based secure data flow."); throw; } if (tries <= 1) { Logger.GetLogger(typeof(EC2InstanceMetadata)).Error(e, "Unable to contact EC2 Metadata service."); return null; } PauseExponentially(DEFAULT_RETRIES - tries); return GetItems(relativeOrAbsolutePath, tries - 1, slurp, token); } return items; } /// <summary> /// Exponentially sleeps based on the current retry value. A lower /// value will sleep shorter than a larger value /// </summary> /// <param name="retry">Base 0 retry index</param> private static void PauseExponentially(int retry) { var pause = (int)(Math.Pow(2, retry) * MIN_PAUSE_MS); Thread.Sleep(pause < MIN_PAUSE_MS ? MIN_PAUSE_MS : pause); } #if !NETSTANDARD [Serializable] #endif private class IMDSDisabledException : InvalidOperationException { }; } /// <summary> /// Returns information about the last time the instance profile was updated, /// including the instance's LastUpdated date, InstanceProfileArn, and InstanceProfileId. /// </summary> public class IAMInstanceProfileMetadata { /// <summary> /// The status of the instance profile /// </summary> public string Code { get; set; } /// <summary> /// Further information about the status of the instance profile /// </summary> public string Message { get; set; } /// <summary> /// The date and time the instance profile was updated /// </summary> public DateTime LastUpdated { get; set; } /// <summary> /// The Amazon Resource Name (ARN) of the instance profile /// </summary> public string InstanceProfileArn { get; set; } /// <summary> /// The Id of the instance profile /// </summary> public string InstanceProfileId { get; set; } } /// <summary> /// The temporary security credentials (AccessKeyId, SecretAccessKey, SessionToken, and Expiration) associated with the IAM role. /// </summary> public class IAMSecurityCredentialMetadata { /// <summary> /// The status of the security credential /// </summary> public string Code { get; set; } /// <summary> /// Further information about the status of the instance profile /// </summary> public string Message { get; set; } /// <summary> /// The date and time the security credential was last updated /// </summary> public DateTime LastUpdated { get; set; } /// <summary> /// The type of the security credential /// </summary> public string Type { get; set; } /// <summary> /// The uniqe id of the security credential /// </summary> public string AccessKeyId { get; set; } /// <summary> /// The secret key used to sign requests /// </summary> public string SecretAccessKey { get; set; } /// <summary> /// The security token /// </summary> public string Token { get; set; } /// <summary> /// The date and time when these credentials expire /// </summary> public DateTime Expiration { get; set; } } /// <summary> /// All of the metadata associated with a network interface on the instance. /// </summary> public class NetworkInterfaceMetadata { private string _path; private string _mac; private IEnumerable<string> _availableKeys; private Dictionary<string, string> _data = new Dictionary<string, string>(); private NetworkInterfaceMetadata() { } /// <summary> /// Construct an instance of NetworkInterface /// </summary> /// <param name="macAddress"></param> public NetworkInterfaceMetadata(string macAddress) { _mac = macAddress; _path = string.Format(CultureInfo.InvariantCulture, "/network/interfaces/macs/{0}/", _mac); } /// <summary> /// The interface's Media Access Control (mac) address. /// </summary> public string MacAddress { get { return _mac; } } /// <summary> /// The ID of the owner of the network interface. /// </summary> /// <remarks> /// In multiple-interface environments, an interface can be attached by a third party, such as Elastic Load Balancing. /// Traffic on an interface is always billed to the interface owner. /// </remarks> public string OwnerId { get { return GetData("owner-id"); } } /// <summary> /// The interface's profile /// </summary> public string Profile { get { return GetData("profile"); } } /// <summary> /// The interface's local hostname. /// </summary> public string LocalHostname { get { return GetData("local-hostname"); } } /// <summary> /// The private IP addresses associated with the interface. /// </summary> public IEnumerable<string> LocalIPv4s { get { return GetItems("local-ipv4s"); } } /// <summary> /// The interface's public hostname. /// </summary> public string PublicHostname { get { return GetData("public-hostname"); } } /// <summary> /// The elastic IP addresses associated with the interface. /// </summary> /// <remarks> /// There may be multiple IP addresses on an instance. /// </remarks> public IEnumerable<string> PublicIPv4s { get { return GetItems("public-ipv4s"); } } /// <summary> /// Security groups to which the network interface belongs. /// </summary> public IEnumerable<string> SecurityGroups { get { return GetItems("security-groups"); } } /// <summary> /// IDs of the security groups to which the network interface belongs. Returned only for Amazon EC2 instances launched into a VPC. /// </summary> public IEnumerable<string> SecurityGroupIds { get { return GetItems("security-group-ids"); } } /// <summary> /// The ID of the Amazon EC2-VPC subnet in which the interface resides. /// </summary> /// <remarks> /// Returned only for Amazon EC2 instances launched into a VPC. /// </remarks> public string SubnetId { get { return GetData("subnet-id"); } } /// <summary> /// The CIDR block of the Amazon EC2-VPC subnet in which the interface resides. /// </summary> /// <remarks> /// Returned only for Amazon EC2 instances launched into a VPC. /// </remarks> public string SubnetIPv4CidrBlock { get { return GetData("subnet-ipv4-cidr-block"); } } /// <summary> /// The CIDR block of the Amazon EC2-VPC subnet in which the interface resides. /// </summary> /// <remarks> /// Returned only for Amazon EC2 instances launched into a VPC. /// </remarks> public string VpcId { get { return GetData("vpc-id"); } } /// <summary> /// Get the private IPv4 address(es) that are associated with the public-ip address and assigned to that interface. /// </summary> /// <param name="publicIp">The public IP address</param> /// <returns>Private IPv4 address(es) associated with the public IP address</returns> public IEnumerable<string> GetIpV4Association(string publicIp) { return EC2InstanceMetadata.GetItems(string.Format(CultureInfo.InvariantCulture, "{0}ipv4-associations/{1}", _path, publicIp)); } private string GetData(string key) { if (_data.ContainsKey(key)) return _data[key]; // Since the keys are variable, cache a list of which ones are available // to prevent unnecessary trips to the service. if (null == _availableKeys) _availableKeys = EC2InstanceMetadata.GetItems(_path); if (_availableKeys.Contains(key)) { _data[key] = EC2InstanceMetadata.GetData(_path + key); return _data[key]; } else return null; } private IEnumerable<string> GetItems(string key) { if (null == _availableKeys) _availableKeys = EC2InstanceMetadata.GetItems(_path); if (_availableKeys.Contains(key)) { return EC2InstanceMetadata.GetItems(_path + key); } else return new List<string>(); } } }
1,066
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ namespace Amazon.Util { public abstract class EnvironmentVariables { public const string AWS_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; public const string _X_AMZN_TRACE_ID = "_X_AMZN_TRACE_ID"; } }
24
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2006-03-01 * */ using System.Runtime.CompilerServices; namespace Amazon.Util { public abstract class HeaderKeys { public const string IfModifiedSinceHeader = "If-Modified-Since"; public const string IfMatchHeader = "If-Match"; public const string IfNoneMatchHeader = "If-None-Match"; public const string IfUnmodifiedSinceHeader = "If-Unmodified-Since"; public const string ConfirmSelfBucketAccess = "x-amz-confirm-remove-self-bucket-access"; public const string ContentRangeHeader = "Content-Range"; public const string ContentTypeHeader = "Content-Type"; public const string ContentLengthHeader = "Content-Length"; public const string ContentMD5Header = "Content-MD5"; public const string ContentEncodingHeader = "Content-Encoding"; public const string ContentDispositionHeader = "Content-Disposition"; public const string ETagHeader = "ETag"; public const string Expires = "Expires"; public const string AuthorizationHeader = "Authorization"; public const string HostHeader = "host"; public const string UserAgentHeader = "User-Agent"; public const string LocationHeader = "location"; public const string DateHeader = "Date"; public const string RangeHeader = "Range"; public const string ExpectHeader = "Expect"; public const string AcceptHeader = "Accept"; public const string ConnectionHeader = "Connection"; public const string StatusHeader = "Status"; public const string XHttpMethodOverrideHeader = "X-HTTP-Method-Override"; public const string TransferEncodingHeader = "transfer-encoding"; public const string RequestIdHeader = "x-amzn-RequestId"; public const string XAmzId2Header = "x-amz-id-2"; public const string XAmzCloudFrontIdHeader = "X-Amz-Cf-Id"; public const string XAmzRequestIdHeader = "x-amz-request-id"; public const string XAmzDateHeader = "X-Amz-Date"; public const string XAmzErrorType = "x-amzn-ErrorType"; public const string XAmznErrorMessage = "x-amzn-error-message"; public const string XAmzSignedHeadersHeader = "X-Amz-SignedHeaders"; public const string XAmzContentSha256Header = "X-Amz-Content-SHA256"; public const string XAmzDecodedContentLengthHeader = "X-Amz-Decoded-Content-Length"; public const string XAmzSecurityTokenHeader = "x-amz-security-token"; public const string XAmzAuthorizationHeader = "X-Amzn-Authorization"; public const string XAmzRegionSetHeader = "X-Amz-Region-Set"; public const string XAmzNonceHeader = "x-amz-nonce"; public const string XAmzServerSideEncryptionHeader = "x-amz-server-side-encryption"; public const string XAmzServerSideEncryptionAwsKmsKeyIdHeader = "x-amz-server-side-encryption-aws-kms-key-id"; public const string XAmzBucketRegion = "x-amz-bucket-region"; public const string XAmzAccountId = "x-amz-account-id"; public const string XAmzOutpostId = "x-amz-outpost-id"; public const string XAmzApiVersion = "x-amz-api-version"; public const string XAmzExpires = "X-Amz-Expires"; public const string XAmzSignature = "X-Amz-Signature"; public const string XAmzAlgorithm = "X-Amz-Algorithm"; public const string XAmzCredential = "X-Amz-Credential"; public const string XAmzTrailerHeader = "X-Amz-Trailer"; public const string XAmzSSECustomerAlgorithmHeader = "x-amz-server-side-encryption-customer-algorithm"; public const string XAmzSSECustomerKeyHeader = "x-amz-server-side-encryption-customer-key"; public const string XAmzSSECustomerKeyMD5Header = "x-amz-server-side-encryption-customer-key-MD5"; public const string XAmzCopySourceSSECustomerAlgorithmHeader = "x-amz-copy-source-server-side-encryption-customer-algorithm"; public const string XAmzCopySourceSSECustomerKeyHeader = "x-amz-copy-source-server-side-encryption-customer-key"; public const string XAmzCopySourceSSECustomerKeyMD5Header = "x-amz-copy-source-server-side-encryption-customer-key-MD5"; public const string XAmzStorageClassHeader = "x-amz-storage-class"; public const string XAmzWebsiteRedirectLocationHeader = "x-amz-website-redirect-location"; public const string XAmzContentLengthHeader = "x-amz-content-length"; public const string XAmzAclHeader = "x-amz-acl"; public const string XAmzCopySourceHeader = "x-amz-copy-source"; public const string XAmzCopySourceRangeHeader = "x-amz-copy-source-range"; public const string XAmzCopySourceIfMatchHeader = "x-amz-copy-source-if-match"; public const string XAmzCopySourceIfModifiedSinceHeader = "x-amz-copy-source-if-modified-since"; public const string XAmzCopySourceIfNoneMatchHeader = "x-amz-copy-source-if-none-match"; public const string XAmzCopySourceIfUnmodifiedSinceHeader = "x-amz-copy-source-if-unmodified-since"; public const string XAmzMetadataDirectiveHeader = "x-amz-metadata-directive"; public const string XAmzMfaHeader = "x-amz-mfa"; public const string XAmzVersionIdHeader = "x-amz-version-id"; public const string XAmzUserAgentHeader = "x-amz-user-agent"; public const string XAmzAbortDateHeader = "x-amz-abort-date"; public const string XAmzAbortRuleIdHeader = "x-amz-abort-rule-id"; public const string XAmznTraceIdHeader = "x-amzn-trace-id"; public const string XAwsEc2MetadataTokenTtlSeconds = "x-aws-ec2-metadata-token-ttl-seconds"; public const string XAwsEc2MetadataToken = "x-aws-ec2-metadata-token"; public const string AmzSdkInvocationId = "amz-sdk-invocation-id"; public const string AmzSdkRequest = "amz-sdk-request"; public const string XAmzQueryError = "x-amzn-query-error"; } }
115
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Runtime; using System.IO; namespace Amazon.Util { public interface ICryptoUtil { string HMACSign(string data, string key, SigningAlgorithm algorithmName); string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName); byte[] ComputeSHA1Hash(byte[] data); byte[] ComputeSHA256Hash(byte[] data); byte[] ComputeSHA256Hash(Stream steam); byte[] ComputeMD5Hash(byte[] data); byte[] ComputeMD5Hash(Stream steam); byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName); string ComputeCRC32Hash(byte[] data); string ComputeCRC32CHash(byte[] data); } }
39
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace Amazon.Util { internal class PaginatedResource<U> : IEnumerable<U> { internal Func<string, Marker<U>> fetcher; internal PaginatedResource(Func<string, Marker<U>> fetcher) { this.fetcher = fetcher; } IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) GetEnumerator(); } public IEnumerator<U> GetEnumerator() { return new PaginationEnumerator<U>(this); } } internal class Marker<U> { private List<U> data; private string nextToken; internal Marker(List<U> data, string nextToken) { this.data = data; this.nextToken = nextToken; } internal List<U> Data { get { return this.data; } } internal string NextToken { get { return this.nextToken; } } } internal class PaginationEnumerator<U> : IEnumerator<U> { private PaginatedResource<U> paginatedResource; private int position = -1; private static Marker<U> blankSpot = new Marker<U>(new List<U>(), (string)null); private Marker<U> currentSpot = blankSpot; bool started = false; internal PaginationEnumerator(PaginatedResource<U> paginatedResource) { this.paginatedResource = paginatedResource; } public bool MoveNext() { position++; while (position == currentSpot.Data.Count) { if (!started || !string.IsNullOrEmpty(currentSpot.NextToken)) { currentSpot = paginatedResource.fetcher(currentSpot.NextToken); position = 0; started = true; } else { currentSpot = blankSpot; position = -1; } } return (position != -1); } public void Reset() { position = -1; currentSpot = new Marker<U>(new List<U>(), (string)null); started = false; } object IEnumerator.Current { get { return Current; } } public U Current { get { try { return currentSpot.Data[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } public void Dispose() { } } }
140
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Globalization; using Amazon.Util.Internal; namespace Amazon.Util { public static class PaginatedResourceFactory { public static object Create<TItemType, TRequestType, TResponseType>(PaginatedResourceInfo pri) { pri.Verify(); return Create<TItemType, TRequestType, TResponseType>(pri.Client, pri.MethodName, pri.Request, pri.TokenRequestPropertyPath, pri.TokenResponsePropertyPath, pri.ItemListPropertyPath); } private static PaginatedResource<ItemType> Create<ItemType, TRequestType, TResponseType> (object client, string methodName, object request, string tokenRequestPropertyPath, string tokenResponsePropertyPath, string itemListPropertyPath) { ITypeInfo clientType = TypeFactory.GetTypeInfo(client.GetType()); MethodInfo fetcherMethod = clientType.GetMethod(methodName, new ITypeInfo[] { TypeFactory.GetTypeInfo(typeof(TRequestType)) }); Type funcType = GetFuncType<TRequestType, TResponseType>(); Func<TRequestType, TResponseType> call = (req) => { return (TResponseType)fetcherMethod.Invoke(client, new object[] { req }); }; return Create<ItemType, TRequestType, TResponseType>(call, (TRequestType)request, tokenRequestPropertyPath, tokenResponsePropertyPath, itemListPropertyPath); } private static PaginatedResource<ItemType> Create<ItemType, TRequestType, TResponseType> (Func<TRequestType, TResponseType> call, TRequestType request, string tokenRequestPropertyPath, string tokenResponsePropertyPath, string itemListPropertyPath) { Func<string, Marker<ItemType>> fetcher = token => { List<ItemType> currentItems; string nextToken; SetPropertyValueAtPath(request, tokenRequestPropertyPath, token); TResponseType nextSet = call(request); nextToken = GetPropertyValueFromPath<string>(nextSet, tokenResponsePropertyPath); currentItems = GetPropertyValueFromPath<List<ItemType>>(nextSet, itemListPropertyPath); return new Marker<ItemType>(currentItems, nextToken); }; return new PaginatedResource<ItemType>(fetcher); } private static void SetPropertyValueAtPath(object instance, string path, string value) { String[] propPath = path.Split('.'); object currentValue = instance; Type currentType = instance.GetType(); PropertyInfo currentProperty = null; int i = 0; for (; i < propPath.Length - 1; i++) { string property = propPath[i]; currentProperty = TypeFactory.GetTypeInfo(currentType).GetProperty(property); currentValue = currentProperty.GetValue(currentValue, null); currentType = currentProperty.PropertyType; } currentProperty = TypeFactory.GetTypeInfo(currentType).GetProperty(propPath[i]); currentProperty.SetValue(currentValue, value, null); } private static T GetPropertyValueFromPath<T>(object instance, string path) { String[] propPath = path.Split('.'); object currentValue = instance; Type currentType = instance.GetType(); PropertyInfo currentProperty = null; foreach (string property in propPath) { currentProperty = TypeFactory.GetTypeInfo(currentType).GetProperty(property); currentValue = currentProperty.GetValue(currentValue, null); currentType = currentProperty.PropertyType; } return (T)currentValue; } internal static Type GetPropertyTypeFromPath(Type start, string path) { String[] propPath = path.Split('.'); Type currentType = start; PropertyInfo currentProperty = null; foreach (string property in propPath) { currentProperty = TypeFactory.GetTypeInfo(currentType).GetProperty(property); currentType = currentProperty.PropertyType; } return currentType; } private static Type GetFuncType<T, U>() { return typeof(Func<T, U>); } internal static T Cast<T>(object o) { return (T)o; } } public class PaginatedResourceInfo { private string tokenRequestPropertyPath; private string tokenResponsePropertyPath; internal object Client { get; set; } internal string MethodName { get; set; } internal object Request { get; set; } internal string TokenRequestPropertyPath { get { string ret = tokenRequestPropertyPath; if (String.IsNullOrEmpty(ret)) { ret = "NextToken"; } return ret; } set { tokenRequestPropertyPath = value; } } internal string TokenResponsePropertyPath { get { string ret = tokenResponsePropertyPath; if (String.IsNullOrEmpty(ret)) { ret = "{0}"; if (Client != null && !String.IsNullOrEmpty(MethodName)) { MethodInfo mi = TypeFactory.GetTypeInfo(Client.GetType()).GetMethod(MethodName); if (mi != null) { Type responseType = mi.ReturnType; string baseName = responseType.Name; if (baseName.EndsWith("Response", StringComparison.Ordinal)) { baseName = baseName.Substring(0, baseName.Length - 8); } if (TypeFactory.GetTypeInfo(responseType).GetProperty(string.Format(CultureInfo.InvariantCulture, "{0}Result", baseName)) != null) { ret = string.Format(CultureInfo.InvariantCulture, ret, string.Format(CultureInfo.InvariantCulture, "{0}Result.{1}", baseName, "{0}")); } } } ret = string.Format(CultureInfo.InvariantCulture, ret, "NextToken"); } return ret; } set { tokenResponsePropertyPath = value; } } internal string ItemListPropertyPath { get; set; } public PaginatedResourceInfo WithClient(object client) { Client = client; return this; } public PaginatedResourceInfo WithMethodName(string methodName) { MethodName = methodName; return this; } public PaginatedResourceInfo WithRequest(object request) { Request = request; return this; } public PaginatedResourceInfo WithTokenRequestPropertyPath(string tokenRequestPropertyPath) { TokenRequestPropertyPath = tokenRequestPropertyPath; return this; } public PaginatedResourceInfo WithTokenResponsePropertyPath(string tokenResponsePropertyPath) { TokenResponsePropertyPath = tokenResponsePropertyPath; return this; } public PaginatedResourceInfo WithItemListPropertyPath(string itemListPropertyPath) { ItemListPropertyPath = itemListPropertyPath; return this; } internal void Verify() { //Client is set if (Client == null) { throw new ArgumentException("PaginatedResourceInfo.Client needs to be set."); } //MethodName exists on Client and takes one argument of the declared request type Type clientType = Client.GetType(); MethodInfo mi = TypeFactory.GetTypeInfo(clientType).GetMethod(MethodName, new ITypeInfo[] { TypeFactory.GetTypeInfo(Request.GetType()) }); if (mi == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "{0} has no method called {1}", clientType.Name, MethodName)); } //Request is valid type. Type requestType = mi.GetParameters()[0].ParameterType; try { Convert.ChangeType(Request, requestType, CultureInfo.InvariantCulture); } catch (Exception) { throw new ArgumentException("PaginatedResourcInfo.Request is an incompatible type."); } //Properties exist Type responseType = mi.ReturnType; VerifyProperty("TokenRequestPropertyPath", requestType, TokenRequestPropertyPath, typeof(string)); VerifyProperty("TokenResponsePropertyPath", responseType, TokenResponsePropertyPath, typeof(string)); VerifyProperty("ItemListPropertyPath", responseType, ItemListPropertyPath, typeof(string), true); } private static void VerifyProperty(string propName, Type start, string path, Type expectedType) { VerifyProperty(propName, start, path, expectedType, false); } private static void VerifyProperty(string propName, Type start, string path, Type expectedType, bool skipTypecheck) { Type type = null; if (String.IsNullOrEmpty(path)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "{0} must contain a value.", propName)); } try { type = PaginatedResourceFactory.GetPropertyTypeFromPath(start, path); } catch (Exception) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "{0} does not exist on {1}", path, start.Name)); } if (!skipTypecheck && type != expectedType) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "{0} on {1} is not of type {2}", path, start.Name, expectedType.Name)); } } } }
297
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ namespace Amazon.Util { /// <summary> /// Class that contains result of executing an external process through the SDKs /// AWSSDKUtils.RunProcess/AWSSDKUtils.RunProcessAsync /// </summary> public class ProcessExecutionResult { /// <summary> /// The exit code with which the process exited /// </summary> public int ExitCode { get; set; } /// <summary> /// The output of the process read till the end /// </summary> public string StandardOutput { get; set; } /// <summary> /// The error output of the process read till the end /// </summary> public string StandardError { get; set; } } }
43
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using Amazon.Runtime; using Amazon.Runtime.Internal.Settings; using Amazon.Runtime.Internal.Util; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; namespace Amazon.Util { /// <summary> /// This class allows profiles supporting AWS credentials and SAML-based authentication to be registered with /// the SDK so that they can later be reference by a profile name. The credential profiles will be available /// for use in the AWS Toolkit for Visual Studio and the AWS Tools for Windows PowerShell. /// <para> /// The credentials are stored under the current users AppData folder encrypted using Windows Data Protection API. /// </para> /// <para> /// To reference a profile from an application's App.config or Web.config use the AWSProfileName setting. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="development"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// </para> /// </summary> [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.NetSDKCredentialsFile, SharedCredentialsFile, or SAMLEndpointManager. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] public static class ProfileManager { // if a profile does not contain a profile type entry, we assume AWS credentials public const string AWSCredentialsProfileType = "AWS"; public const string SAMLRoleProfileType = "SAML"; public static bool IsAvailable { get { return UserCrypto.IsUserCryptAvailable; } } /// <summary> /// Registers an AWS credentials profile that can later be referenced by the profileName. /// This profile will only be visible for the current user. /// </summary> /// <param name="profileName">Name given to the AWS credentials.</param> /// <param name="accessKeyId">The AWS access key id</param> /// <param name="secretKey">The AWS secret key</param> public static void RegisterProfile(string profileName, string accessKeyId, string secretKey) { AWSCredentialsProfile.Persist(profileName, accessKeyId, secretKey); } /// <summary> /// <para> /// Registers a role-based profile to be used with SAML authentication. The profile contains /// details of the role to be assumed when AWS credentials are requested based on the role and /// a reference to a SAML endpoint profile containing details of the endpoint to be called to /// authenticate the user. /// </para> /// <para> /// If user identity information is not supplied then the identity of the logged-in user will /// be used when authenticaton is performed against the endpoint referenced in the SAML endpoint /// profile. If identity is provided, no password information is stored in the role profile and /// the user must supply the password for the identity prior to authentication with the endpoint. /// </para> /// </summary> /// <param name="profileName">Name to be assigned to the profile</param> /// <param name="endpointName"> /// The name assigned to the endpoint settings, previously saved with RegisterSAMLEndpoint. /// </param> /// <param name="roleArn"> /// The arn of the role that the user wants to assume when using this profile. This /// must be one of the set returned by the saml endpoint when the user authenticates. /// </param> /// <param name="userIdentity"> /// Optional. By default the identity of the logged-in user will be used when authentication /// is performed - the user will not be prompted to supply a password. By supplying a custom /// identity for this parameter, the user will be prompted to supply the password for the /// identity prior to authentication. /// </param> public static void RegisterSAMLRoleProfile(string profileName, string endpointName, string roleArn, string userIdentity) { RegisterSAMLRoleProfile(profileName, endpointName, roleArn, userIdentity, null); } /// <summary> /// <para> /// Registers a role-based profile to be used with SAML authentication. The profile contains /// details of the role to be assumed when AWS credentials are requested based on the role and /// a reference to a SAML endpoint profile containing details of the endpoint to be called to /// authenticate the user. /// </para> /// <para> /// If user identity information is not supplied then the identity of the logged-in user will /// be used when authenticaton is performed against the endpoint referenced in the SAML endpoint /// profile. If identity is provided, no password information is stored in the role profile and /// the user must supply the password for the identity prior to authentication with the endpoint. /// </para> /// </summary> /// <param name="profileName">Name to be assigned to the profile</param> /// <param name="endpointName"> /// The name assigned to the endpoint settings, previously saved with RegisterSAMLEndpoint. /// </param> /// <param name="roleArn"> /// The arn of the role that the user wants to assume when using this profile. This /// must be one of the set returned by the saml endpoint when the user authenticates. /// </param> /// <param name="userIdentity"> /// Optional. By default the identity of the logged-in user will be used when authentication /// is performed - the user will not be prompted to supply a password. By supplying a custom /// identity for this parameter, the user will be prompted to supply the password for the /// identity prior to authentication. /// </param> /// <param name="stsRegion"> /// Set for profiles intended to be used in regions where a region-specific STS endpoint /// must be used (eg cn-north-1). If left empty/null, the global sts.amazonaws.com endpoint /// will be used when credentials are obtained for this profile. /// </param> public static void RegisterSAMLRoleProfile(string profileName, string endpointName, string roleArn, string userIdentity, string stsRegion) { SAMLRoleProfile.Persist(profileName, endpointName, roleArn, userIdentity, null, stsRegion); } /// <summary> /// Registers an endpoint to be used in conjunction with SAML role profiles. The role profiles /// reference the endpoint settings to obtain the actual endpoint and any customization settings /// needed to perform authentication. /// </summary> /// <param name="endpointName">Name to be assigned to the endpoint settings.</param> /// <param name="endpoint">The full uri of the authentication endpoint.</param> /// <param name="authenticationType"> /// The authentication type to use when performing calls against the endpoint. Valid values are 'NTLM', /// 'Digest', 'Kerberos' and 'Negotiate'. The default if not configured (null/empty string) is 'Kerberos'. /// </param> /// <returns>The unique id assigned to the new settings.</returns> public static string RegisterSAMLEndpoint(string endpointName, Uri endpoint, string authenticationType) { return SAMLEndpointSettings.Persist(endpointName, endpoint, authenticationType); } /// <summary> /// Deletes the settings for an AWS credentials or SAML role profile from the SDK account store. /// </summary> /// <param name="profileName">The name of the profile to remove.</param> public static void UnregisterProfile(string profileName) { var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); var os = ReadProfileSettings(settings, profileName); if (os != null) { settings.Remove(os.UniqueKey); PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredProfiles, settings); } } /// <summary> /// Lists all profile names registered with the SDK account store. /// </summary> /// <returns>The profile names.</returns> public static IEnumerable<string> ListProfileNames() { var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); return settings.Select(os => os.GetValueOrDefault(SettingsConstants.DisplayNameField, null)).ToList(); } /// <summary> /// Loads and returns all available credential profiles registered in the store. /// </summary> /// <returns>Collection of profiles.</returns> public static IEnumerable<ProfileSettingsBase> ListProfiles() { var profiles = new List<ProfileSettingsBase>(); var profileNames = ListProfileNames(); foreach (var profileName in profileNames) { try { if (SAMLRoleProfile.CanCreateFrom(profileName)) profiles.Add(SAMLRoleProfile.LoadFrom(profileName)); else if (AWSCredentialsProfile.CanCreateFrom(profileName)) profiles.Add(AWSCredentialsProfile.LoadFrom(profileName)); } catch (Exception e) { Logger.GetLogger(typeof(ProfileManager)).Error(e, "Error loading AWS credential or SAML role profile '{0}'", profileName); } } return profiles; } /// <summary> /// Checks if a given profile is known in the SDK credential store. /// </summary> /// <param name="profileName">The name of the profile to test for existence</param> /// <returns>True if the profile exists.</returns> public static bool IsProfileKnown(string profileName) { return (ReadProfileSettings(profileName) != null); } /// <summary> /// Copies the contents of the source profile to the destination. If the destination /// profile does not exist a new profile is created. Note that if the destination /// profile exists, all keys it contains are removed and replaced with keys from the /// source profile. /// </summary> /// <param name="sourceProfileName">The name of the profile to copy from.</param> /// <param name="destinationProfileName">The name of the profile to create or update.</param> /// <returns>The unique id assigned to the destination settings.</returns> public static string CopyProfileSettings(string sourceProfileName, string destinationProfileName) { var sourceSettings = ReadProfileSettings(sourceProfileName); if (sourceSettings == null) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "An AWS credentials or SAML role profile with name '{0}' could not be found.", sourceProfileName)); return CopyProfileSettings(sourceSettings, destinationProfileName); } /// <summary> /// Copies the contents of the source profile to the destination. If the destination /// profile does not exist a new profile is created. Note that if the destination /// profile exists, all keys it contains are removed and replaced with keys from the /// source profile. /// </summary> /// <param name="source">The source profile to copy keys and values from.</param> /// <param name="destinationProfileName">The name of the profile to create or update.</param> /// <returns>The unique id assigned to the destination settings.</returns> public static string CopyProfileSettings(SettingsCollection.ObjectSettings source, string destinationProfileName) { var allSettings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); var destination = ReadProfileSettings(allSettings, destinationProfileName); // overwrite with new object if dest exists, not merge, otherwise we can potentially mix credential // profile types if (destination == null) destination = allSettings.NewObjectSettings(Guid.NewGuid().ToString()); else destination = allSettings.NewObjectSettings(destination.UniqueKey); destination[SettingsConstants.DisplayNameField] = destinationProfileName; foreach (var k in source.Keys) { if (!k.Equals(SettingsConstants.DisplayNameField)) destination[k] = source[k]; } PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredProfiles, allSettings); return destination.UniqueKey; } /// <summary> /// Tries to get the AWS credentials from a profile in the SDK account store. /// </summary> /// <param name="profileName">The profile to get the credentials for.</param> /// <param name="credentials">Outputs the credentials for the profile.</param> /// <returns>Returns true if the profile exists otherwise false is returned.</returns> public static bool TryGetAWSCredentials(string profileName, out AWSCredentials credentials) { credentials = null; try { AWSCredentialsProfile profile; if (TryGetProfile(profileName, out profile)) credentials = profile.Credentials; } catch (Exception e) { Logger.GetLogger(typeof(ProfileManager)).Error(e, "Error loading AWS credentials from profile {0}", profileName); } return credentials != null; } /// <summary> /// Gets the AWS credentials from a profile in the SDK account store. /// </summary> /// <param name="profileName">The profile to get the credentials for.</param> /// <returns>The AWS credentials for the profile.</returns> /// <exception cref="AmazonClientException">Thrown if the profile does not exist</exception> public static AWSCredentials GetAWSCredentials(string profileName) { AWSCredentialsProfile profile; if (TryGetProfile(profileName, out profile)) return profile.Credentials; throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "A profile named {0} has not been registered or contains invalid data.", profileName)); } /// <summary> /// Returns the profile with the specified name, if it has been registered in the SDK store. /// </summary> /// <param name="profileName">The name of the registered profile</param> /// <returns>The loaded profile data</returns> public static ProfileSettingsBase GetProfile(string profileName) { if (!IsProfileKnown(profileName)) throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "A profile named {0} has not been registered.", profileName)); var profile = GetProfile<AWSCredentialsProfile>(profileName) ?? (ProfileSettingsBase) GetProfile<SAMLRoleProfile>(profileName); if (profile == null) throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "A profile named {0} was found but could not be loaded.", profileName)); return profile; } /// <summary> /// Returns the persisted data in the SDK store as a profile of the specified type T. /// </summary> /// <param name="profileName">The name of the profile holding the settings.</param> /// <returns>The loaded profile. An exception is thrown if the profile could not be loaded.</returns> /// <exception cref="AmazonClientException">Thrown if the profile does not exist</exception> /// <remarks> /// Currently supported profile types: AWSCredentialsProfile and SAMLRoleProfile. /// </remarks> public static T GetProfile<T>(string profileName) where T : ProfileSettingsBase { if (typeof(T) == typeof(AWSCredentialsProfile)) return AWSCredentialsProfile.LoadFrom(profileName) as T; if (typeof(T) == typeof(SAMLRoleProfile)) return SAMLRoleProfile.LoadFrom(profileName) as T; throw new ArgumentException("Unrecognized profile type parameter"); } /// <summary> /// Tries to load the specified profile data corresponding to profile type T from a named /// profile in the SDK account store. /// </summary> /// <param name="profileName">The name of the profile holding the settings.</param> /// <param name="profile">The loaded profile data.</param> /// <returns>Returns true if the profile exists otherwise false is returned.</returns> /// <remarks> /// Currently supported profile types: AWSCredentialsProfile and SAMLRoleProfile. /// </remarks> public static bool TryGetProfile<T>(string profileName, out T profile) where T : ProfileSettingsBase { profile = null; try { if (typeof(T) == typeof(AWSCredentialsProfile)) profile = AWSCredentialsProfile.LoadFrom(profileName) as T; else if (typeof(T) == typeof(SAMLRoleProfile)) profile = SAMLRoleProfile.LoadFrom(profileName) as T; else throw new ArgumentException("Unrecognized profile type parameter", (typeof(T).FullName)); } catch (Exception e) { Logger.GetLogger(typeof(ProfileManager)).Error(e, "Unable to load profile {0}, unknown profile, missing/invalid data or unrecognized profile type.", profileName); } return profile != null; } /// <summary> /// Attempts to load the settings defining a SAML endpoint. /// </summary> /// <param name="endpointName">The name assigned to the settings for the endpoint.</param> /// <param name="endpointSettings">The instantiated endpoint.</param> /// <returns>True if the settings were successfully loaded.</returns> public static bool TryGetSAMLEndpoint(string endpointName, out SAMLEndpointSettings endpointSettings) { endpointSettings = null; try { endpointSettings = SAMLEndpointSettings.LoadFrom(endpointName); } catch (Exception e) { Logger.GetLogger(typeof(ProfileManager)).Error(e, "Unable to load SAML endpoint profile '{0}', unknown profile or missing/invalid data.", endpointName); } return endpointSettings != null; } /// <summary> /// Loads the settings defining a SAML endpoint. /// </summary> /// <param name="endpointName">The name assigned to the settings for the endpoint.</param> /// <returns>The loaded settings. An exception is thrown if they could not be loaded.</returns> /// <exception cref="AmazonClientException">Thrown if the endpoint settings do not exist.</exception> public static SAMLEndpointSettings GetSAMLEndpoint(string endpointName) { SAMLEndpointSettings endpointSettings; if (!TryGetSAMLEndpoint(endpointName, out endpointSettings)) throw new AmazonClientException(string.Format(CultureInfo.InvariantCulture, "A SAML endpoint profile with name {0} has not been registered or is invalid.", endpointName)); return endpointSettings; } internal static SettingsCollection.ObjectSettings ReadProfileSettings(string profileName) { var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); return ReadProfileSettings(settings, profileName); } internal static SettingsCollection.ObjectSettings ReadProfileSettings(SettingsCollection settings, string profileName) { return settings.FirstOrDefault(x => string.Equals(x[SettingsConstants.DisplayNameField], profileName, StringComparison.OrdinalIgnoreCase)); } internal static SettingsCollection.ObjectSettings ReadSettings(SettingsCollection settings, string settingsKey) { return settings.FirstOrDefault(x => string.Equals(x.UniqueKey, settingsKey, StringComparison.OrdinalIgnoreCase)); } } /// <summary> /// Common base contract for all types of credential and role profiles. /// </summary> [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.CredentialProfile. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] public abstract class ProfileSettingsBase { /// <summary> /// The user-defined name for the settings. /// </summary> public string Name { get; protected set; } /// <summary> /// The unique id of the profile in the backing store. /// </summary> public string UniqueId { get; protected set; } /// <summary> /// Saves the profile data to backing store, returning the unique id /// assigned to the data. /// </summary> public abstract string Persist(); protected static SettingsCollection.ObjectSettings LoadCredentialsProfile(string profileName) { var os = ProfileManager.ReadProfileSettings(profileName); if (os == null) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "An AWS credentials or SAML role profile with name '{0}' could not be found.", profileName)); return os; } } /// <summary> /// The persisted data for a set of AWS credentials. At a minimum this /// is access key and secret key data. /// </summary> [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.CredentialProfile. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] public class AWSCredentialsProfile : ProfileSettingsBase { public BasicAWSCredentials Credentials { get; private set; } /// <summary> /// Tests if an AWSCredentialsProfile instance could be instantiated from /// the persisted settings data. /// </summary> /// <param name="profileName">The name given to the persisted settings (previously verified as existing).</param> /// <returns>True if the settings are compatible with an AWSCredentialsProfile type.</returns> public static bool CanCreateFrom(string profileName) { var os = LoadCredentialsProfile(profileName); return CanCreateFrom(os); } /// <summary> /// Tests if an AWSCredentialsProfile instance could be instantiated from /// the persisted settings data. /// </summary> /// <param name="os">The persisted settings.</param> /// <returns>True if the settings are compatible with an AWSCredentialsProfile type.</returns> public static bool CanCreateFrom(SettingsCollection.ObjectSettings os) { var osProfileType = os.GetValueOrDefault(SettingsConstants.ProfileTypeField, null); // legacy AWS profiles will not have the type key present if (osProfileType == null || osProfileType.Equals(ProfileManager.AWSCredentialsProfileType, StringComparison.OrdinalIgnoreCase)) { try { Validate(os); return true; } catch (InvalidDataException) { var msg = (string.Format(CultureInfo.InvariantCulture, "Profile '{0}' indicates AWS credential type but does not contain AWS credential key materials", os[SettingsConstants.DisplayNameField])); Logger.GetLogger(typeof(AWSCredentialsProfile)).InfoFormat(msg); } } return false; } /// <summary> /// Instantiates an AWSCredentialsProfile instance from the specified profile name. /// </summary> /// <param name="profileName">The name of the profile holding the settings.</param> /// <returns>New credentials profile instance. An exception is thrown if the profile data is invalid.</returns> public static AWSCredentialsProfile LoadFrom(string profileName) { var os = LoadCredentialsProfile(profileName); return LoadFrom(os); } /// <summary> /// Instantiates an AWSCredentialsProfile instance from the supplied settings collection. /// </summary> /// <param name="os">The settings representing the stored profile.</param> /// <returns>New credentials profile instance. An exception is thrown if the profile data is invalid.</returns> public static AWSCredentialsProfile LoadFrom(SettingsCollection.ObjectSettings os) { if (os == null) throw new ArgumentNullException("os"); if (!CanCreateFrom(os)) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Profile '{0}' does not contain AWS credential materials", os[SettingsConstants.DisplayNameField])); Validate(os); var accessKeyId = os.GetValueOrDefault(SettingsConstants.AccessKeyField, null); var secretkey = os.GetValueOrDefault(SettingsConstants.SecretKeyField, null); return new AWSCredentialsProfile(os[SettingsConstants.DisplayNameField], accessKeyId, secretkey); } /// <summary> /// Validates the contents of the specified profile. /// </summary> /// <param name="profileName">The name of the AWS credentials profile to validate.</param> /// <exception cref="InvalidDataException">Thrown if the profile settings fail to validate.</exception> public static void Validate(string profileName) { var os = LoadCredentialsProfile(profileName); Validate(os); } /// <summary> /// Verifies that the persisted settings contains the minimal viable data to /// instantiate an AWSCredentialsProfile instance. /// </summary> /// <param name="os">The persisted settings.</param> /// <exception cref="InvalidDataException">Thrown if the profile settings fail to validate.</exception> private static void Validate(SettingsCollection.ObjectSettings os) { var accessKeyId = os.GetValueOrDefault(SettingsConstants.AccessKeyField, null); if (accessKeyId == null) throw new InvalidDataException("Missing or invalid access key value in the profile settings."); var secretkey = os.GetValueOrDefault(SettingsConstants.SecretKeyField, null); if (secretkey == null) throw new InvalidDataException("Missing or invalid secret key value in the profile settings."); } /// <summary> /// Persists the profile data to the store file. /// </summary> /// <returns>The unique ID assigned to the settings.</returns> public override string Persist() { return Persist(Name, Credentials.GetCredentials().AccessKey, Credentials.GetCredentials().SecretKey); } /// <summary> /// Creates or updates the profile data in the store file. /// </summary> /// <returns>The unique ID assigned to the settings.</returns> public static string Persist(string profileName, string accessKeyId, string secretKey) { var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); var os = ProfileManager.ReadProfileSettings(settings, profileName); if (os == null) os = settings.NewObjectSettings(Guid.NewGuid().ToString()); os[SettingsConstants.ProfileTypeField] = ProfileManager.AWSCredentialsProfileType; os[SettingsConstants.DisplayNameField] = profileName; os[SettingsConstants.AccessKeyField] = accessKeyId; os[SettingsConstants.SecretKeyField] = secretKey; PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredProfiles, settings); return os.UniqueKey; } private AWSCredentialsProfile(string profileName, string accessKeyId, string secretKey) { Name = profileName; Credentials = new BasicAWSCredentials(accessKeyId, secretKey); } } /// <summary> /// The persisted data for a SAML endpoint. One or more role profiles /// will reference this to obtain the common endpoint and other data needed /// to perform authentication with a set of user credentials. /// </summary> [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialManagement.SAMLEndpoint. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] public class SAMLEndpointSettings : ProfileSettingsBase { /// <summary> /// The default authentication type to use when attempting to perform an /// authentication call against the configured endpoint. /// </summary> public static readonly string DefaultAuthenticationType = "Kerberos"; /// <summary> /// The authentication endpoint which must be a HTTPS scheme. /// </summary> public Uri Endpoint { get; private set; } private string _authenticationType = null; /// <summary> /// The authentication type to use when calling the endpoint. /// </summary> public string AuthenticationType { get { return string.IsNullOrEmpty(_authenticationType) ? DefaultAuthenticationType : _authenticationType; } } /// <summary> /// Tests if a SAMLEndpointSettings instance could be instantiated from /// the persisted settings data. /// </summary> /// <param name="endpointName">The name given to the persisted settings.</param> /// <returns>True if the settings are compatible.</returns> public static bool CanCreateFrom(string endpointName) { var os = LoadSettings(endpointName); return CanCreateFrom(os); } /// <summary> /// Tests if a SAMLEndpointSettings instance could be instantiated from /// the persisted settings data. /// </summary> /// <param name="os">The persisted settings.</param> /// <returns>True if the settings are compatible.</returns> public static bool CanCreateFrom(SettingsCollection.ObjectSettings os) { var endpoint = os.GetValueOrDefault(SettingsConstants.EndpointField, null); return !string.IsNullOrEmpty(endpoint); } /// <summary> /// Instantiates an instance from settings stored with the specified name. /// </summary> /// <param name="endpointName">The name of the endpoint settings in the store.</param> /// <returns>Profile instance or an exception if the profile data does not exist/contains invalid data.</returns> public static SAMLEndpointSettings LoadFrom(string endpointName) { var os = LoadSettings(endpointName); return LoadFrom(os); } /// <summary> /// Instantiates an instance from the supplied settings. /// </summary> /// <param name="os">The persisted settings.</param> /// <returns>Profile instance or an exception if the profile data is invalid.</returns> public static SAMLEndpointSettings LoadFrom(SettingsCollection.ObjectSettings os) { if (os == null) throw new ArgumentNullException("os"); if (!CanCreateFrom(os)) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Endpoint settings '{0}' does not contain SAML endpoint materials", os[SettingsConstants.DisplayNameField])); Validate(os); var endpoint = os.GetValueOrDefault(SettingsConstants.EndpointField, null); string authenticationType = os.GetValueOrDefault(SettingsConstants.AuthenticationTypeField, null); return new SAMLEndpointSettings(os[SettingsConstants.DisplayNameField], new Uri(endpoint, UriKind.RelativeOrAbsolute), authenticationType); } /// <summary> /// Validates the contents of the specified endpoint settings. /// </summary> /// <param name="endpointName">The name of the SAML endpoint settings to validate.</param> /// <exception cref="InvalidDataException">Thrown if the settings fail to validate.</exception> public static void Validate(string endpointName) { var os = LoadSettings(endpointName); Validate(os); } /// <summary> /// Verifies that the persisted settings contains the minimal viable data to /// instantiate a SAMLEndpointSettings instance. /// </summary> /// <param name="os">The persisted settings.</param> /// <exception cref="InvalidDataException">Thrown if the settings fail to validate.</exception> private static void Validate(SettingsCollection.ObjectSettings os) { var endpoint = os.GetValueOrDefault(SettingsConstants.EndpointField, null); if (endpoint == null) throw new InvalidDataException("Missing endpoint value in the profile settings."); try { var u = new Uri(endpoint); if (!string.Equals(u.Scheme, "https", StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("The scheme of the endpoint must be HTTPS."); } catch (UriFormatException e) { throw new InvalidDataException("The configured endpoint is not valid.", e); } } /// <summary> /// Persists the settings to the storage file. /// </summary> /// <returns>The unique id assigned to the profile</returns> public override string Persist() { return Persist(Name, Endpoint, AuthenticationType); } /// <summary> /// Creates or updates the settings data for a SAML endpoint in the backing store file. An error is /// thrown if the scheme for the endpoint is not https. /// </summary> /// <param name="settingsName">The name of the settings to create or update</param> /// <param name="endpoint">The authentication endpoint</param> /// <param name="authenticationType">Optional authentication type to use when performing calls against the endpoint</param> /// <returns>The unique id assigned to the profile</returns> public static string Persist(string settingsName, Uri endpoint, string authenticationType) { if (!string.Equals(endpoint.Scheme, "https", StringComparison.OrdinalIgnoreCase)) throw new AmazonClientException("Endpoint uri is not Https protocol."); var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredSAMLEndpoints); var os = ProfileManager.ReadProfileSettings(settings, settingsName); if (os == null) os = settings.NewObjectSettings(Guid.NewGuid().ToString()); os[SettingsConstants.EndpointField] = endpoint.ToString(); os[SettingsConstants.DisplayNameField] = settingsName; if (!string.IsNullOrEmpty(authenticationType) && !authenticationType.Equals(DefaultAuthenticationType, StringComparison.OrdinalIgnoreCase)) os[SettingsConstants.AuthenticationTypeField] = authenticationType; PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredSAMLEndpoints, settings); return os.UniqueKey; } /// <summary> /// Constructs an endpoint settings instance. /// </summary> /// <param name="settingsName">The user-defined name to assign to the settings.</param> /// <param name="endpoint"> /// The absolute uri, including any query and relyingParty data, of the endpoint. /// </param> /// <param name="authenticationType"> /// The authentication type to use when performing requests against the endpoint. /// </param> private SAMLEndpointSettings(string settingsName, Uri endpoint, string authenticationType) { Name = settingsName; Endpoint = endpoint; if (!string.IsNullOrEmpty(authenticationType)) _authenticationType = authenticationType; } private static SettingsCollection.ObjectSettings LoadSettings(string endpointName) { var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredSAMLEndpoints); var os = ProfileManager.ReadProfileSettings(settings, endpointName); if (os == null) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "SAML endpoint settings with name '{0}' could not be found.", endpointName)); return os; } } /// <summary> /// <para> /// The persisted data for a saml role profile for a user. This profile /// references an endpoint profile containing the actual endpoint to be used, and /// adds details of the role to be assumed when the profile is selected. /// </para> /// <para> /// Optionally the profile can store a username and domain to be used during /// authentication (default behavior, if this is not specified, is to use the user's /// default network credentials). /// </para> /// </summary> [Obsolete("This class is obsolete and will be removed in a future release. Please use Amazon.Runtime.CredentialProfile. Visit http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html for further details.")] public class SAMLRoleProfile : ProfileSettingsBase { private object _synclock = new object(); /// <summary> /// The ARN of the role that is to be assumed. /// </summary> public string RoleArn { get; internal set; } /// <summary> /// If non-default network credentials are to used contains /// the user identity (in domain\user format, domain optional) that /// should be used to supply credentials when the profile is used in /// authentication. The user must be prompted to supply the /// corresponding password prior to authentication. /// </summary> public string UserIdentity { get; internal set; } /// <summary> /// If a specific user identity was specified in the profile, /// returns true to indicate a password needs to be obtained from /// the user before obtaining network credentials to be used on /// authentication. The default is to use the credentials /// associated with the currently logged-in user or process to /// perform authentication, which does not require the user to be /// prompted. /// </summary> public bool UseDefaultUserIdentity { get { return string.IsNullOrEmpty(UserIdentity); } } /// <summary> /// <para> /// For regions with a region-specific endpoint for STS (eg cn-north-1) this /// field can be set to ensure calls to obtain temporary credentials /// after successful authentication are forwarded to the correct regional /// endpoint. /// </para> /// <para> /// This field does not need to be set when running in a region for /// which the sts.amazonaws.com endpoint is valid. /// </para> /// </summary> public string Region { get; private set; } private SAMLImmutableCredentials _session = null; /// <summary> /// Retrieves the active credential session, if any, associated with the /// role profile. /// </summary> /// <returns> /// The current credentials valid for the role specified in the profile. Returns /// null if no active session is available, or the active session has expired. /// </returns> /// <remarks> /// When a user successfully authenticates and receives temporary AWS /// credentials for a role, the profile is updated with details of the /// session. When the profile is loaded by other processes or tools, if /// session data is present and still valid it can be retrieved using this /// method avoiding the need to re-authenticate and get additional temporary /// credentials. /// </remarks> public SAMLImmutableCredentials GetCurrentSession() { SAMLImmutableCredentials session = null; lock (_synclock) { if (_session != null && _session.Expires <= AWSSDKUtils.CorrectedUtcNow) { UpdateProfileSessionData(null); _session = null; } session = _session; } return session; } /// <summary> /// Persists the current credentials to a 'session' key in the RoleSessions.json file. /// This enables external applications and tools using the same profile to obtain credentials /// without needing to separately re-authenticate the user prior to expiry of the current /// credentials. After persisting the session data it can be retrieved using GetCurrentSession(). /// </summary> /// <remarks> /// Although the credentials are temporary we still encrypt the stored data when at rest in /// the sdk credential store. /// </remarks> /// <param name="credentials"> /// The current credentials valid for the role specified in the profile. /// </param> public void PersistSession(SAMLImmutableCredentials credentials) { lock (_synclock) { UpdateProfileSessionData(credentials); _session = credentials; } } /// <summary> /// Stores or clears the persisted session data. /// </summary> /// <param name="credentials"></param> private void UpdateProfileSessionData(SAMLImmutableCredentials credentials) { string sessionData = null; if (credentials != null) sessionData = credentials.ToJson(); Persist(sessionData); } /// <summary> /// The endpoint settings from which the actual endpoint to use in authentication /// is obtained. /// </summary> public SAMLEndpointSettings EndpointSettings { get; internal set; } /// <summary> /// Tests if a SAMLRoleProfile instance could be instantiated from /// the persisted settings data. /// </summary> /// <param name="profileName">The name given to the persisted settings.</param> /// <returns>True if the settings are compatible with a SAMLRoleProfile type.</returns> public static bool CanCreateFrom(string profileName) { var os = LoadCredentialsProfile(profileName); return CanCreateFrom(os); } /// <summary> /// Tests if a SAMLRoleProfile instance could be instantiated from /// the persisted settings data. /// </summary> /// <param name="os">The persisted settings.</param> /// <returns>True if the settings are compatible with a SAMLRoleProfile type.</returns> public static bool CanCreateFrom(SettingsCollection.ObjectSettings os) { var osProfileType = os.GetValueOrDefault(SettingsConstants.ProfileTypeField, null); return osProfileType != null && osProfileType.Equals(ProfileManager.SAMLRoleProfileType, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Instantiates an instance from settings stored with the specified name. /// </summary> /// <param name="profileName">The name of the endpoint profile.</param> /// <returns>Profile instance or an exception if the profile data does not exist/contains invalid data.</returns> public static SAMLRoleProfile LoadFrom(string profileName) { var os = LoadCredentialsProfile(profileName); return LoadFrom(os); } /// <summary> /// Instantiates an instance from the supplied settings. In addition to the profile settings /// the SDK will inspect for a RoleSessions.json file containing active session data and if /// an entry for the profile is present, will add the session data to the returned profile /// object. /// </summary> /// <param name="os">The persisted settings.</param> /// <returns>Profile instance or an exception if the profile data is invalid.</returns> public static SAMLRoleProfile LoadFrom(SettingsCollection.ObjectSettings os) { if (os == null) throw new ArgumentNullException("os"); if (!CanCreateFrom(os)) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Profile '{0}' does not contain SAML role materials", os[SettingsConstants.DisplayNameField])); Validate(os); var endpointName = os[SettingsConstants.EndpointNameField]; var endpointSettings = ProfileManager.GetSAMLEndpoint(endpointName); var profileName = os[SettingsConstants.DisplayNameField]; var roleArn = os[SettingsConstants.RoleArnField]; var userIdentity = os.GetValueOrDefault(SettingsConstants.UserIdentityField, null); var region = os.GetValueOrDefault(SettingsConstants.Region, null); SAMLImmutableCredentials activeCredentials = LoadActiveSessionCredentials(profileName); return new SAMLRoleProfile(profileName, endpointSettings, roleArn, userIdentity, activeCredentials, region); } /// <summary> /// Validates the contents of the specified profile. /// </summary> /// <param name="profileName">The name of the SAML role profile to validate.</param> /// <exception cref="InvalidDataException">Thrown if the profile settings fail to validate.</exception> public static void Validate(string profileName) { var os = LoadCredentialsProfile(profileName); Validate(os); } /// <summary> /// Validates that the presented settings would result in a valid role profile /// instance. /// </summary> /// <param name="os">The persisted settings.</param> /// <exception cref="InvalidDataException">Thrown if the profile settings fail to validate.</exception> private static void Validate(SettingsCollection.ObjectSettings os) { var endpointName = os.GetValueOrDefault(SettingsConstants.EndpointNameField, null); if (endpointName == null) throw new InvalidDataException("Missing EndpointName data."); SAMLEndpointSettings endpointSettings; if (!ProfileManager.TryGetSAMLEndpoint(endpointName, out endpointSettings)) throw new InvalidDataException(string.Format(CultureInfo.InvariantCulture, "Endpoint settings with the name '{0}' could not be found.", endpointName)); if (string.IsNullOrEmpty(os[SettingsConstants.RoleArnField])) throw new InvalidDataException("Missing role ARN data."); } /// <summary> /// Stores the data in the role profile to the backing store file. /// </summary> public override string Persist() { return Persist(Name, EndpointSettings.Name, RoleArn, UserIdentity, null, Region); } private string Persist(string session) { return Persist(Name, EndpointSettings.Name, RoleArn, UserIdentity, session, Region); } /// <summary> /// <para> /// Registers a role-based profile to be used with SAML authentication. The profile contains /// details of the role to be assumed when AWS credentials are requested based on the role and /// a reference to a SAML endpoint profile containing details of the endpoint to be called to /// authenticate the user. /// </para> /// <para> /// If user identity information is not supplied then the identity of the logged-in user will /// be used when authenticaton is performed against the endpoint referenced in the SAML endpoint /// profile. If identity is provided, no password information is stored in the role profile and /// the user must supply the password for the identity prior to authentication with the endpoint. /// </para> /// </summary> /// <param name="profileName">Name to be assigned to the profile</param> /// <param name="endpointSettingsName"> /// The name of the settings in the SAML endpoints file containing details of the /// endpoint to authenticate with. /// </param> /// <param name="roleArn"> /// The arn of the role that the user wants to assume when using this profile. This /// must be one of the set returned by the saml endpoint when the user authenticates. /// </param> /// <param name="userIdentity"> /// Optional, can be used to prompt the user for a password for the account when authentication /// is performed from a system that is not domain-joined. /// </param> /// <param name="session"> /// Optional, details of the currently active credentials for the role that we want to /// persist into the profile for other tools or processes to pick up, avoiding the need /// to continually re-authenticate the user as they switch between tools. The active session, /// if any, is stored separately from the profile using the file RoleSessions.json. /// </param> /// <param name="region"> /// Set for profiles intended to be used in regions where a region-specific STS endpoint /// must be used (eg cn-north-1). If left empty/null, the global sts.amazonaws.com endpoint /// will be used when credentials are obtained for this profile. /// </param> /// <returns>The unique id assigned to the profile.</returns> public static string Persist(string profileName, string endpointSettingsName, string roleArn, string userIdentity, string session, string region) { if (string.IsNullOrEmpty(profileName) || string.IsNullOrEmpty(endpointSettingsName) || string.IsNullOrEmpty(roleArn)) throw new ArgumentException("Profile name, endpoint settings name and role ARN must be supplied."); SAMLEndpointSettings endpointSettings; if (!ProfileManager.TryGetSAMLEndpoint(endpointSettingsName, out endpointSettings)) { var msg = string.Format(CultureInfo.CurrentCulture, "Failed to load SAML endpoint settings with name {0}", endpointSettingsName); throw new ArgumentException(msg); } var settings = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredProfiles); var os = ProfileManager.ReadProfileSettings(settings, profileName); if (os == null) os = settings.NewObjectSettings(Guid.NewGuid().ToString()); os[SettingsConstants.ProfileTypeField] = ProfileManager.SAMLRoleProfileType; os[SettingsConstants.DisplayNameField] = profileName; os[SettingsConstants.EndpointNameField] = endpointSettings.Name; os[SettingsConstants.RoleArnField] = roleArn; os[SettingsConstants.UserIdentityField] = userIdentity; if (!string.IsNullOrEmpty(region)) os[SettingsConstants.Region] = region; PersistActiveSessionCredentials(profileName, session); PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredProfiles, settings); return os.UniqueKey; } /// <summary> /// Tests for and loads any active session credentials for the specified profile. The session data /// exists in a separate file from the profile, RoleSessions.json. /// </summary> /// <param name="profileName"></param> /// <returns></returns> private static SAMLImmutableCredentials LoadActiveSessionCredentials(string profileName) { SAMLImmutableCredentials sessionCredentials = null; var roleSessions = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredRoleSessions); if (roleSessions != null) { var settings = ProfileManager.ReadSettings(roleSessions, profileName); if (settings != null) { var roleSession = settings[SettingsConstants.RoleSession]; sessionCredentials = SAMLImmutableCredentials.FromJson(roleSession); } } return sessionCredentials; } /// <summary> /// Stores the supplied session data into the RoleSessions.json backing file. /// </summary> /// <param name="profileName"></param> /// <param name="session"></param> private static void PersistActiveSessionCredentials(string profileName, string session) { var roleSessions = PersistenceManager.Instance.GetSettings(SettingsConstants.RegisteredRoleSessions); if (string.IsNullOrEmpty(session) && roleSessions == null) return; var settings = ProfileManager.ReadSettings(roleSessions, profileName); if (settings == null) settings = roleSessions.NewObjectSettings(profileName); settings[SettingsConstants.RoleSession] = session; PersistenceManager.Instance.SaveSettings(SettingsConstants.RegisteredRoleSessions, roleSessions); } /// <summary> /// Constructs a profile data instance that will use the specified network identity /// during authentication with configured endpoint. /// </summary> /// <param name="profileName">The user-defined name of the profile that sourced this data.</param> /// <param name="endpointSettings">The settings for the authentication endpoint.</param> /// <param name="roleArn">The role that should be assumed on successful authentication.</param> /// <param name="userIdentity">The credentials to supply in authentication, in domain\user format.</param> /// <param name="currentSession"> /// Deserialized credential data from the profile, if still valid. Null if the profile does not /// contain any active credentials, or the credentials it did hold are now invalid. /// </param> /// <param name="region"> /// Set for profiles intended to be used in regions where a region-specific STS endpoint /// must be used (eg cn-north-1). If left empty/null, the global sts.amazonaws.com endpoint /// will be used when credentials are obtained for this profile. /// </param> private SAMLRoleProfile(string profileName, SAMLEndpointSettings endpointSettings, string roleArn, string userIdentity, SAMLImmutableCredentials currentSession, string region) { Name = profileName; EndpointSettings = endpointSettings; RoleArn = roleArn; UserIdentity = userIdentity; _session = currentSession; Region = region; } } }
1,216
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Globalization; namespace Amazon.Util { /// <summary> /// Object to track circular references in nested types. /// At each level of nesting, make a call to Track to retrieve Tracker, /// a tracking object implementing the IDisposable interface. /// Dispose of this tracker when leaving the context of the tracked object. /// </summary> public class CircularReferenceTracking { private object referenceTrackersLock = new object(); private Stack<Tracker> referenceTrackers = new Stack<Tracker>(); /// <summary> /// Tracker. Must be disposed. /// </summary> private class Tracker : IDisposable { public object Target { get; private set; } private CircularReferenceTracking State { get; set; } private bool disposed; public Tracker(CircularReferenceTracking state, object target) { State = state; Target = target; } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "Tracking {0}", Target); } #region Dispose Pattern Implementation /// <summary> /// Implements the Dispose pattern /// </summary> /// <param name="disposing">Whether this object is being disposed via a call to Dispose /// or garbage collected.</param> protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { State.PopTracker(this); } this.disposed = true; } } /// <summary> /// Disposes of all managed and unmanaged resources. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } ~Tracker() { this.Dispose(false); } #endregion } /// <summary> /// Adds the current target to a reference list and returns a tracker. /// The tracker removes the target from the reference list when the /// tracker is disposed. /// </summary> /// <param name="target"></param> /// <returns></returns> public IDisposable Track(object target) { if (target == null) throw new ArgumentNullException("target"); lock (referenceTrackersLock) { if (TrackerExists(target)) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Circular reference detected with object [{0}] of type {1}", target, target.GetType().FullName)); var tracker = new Tracker(this, target); referenceTrackers.Push(tracker); return tracker; } } private void PopTracker(Tracker tracker) { lock (referenceTrackersLock) { if (referenceTrackers.Peek() != tracker) throw new InvalidOperationException("Tracker being released is not the latest one. Make sure to release child trackers before releasing parent."); referenceTrackers.Pop(); } } private bool TrackerExists(object target) { foreach (var tracker in referenceTrackers) if (object.ReferenceEquals(tracker.Target, target)) return true; return false; } } }
137
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System.IO; namespace Amazon.Util.Internal { /// <summary> /// Wrapper class over <see cref="Directory"/> operations. /// This change was done for testability. /// </summary> public interface IDirectory { /// <inheritdoc cref="Directory.CreateDirectory"/> DirectoryInfo CreateDirectory(string path); } /// <inheritdoc cref="IDirectory"/> public class DirectoryRetriever : IDirectory { public DirectoryInfo CreateDirectory(string path) => Directory.CreateDirectory(path); } }
35
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Amazon.Util.Internal { /// <summary> /// Wrapper class which invokes the static method /// public static string GetEnvironmentVariable(string variable) /// underneath. This class is added as a property on the singleton class /// EnvironmentVariableSource. This change was done for testability. /// </summary> public sealed class EnvironmentVariableRetriever : IEnvironmentVariableRetriever { public string GetEnvironmentVariable(string key) { return Environment.GetEnvironmentVariable(key); } } }
37
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Collections.Generic; using System.Text; namespace Amazon.Util.Internal { /// <summary> /// Singleton class that holds the property of type IEnvironmentVariableRetreiver. /// This property can hold an instance of type EnvironmentVariableRetreiver which has a wrapper /// method for /// public static string GetEnvironmentVariable(string variable) /// or can be mocked for testing purposes. /// </summary> public sealed class EnvironmentVariableSource { private static readonly EnvironmentVariableSource instance = new EnvironmentVariableSource(); private EnvironmentVariableSource() { } static EnvironmentVariableSource() { } public IEnvironmentVariableRetriever EnvironmentVariableRetriever { get; set; } = new EnvironmentVariableRetriever(); public static EnvironmentVariableSource Instance { get { return instance; } } } }
51
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.IO; #if AWS_ASYNC_API using System.Threading; using System.Threading.Tasks; #endif namespace Amazon.Util.Internal { /// <summary> /// Wrapper class over <see cref="File"/> operations. /// This change was done for testability. /// </summary> public interface IFile { /// <inheritdoc cref="File.Exists"/> bool Exists(string path); /// <inheritdoc cref="File.ReadAllText(string)"/> string ReadAllText(string path); /// <inheritdoc cref="File.WriteAllText(string, string)"/> void WriteAllText(string path, string contents); #if AWS_ASYNC_API /// <inheritdoc cref="File.ReadAllText(string)"/> Task<string> ReadAllTextAsync(string path, CancellationToken token = default); /// <inheritdoc cref="File.WriteAllText(string, string)"/> Task WriteAllTextAsync(string path, string contents, CancellationToken token = default); #endif } /// <inheritdoc cref="IFile"/> public class FileRetriever : IFile { public bool Exists(string path) => File.Exists(path); public string ReadAllText(string path) => File.ReadAllText(path); public void WriteAllText(string path, string contents) => File.WriteAllText(path, contents); #if AWS_ASYNC_API public async Task<string> ReadAllTextAsync(string path, CancellationToken token = default) { using (var fs = File.OpenRead(path)) using (var reader = new StreamReader(fs)) return await reader.ReadToEndAsync().ConfigureAwait(false); } public async Task WriteAllTextAsync(string path, string contents, CancellationToken token = default) { //we use FileMode.Create because we want to truncate the file first if the file exists then write to it. using (var fs = new FileStream(path, FileMode.Create)) using (var writer = new StreamWriter(fs)) await writer.WriteAsync(contents).ConfigureAwait(false); } #endif } }
76
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System.Collections; namespace Amazon.Util.Internal { /// <summary> /// Interface for EnvironmentVariableRetriever. /// This serves as a property for the singleton EnvironmentVariableSource /// </summary> public interface IEnvironmentVariableRetriever { string GetEnvironmentVariable(string key); } }
28
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using Amazon.Runtime.Internal.Util; using Amazon.Util.Internal.PlatformServices; namespace Amazon.Util.Internal { public static partial class InternalSDKUtils { #region UserAgent static string _versionNumber; static string _customSdkUserAgent; static string _customData; public static void SetUserAgent(string productName, string versionNumber) { SetUserAgent(productName, versionNumber, null); } public static void SetUserAgent(string productName, string versionNumber, string customData) { _userAgentBaseName = productName; _versionNumber = versionNumber; _customData = customData; BuildCustomUserAgentString(); } static void BuildCustomUserAgentString() { if (_versionNumber == null) { _versionNumber = CoreVersionNumber; } var environmentInfo = ServiceFactory.Instance.GetService<IEnvironmentInfo>(); string executionEnvironmentString = ""; executionEnvironmentString = GetExecutionEnvironmentUserAgentString(); if (string.IsNullOrEmpty(executionEnvironmentString)) { _customSdkUserAgent = string.Format(CultureInfo.InvariantCulture, "{0}/{1} {2} OS/{3} {4}", _userAgentBaseName, _versionNumber, environmentInfo.FrameworkUserAgent, environmentInfo.PlatformUserAgent, _customData).Trim(); } else { _customSdkUserAgent = string.Format(CultureInfo.InvariantCulture, "{0}/{1} {2} OS/{3} {4} {5}", _userAgentBaseName, _versionNumber, environmentInfo.FrameworkUserAgent, environmentInfo.PlatformUserAgent, executionEnvironmentString, _customData).Trim(); } } public static string BuildUserAgentString(string serviceSdkVersion) { if (!string.IsNullOrEmpty(_customSdkUserAgent)) { return _customSdkUserAgent; } var environmentInfo = ServiceFactory.Instance.GetService<IEnvironmentInfo>(); #if BCL return string.Format(CultureInfo.InvariantCulture, "{0}/{1} aws-sdk-dotnet-core/{2} {3} OS/{4} {5} {6}", _userAgentBaseName, serviceSdkVersion, CoreVersionNumber, environmentInfo.FrameworkUserAgent, environmentInfo.PlatformUserAgent, GetExecutionEnvironmentUserAgentString(), _customData).Trim(); #elif NETSTANDARD return string.Format(CultureInfo.InvariantCulture, "{0}/{1} aws-sdk-dotnet-core/{2} {3} OS/{4} {5} {6}", _userAgentBaseName, serviceSdkVersion, CoreVersionNumber, environmentInfo.FrameworkUserAgent, environmentInfo.PlatformUserAgent, GetExecutionEnvironmentUserAgentString(), _customData).Trim(); #endif } #endregion public static void ApplyValues(object target, IDictionary<string, object> propertyValues) { if (propertyValues == null || propertyValues.Count == 0) return; var targetTypeInfo = TypeFactory.GetTypeInfo(target.GetType()); foreach(var kvp in propertyValues) { var property = targetTypeInfo.GetProperty(kvp.Key); if (property == null) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unable to find property {0} on type {1}.", kvp.Key, targetTypeInfo.FullName)); try { var propertyTypeInfo = TypeFactory.GetTypeInfo(property.PropertyType); if (propertyTypeInfo.IsEnum) { var enumValue = Enum.Parse(property.PropertyType, kvp.Value.ToString(), true); property.SetValue(target, enumValue, null); } else { property.SetValue(target, kvp.Value, null); } } catch(Exception e) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unable to set property {0} on type {1}: {2}", kvp.Key, targetTypeInfo.FullName, e.Message)); } } } public static void AddToDictionary<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TKey key, TValue value) { if (dictionary.ContainsKey(key)) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Dictionary already contains item with key {0}", key)); dictionary[key] = value; } public static void FillDictionary<T, TKey, TValue>(IEnumerable<T> items, Func<T, TKey> keyGenerator, Func<T, TValue> valueGenerator, Dictionary<TKey, TValue> targetDictionary) { foreach (var item in items) { var key = keyGenerator(item); var value = valueGenerator(item); AddToDictionary(targetDictionary, key, value); } } public static Dictionary<TKey, TValue> ToDictionary<T, TKey, TValue>(IEnumerable<T> items, Func<T, TKey> keyGenerator, Func<T, TValue> valueGenerator) { return ToDictionary<T, TKey, TValue>(items, keyGenerator, valueGenerator, comparer: null); } public static Dictionary<TKey, TValue> ToDictionary<T, TKey, TValue>(IEnumerable<T> items, Func<T, TKey> keyGenerator, Func<T, TValue> valueGenerator, IEqualityComparer<TKey> comparer) { Dictionary<TKey, TValue> dictionary; if (comparer == null) dictionary = new Dictionary<TKey, TValue>(); else dictionary = new Dictionary<TKey, TValue>(comparer); FillDictionary(items, keyGenerator, valueGenerator, dictionary); return dictionary; } public static bool TryFindByValue<TKey, TValue>( IDictionary<TKey, TValue> dictionary, TValue value, IEqualityComparer<TValue> valueComparer, out TKey key) { foreach (var kvp in dictionary) { var candidateValue = kvp.Value; if (valueComparer.Equals(value, candidateValue)) { key = kvp.Key; return true; } } key = default(TKey); return false; } internal static string EXECUTION_ENVIRONMENT_ENVVAR = "AWS_EXECUTION_ENV"; internal static string GetExecutionEnvironment() { return Environment.GetEnvironmentVariable(EXECUTION_ENVIRONMENT_ENVVAR); } private static string GetExecutionEnvironmentUserAgentString() { string userAgentString = ""; string executionEnvValue = GetExecutionEnvironment(); if (!string.IsNullOrEmpty(executionEnvValue)) { userAgentString = string.Format(CultureInfo.InvariantCulture, "exec-env/{0}", executionEnvValue); } return userAgentString; } /// <summary> /// Tests if the filePath is rooted with the directoryPath when resolved. The filePath and /// directoryPath do not need to exist to call this method. /// </summary> /// <param name="filePath">The filePath to test against the directoryPath.</param> /// <param name="directoryPath">The directoryPath to use as root in the test.</param> /// <returns>true if directoryPath is root of filePath else false</returns> public static bool IsFilePathRootedWithDirectoryPath(string filePath, string directoryPath) { //Construct a local directory path that always ends with the directory separator char. This //ensures our directory starts with test doesn't allow files that start with the directory //to be popped off the path to fake out the test: //LocalDirectory = a\b\c //FilePath = a\b\c\..\ctest.txt var dirTestPath = directoryPath; if (!dirTestPath.EndsWith(Path.DirectorySeparatorChar.ToString())) { dirTestPath += Path.DirectorySeparatorChar; } var dirInfo = new DirectoryInfo(dirTestPath); var fileInfo = new FileInfo(filePath); //Test if the target file is a child of directoryPath return fileInfo.FullName.StartsWith(dirInfo.FullName); } #region IsSet methods /* Set Collection True -> set to empty AlwaysSend* False -> set to empty collection type Value type True -> set to default(T) False -> set to null Get Collection Field is AlwaysSend* OR has items -> True Otherwise -> False Value type Field is any value -> True Null -> False */ public static void SetIsSet<T>(bool isSet, ref Nullable<T> field) where T : struct { if (isSet) field = default(T); else field = null; } public static void SetIsSet<T>(bool isSet, ref List<T> field) { if (isSet) field = new AlwaysSendList<T>(field); else field = new List<T>(); } public static void SetIsSet<TKey, TValue>(bool isSet, ref Dictionary<TKey, TValue> field) { if (isSet) field = new AlwaysSendDictionary<TKey, TValue>(field); else field = new Dictionary<TKey, TValue>(); } public static bool GetIsSet<T>(Nullable<T> field) where T : struct { return (field.HasValue); } public static bool GetIsSet<T>(List<T> field) { if (field == null) return false; if (field.Count > 0) return true; var sl = field as AlwaysSendList<T>; if (sl != null) return true; return false; } public static bool GetIsSet<TKey, TVvalue>(Dictionary<TKey, TVvalue> field) { if (field == null) return false; if (field.Count > 0) return true; var sd = field as AlwaysSendDictionary<TKey, TVvalue>; if (sd != null) return true; return false; } #endregion } }
325
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This is a generated file. */ using System; using System.Collections.Generic; using System.Linq; using System.Globalization; using System.Text; using Amazon.Runtime.Internal.Util; namespace Amazon.Util.Internal { public static partial class InternalSDKUtils { internal const string CoreVersionNumber = "3.7.107.9"; } }
34
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Runtime; using Amazon.Runtime.Internal.Settings; using Amazon.Runtime.Internal.Util; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Amazon.Util.Internal { /// <summary> /// Manager to access a settings store file. Objects are primarily accessed by DisplayName rather than unique key. /// Settings store files are located under the current user's AppData\Local\AWSToolkit folder. /// Select keys in these files are encrypted on a per user, per machine basis using the Windows Data Protection API; /// the encrypted values cannot be used by any other user or on any other machine. /// /// This class is not threadsafe. /// </summary> public class NamedSettingsManager { /// <summary> /// True if the encrypted store is availble, false otherwise. /// </summary> public static bool IsAvailable { get { return UserCrypto.IsUserCryptAvailable; } } private SettingsManager settingsManager; /// <summary> /// Construct an NamedSettingsManager. /// </summary> /// <param name="settingsType">The base filename to read/write.</param> public NamedSettingsManager(string settingsType) { settingsManager = new SettingsManager(settingsType); } /// <summary> /// Register an object. Let the uniqueKey be assigned automatically. /// </summary> /// <param name="displayName">The display name for the object.</param> /// <param name="properties">The property names and values for the object.</param> /// <returns>The unique key that was assigned to the object.</returns> public string RegisterObject(string displayName, Dictionary<string, string> properties) { if (string.IsNullOrEmpty(displayName)) throw new ArgumentException("displayName cannot be null or empty."); var propertiesPlusName = new Dictionary<string, string>(properties); propertiesPlusName[SettingsConstants.DisplayNameField] = displayName; string uniqueKey; if (settingsManager.TryGetObjectByProperty(SettingsConstants.DisplayNameField, displayName, out uniqueKey, out properties)) return settingsManager.RegisterObject(uniqueKey, propertiesPlusName); else return settingsManager.RegisterObject(propertiesPlusName); } /// <summary> /// Try to get an object form the store. /// </summary> /// <param name="displayName">The display name for the object.</param> /// <param name="properties">The property names and values for the object.</param> /// <returns>True if the object was found, false otherwise.</returns> public bool TryGetObject(string displayName, out Dictionary<string, string> properties) { string uniqueKey; return TryGetObject(displayName, out uniqueKey, out properties); } /// <summary> /// Try to get an object form the store. /// </summary> /// <param name="displayName">The display name for the object.</param> /// <param name="uniqueKey">The uniqueKey of the object in the store</param> /// <param name="properties">The property names and values for the object.</param> /// <returns>True if the object was found, false otherwise.</returns> public bool TryGetObject(string displayName, out string uniqueKey, out Dictionary<string, string> properties) { return settingsManager.TryGetObjectByProperty(SettingsConstants.DisplayNameField, displayName, out uniqueKey, out properties); } /// <summary> /// Unregister an object from the store. /// </summary> /// <param name="displayName">The display name for the object.</param> public void UnregisterObject(string displayName) { string uniqueKey; Dictionary<string, string> properties; if (settingsManager.TryGetObjectByProperty(SettingsConstants.DisplayNameField, displayName, out uniqueKey, out properties)) { settingsManager.UnregisterObject(uniqueKey); } } /// <summary> /// Rename an object in the store. /// </summary> /// <param name="oldDisplayName"></param> /// <param name="newDisplayName"></param> /// <param name="force">if true and destination object already exists overwrite it</param> public void RenameObject(string oldDisplayName, string newDisplayName, bool force) { Dictionary<string, string> fromObject; string fromUniqueKey; Dictionary<string, string> toObject; string toUniqueKey; if (TryGetObject(oldDisplayName, out fromUniqueKey, out fromObject)) { if (TryGetObject(newDisplayName, out toUniqueKey, out toObject)) { // if oldDisplayName == newDisplayName it's a no op if (!string.Equals(oldDisplayName, newDisplayName, StringComparison.Ordinal)) { if (force) { settingsManager.UnregisterObject(toUniqueKey); // recursive call with force == false now that the destination object is gone RenameObject(oldDisplayName, newDisplayName, false); } else throw new ArgumentException("Cannot rename object. The destination object '" + newDisplayName + "' already exists."); } } else { fromObject[SettingsConstants.DisplayNameField] = newDisplayName; settingsManager.RegisterObject(fromUniqueKey, fromObject); } } else throw new ArgumentException("Cannot rename object. The source object '" + oldDisplayName + "' does not exist."); } /// <summary> /// Copy an object in the store. /// The new object will be a copy of the original, except it will be assigned a new unique key. /// </summary> /// <param name="fromDisplayName"></param> /// <param name="toDisplayName"></param> /// <param name="force">if true and destination object already exists overwrite it</param> public void CopyObject(string fromDisplayName, string toDisplayName, bool force) { Dictionary<string, string> fromObject; Dictionary<string, string> toObject; string toUniqueKey; if (TryGetObject(fromDisplayName, out fromObject)) { if (TryGetObject(toDisplayName, out toUniqueKey, out toObject)) { // if fromDisplayName == toDisplayName it's a no op if (!string.Equals(fromDisplayName, toDisplayName, StringComparison.Ordinal)) { if (force) { settingsManager.UnregisterObject(toUniqueKey); // recursive call with force == false now that the destination object is gone CopyObject(fromDisplayName, toDisplayName, force); } else throw new ArgumentException("Cannot copy object. The destination object '" + toDisplayName + "' already exists."); } } else { // Register the copy. A new unique key will be automatically assigned. RegisterObject(toDisplayName, fromObject); } } else throw new ArgumentException("Cannot copy object. The source object '" + fromDisplayName + "' does not exist."); } /// <summary> /// Get a list of the display names for the objects in the store. /// </summary> /// <returns>A list of display names.</returns> public List<string> ListObjectNames() { return settingsManager.SelectProperty(SettingsConstants.DisplayNameField); } } }
204
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using Amazon.Internal; using Amazon.Runtime.Internal.Util; namespace Amazon.Util.Internal { /// <summary> /// Finds region string in the endpoint string using predefined rules /// If predefined rules fail to match the region, regular expression strings provided in /// endpoints.json are used to find the region. /// If regular expressions also fail, then a default region is returned. /// </summary> public class RegionFinder : IDisposable { internal class EndpointSegment { public string Value { get; set; } public IRegionEndpoint RegionEndpoint { get; set; } public bool UseThisValue { get; set; } public List<EndpointSegment> Children { get; set; } } #region Constants private const string DefaultRegion = "us-east-1"; private const string DefaultGovRegion = "us-gov-west-1"; #endregion #region Members private readonly EndpointSegment _root; private readonly Logger _logger; private readonly Dictionary<string, IRegionEndpoint> _regionEndpoints; private readonly RegionEndpointProviderV3 _regionEndpointProviderV3; #endregion #region Constructors internal RegionFinder() { _regionEndpointProviderV3 = new RegionEndpointProviderV3(); _regionEndpoints = BuildRegionEndpoints(); _root = BuildRoot(); _logger = Logger.GetLogger(typeof(RegionFinder)); } #endregion #region Public methods /// <summary> /// Finds the region in the provided endpoint parsing from right to left /// Try to find exact match of the region in endpoints.json /// If there doesn't exist an exact match, find a fuzzy match /// Else return default region /// </summary> /// <param name="endpoint">Endpoint string</param> /// <returns>First successfully parsed region from right to left in the given endpoint or default region</returns> public IRegionEndpoint FindRegion(string endpoint) { if (string.IsNullOrEmpty(endpoint)) { return _root.RegionEndpoint; } endpoint = GetAuthority(endpoint.ToLower()); var exactRegion = FindExactRegion(endpoint); if (exactRegion != null && exactRegion.UseThisValue) { return exactRegion.RegionEndpoint; } _logger.InfoFormat($"Unable to find exact matched region in endpoint {endpoint}"); var fuzzyRegion = FindFuzzyRegion(endpoint); if (fuzzyRegion != null) { _logger.InfoFormat($"{fuzzyRegion.RegionName} fuzzy region found in endpoint {endpoint}"); return fuzzyRegion; } _logger.InfoFormat($"Unable to find fuzzy matched region in endpoint {endpoint}"); // Return the default region return _root.RegionEndpoint; } /// <summary> /// Returns the Domain Name System host name /// </summary> /// <param name="url">URL string</param> /// <returns>A String containing the authority component of the URL</returns> public static string GetAuthority(string url) { if (string.IsNullOrEmpty(url)) { return null; } var schemeEndIndex = url.IndexOf("://", StringComparison.Ordinal); if (schemeEndIndex != -1) { url = url.Substring(schemeEndIndex + 3); } var hostEndIndex = url.IndexOf("/", StringComparison.Ordinal); if (hostEndIndex != -1) { url = url.Substring(0, hostEndIndex); } return url; } /// <summary> /// Find region in the endpoint using endpoints.json region regexs /// If there doesn't exist a match, return null /// </summary> /// <param name="endpoint"></param> /// <returns>First matched region from right to left in the given endpoint or null</returns> public IRegionEndpoint FindFuzzyRegion(string endpoint) { foreach (var regionRegex in _regionEndpointProviderV3.AllRegionRegex) { // A typical region regex looks like "^(us|eu|ap|sa|ca|me|af)\\-\\w+\\-\\d+$" // Remove the start (^) and end ($) keyword to allow regex matching without defined start and end pattern var trimmedRegionRegex = regionRegex.Trim('^', '$'); var match = Regex.Match(endpoint, trimmedRegionRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.RightToLeft); if (match.Success) { return new RegionEndpointProviderV2.RegionEndpoint(match.Value, "Unknown"); } } return null; } #endregion #region Internal methods /// <summary> /// Find endpoint segment in the endpoint parsing right to left /// If there exists an exception such as us-gov, return exception value /// Else return null /// </summary> /// <param name="endpoint">Endpoint string</param> /// <returns>First parsed region from right to left in the given endpoint or null</returns> internal EndpointSegment FindExactRegion(string endpoint) { var segments = endpoint.Split('.'); return FindExactRegion(segments, segments.Length - 1, _root); } #endregion #region Private methods private Dictionary<string, IRegionEndpoint> BuildRegionEndpoints() { var allRegionEndpoints = new Dictionary<string, IRegionEndpoint>(); foreach (var regionEndpoint in _regionEndpointProviderV3.AllRegionEndpoints) { allRegionEndpoints[regionEndpoint.RegionName] = regionEndpoint; } return allRegionEndpoints; } /// <summary> /// Builds an exception tree root that is used to handle the exception cases for an endpoint to determine the region. /// New exceptions must be added as a child to the root. /// If there exists a sub-exception that depends on the parent exception, it must be added as a child to the parent node /// For example, us-gov followed by s-accelerate from right to left, then us-gov must have s3-accelerate as a Child /// </summary> /// <returns>Root of exception tree</returns> private EndpointSegment BuildRoot() { return new EndpointSegment() { Children = new List<EndpointSegment>() { new EndpointSegment() { Value = "s3-accelerate", RegionEndpoint = null, UseThisValue = true, }, new EndpointSegment() { Value = "us-gov", RegionEndpoint = _regionEndpoints[DefaultGovRegion], UseThisValue = true } }, RegionEndpoint = _regionEndpoints[DefaultRegion] }; } private EndpointSegment FindExactRegion(IList<string> segments, int segmentIndex, EndpointSegment currentEndpointSegment) { // Return null if there doesn't exist a matching region if (segmentIndex < 0) { return null; } var segment = segments[segmentIndex]; // Move down in the tree, if there exists a child node var nextEndpointSegment = currentEndpointSegment.Children.FirstOrDefault(endpointSegment => endpointSegment.Value.Equals(segment)); if (nextEndpointSegment != null) { currentEndpointSegment = nextEndpointSegment; } // Return the value of node if exception is configured with return value if (currentEndpointSegment.UseThisValue) { return currentEndpointSegment; } // Check for the region var valueToCheck = string.Empty; var dashedSegments = segment.Split('-'); for (var dashedSegmentIndex = dashedSegments.Length - 1; dashedSegmentIndex >= 0; dashedSegmentIndex--) { valueToCheck = string.IsNullOrEmpty(valueToCheck) ? dashedSegments[dashedSegmentIndex] : $"{dashedSegments[dashedSegmentIndex]}-{valueToCheck}"; if (_regionEndpoints.ContainsKey(valueToCheck)) { return new EndpointSegment() { RegionEndpoint = _regionEndpoints[valueToCheck], UseThisValue = true }; } } return FindExactRegion(segments, segmentIndex - 1, currentEndpointSegment); } #endregion private static readonly RegionFinder _instance = new RegionFinder(); private bool disposedValue; /// <summary> /// Gets the singleton. /// </summary> public static RegionFinder Instance { get { return _instance; } } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { if(_regionEndpointProviderV3 != null) { _regionEndpointProviderV3.Dispose(); } } disposedValue = true; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } }
303
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace Amazon.Util.Internal { /// <summary> /// Root AWS config /// </summary> public partial class RootConfig { public CSMConfig CSMConfig { get; set; } public LoggingConfig Logging { get; private set; } public ProxyConfig Proxy { get; private set; } public string EndpointDefinition { get; set; } public string Region { get; set; } public string ProfileName { get; set; } public string ProfilesLocation { get; set; } public RegionEndpoint RegionEndpoint { get { if (string.IsNullOrEmpty(Region)) return null; return RegionEndpoint.GetBySystemName(Region); } set { if (value == null) Region = null; else Region = value.SystemName; } } public bool UseSdkCache { get; set; } public bool CorrectForClockSkew { get; set; } public bool UseAlternateUserAgentHeader { get; set; } public string ApplicationName { get; set; } public bool? CSMEnabled { get; set; } public string CSMClientId { get; set; } public int? CSMPort { get; set; } private const string _rootAwsSectionName = "aws"; public RootConfig() { CSMConfig = new CSMConfig(); Logging = new LoggingConfig(); Proxy = new ProxyConfig(); EndpointDefinition = AWSConfigs._endpointDefinition; Region = AWSConfigs._awsRegion; ProfileName = AWSConfigs._awsProfileName; ProfilesLocation = AWSConfigs._awsAccountsLocation; UseSdkCache = AWSConfigs._useSdkCache; CorrectForClockSkew = true; #if !NETSTANDARD var root = AWSConfigs.GetSection<AWSSection>(_rootAwsSectionName); Logging.Configure(root.Logging); Proxy.Configure(root.Proxy); CSMConfig.Configure(root.CSMConfig); ServiceSections = root.ServiceSections; if (root.UseSdkCache.HasValue) UseSdkCache = root.UseSdkCache.Value; EndpointDefinition = Choose(EndpointDefinition, root.EndpointDefinition); Region = Choose(Region, root.Region); ProfileName = Choose(ProfileName, root.ProfileName); ProfilesLocation = Choose(ProfilesLocation, root.ProfilesLocation); ApplicationName = Choose(ApplicationName, root.ApplicationName); if (root.CorrectForClockSkew.HasValue) CorrectForClockSkew = root.CorrectForClockSkew.Value; #endif } // If a is not null-or-empty, returns a; otherwise, returns b. private static string Choose(string a, string b) { return (string.IsNullOrEmpty(a) ? b : a); } IDictionary<string, XElement> ServiceSections { get; set; } public XElement GetServiceSection(string service) { XElement section; if (ServiceSections.TryGetValue(service, out section)) return section; return null; } } }
102
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Runtime; using Amazon.Runtime.Internal.Settings; using Amazon.Runtime.Internal.Util; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Amazon.Util.Internal { /// <summary> /// Manager to access a settings store file. /// Settings store files are located under the current user's AppData\Local\AWSToolkit folder. /// Select keys in these files are encrypted on a per user, per machine basis using the Windows Data Protection API; /// the encrypted values cannot be used by any other user or on any other machine. /// /// This class is not threadsafe. /// </summary> public class SettingsManager { /// <summary> /// True if the encrypted store is availble, false otherwise. /// </summary> public static bool IsAvailable { get { return UserCrypto.IsUserCryptAvailable; } } /// <summary> /// Construct a SettingsManager. /// </summary> /// <param name="settingsType">The base filename to read/write.</param> public SettingsManager(string settingsType) { EnsureAvailable(); SettingsType = settingsType; } /// <summary> /// The base filename to read/write. /// </summary> public string SettingsType { get; private set; } /// <summary> /// Register an object. Let the uniqueKey be assigned automatically. /// </summary> /// <param name="properties">The property names and values for the object.</param> /// <returns>The unique key that was assigned to the object.</returns> public string RegisterObject(Dictionary<string, string> properties) { return RegisterObject(null, properties); } /// <summary> /// Register an object. /// </summary> /// <param name="uniqueKey">The uniqueKey for the object, or null if one should be assigned automatically.</param> /// <param name="properties">The property names and values for the object.</param> /// <returns>The unique key that was assigned to the object.</returns> public string RegisterObject(string uniqueKey, Dictionary<string, string> properties) { var settings = GetSettings(); SettingsCollection.ObjectSettings objectSettings; if (!TryGetObjectSettings(uniqueKey, settings, out objectSettings)) { string actualUniqueKey; if (string.IsNullOrEmpty(uniqueKey)) actualUniqueKey = Guid.NewGuid().ToString("D"); else actualUniqueKey = uniqueKey; objectSettings = settings.NewObjectSettings(actualUniqueKey); } foreach (var pair in properties) { if (pair.Value == null) objectSettings.Remove(pair.Key); else objectSettings[pair.Key] = pair.Value; } SaveSettings(settings); return objectSettings.UniqueKey; } /// <summary> /// Try to get an object form the store. /// </summary> /// <param name="uniqueKey">The uniqueKey of the object in the store</param> /// <param name="properties">The property names and values for the object.</param> /// <returns>True if the object was found, false otherwise.</returns> public bool TryGetObject(string uniqueKey, out Dictionary<string, string> properties) { var settings = GetSettings(); SettingsCollection.ObjectSettings objectSettings; properties = null; if (TryGetObjectSettings(uniqueKey, settings, out objectSettings)) { uniqueKey = objectSettings.UniqueKey; properties = new Dictionary<string, string>(); foreach (var key in objectSettings.Keys) { properties.Add(key, objectSettings[key]); } } return properties != null; } /// <summary> /// Try to get an object form the store based on the value of a specific property. /// If multiple objects with the same property value exist, return the first one. /// </summary> /// <param name="propertyName">The name of the property to search on.</param> /// <param name="value">The value of the property to search on.</param> /// <param name="uniqueKey">The unique key of the object.</param> /// <param name="properties">The properties of the object.</param> /// <returns></returns> public bool TryGetObjectByProperty(string propertyName, string value, out string uniqueKey, out Dictionary<string, string> properties) { var settings = GetSettings(); SettingsCollection.ObjectSettings objectSettings; properties = null; uniqueKey = null; if (TryGetObjectSettings(propertyName, value, settings, out objectSettings)) { uniqueKey = objectSettings.UniqueKey; properties = new Dictionary<string, string>(); foreach (var key in objectSettings.Keys) { properties.Add(key, objectSettings[key]); } } return properties != null; } /// <summary> /// Get a list of the unique keys of all the objects in the store. /// </summary> /// <returns></returns> public List<string> ListUniqueKeys() { var settings = GetSettings(); return new List<string>(settings.Select(x => x.UniqueKey)); } /// <summary> /// Get the value of a specific property for each object in the store. /// </summary> /// <param name="propertyName"></param> /// <returns></returns> public List<string> SelectProperty(string propertyName) { var settings = GetSettings(); return new List<string>(settings.Select(x => x[propertyName])); } /// <summary> /// Unregister an object from the store. /// </summary> /// <param name="uniqueKey">The unique key for the object.</param> public void UnregisterObject(string uniqueKey) { var settings = GetSettings(); SettingsCollection.ObjectSettings objectSettings = null; if (TryGetObjectSettings(uniqueKey, settings, out objectSettings)) { settings.Remove(objectSettings.UniqueKey); SaveSettings(settings); } } private SettingsCollection GetSettings() { return PersistenceManager.Instance.GetSettings(SettingsType); } private void SaveSettings(SettingsCollection settings) { PersistenceManager.Instance.SaveSettings(SettingsType, settings); } private static bool TryGetObjectSettings(string propertyName, string value, SettingsCollection settings, out SettingsCollection.ObjectSettings objectSettings) { objectSettings = settings.FirstOrDefault(x => string.Equals(x[propertyName], value, StringComparison.OrdinalIgnoreCase)); return objectSettings != null; } private static bool TryGetObjectSettings(string uniqueKey, SettingsCollection settings, out SettingsCollection.ObjectSettings objectSettings) { objectSettings = settings.FirstOrDefault(x => string.Equals(x.UniqueKey, uniqueKey, StringComparison.OrdinalIgnoreCase)); return objectSettings != null; } private static void EnsureAvailable() { if (!IsAvailable) { throw new AmazonClientException("The encrypted store is not available. This may be due to use of a non-Windows operating system or Windows Nano Server, or the current user account may not have its profile loaded."); } } } }
219
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Amazon.Util.Internal { public interface ITypeInfo { Type BaseType { get; } Type Type { get; } Assembly Assembly { get; } bool IsArray { get; } Array ArrayCreateInstance(int length); Type GetInterface(string name); Type[] GetInterfaces(); IEnumerable<PropertyInfo> GetProperties(); IEnumerable<FieldInfo> GetFields(); FieldInfo GetField(string name); MethodInfo GetMethod(string name); MethodInfo GetMethod(string name, ITypeInfo[] paramTypes); MemberInfo[] GetMembers(); ConstructorInfo GetConstructor(ITypeInfo[] paramTypes); PropertyInfo GetProperty(string name); bool IsAssignableFrom(ITypeInfo typeInfo); bool IsEnum {get;} bool IsClass { get; } bool IsValueType { get; } bool IsInterface { get; } bool IsAbstract { get; } bool IsSealed { get; } object EnumToObject(object value); ITypeInfo EnumGetUnderlyingType(); object CreateInstance(); ITypeInfo GetElementType(); bool IsType(Type type); string FullName { get; } string Name { get; } bool IsGenericTypeDefinition { get; } bool IsGenericType { get; } bool ContainsGenericParameters { get; } Type GetGenericTypeDefinition(); Type[] GetGenericArguments(); object[] GetCustomAttributes(bool inherit); object[] GetCustomAttributes(ITypeInfo attributeType, bool inherit); } public static partial class TypeFactory { public static readonly ITypeInfo[] EmptyTypes = new ITypeInfo[] { }; public static ITypeInfo GetTypeInfo(Type type) { if (type == null) return null; return new TypeInfoWrapper(type); } abstract class AbstractTypeInfo : ITypeInfo { protected Type _type; internal AbstractTypeInfo(Type type) { this._type = type; } public Type Type { get{return this._type;} } public override int GetHashCode() { return this._type.GetHashCode(); } public override bool Equals(object obj) { var typeWrapper = obj as AbstractTypeInfo; if (typeWrapper == null) return false; return this._type.Equals(typeWrapper._type); } public bool IsType(Type type) { return this._type == type; } public abstract Type BaseType { get; } public abstract Assembly Assembly { get; } public abstract Type GetInterface(string name); public abstract Type[] GetInterfaces(); public abstract IEnumerable<PropertyInfo> GetProperties(); public abstract IEnumerable<FieldInfo> GetFields(); public abstract FieldInfo GetField(string name); public abstract MethodInfo GetMethod(string name); public abstract MethodInfo GetMethod(string name, ITypeInfo[] paramTypes); public abstract MemberInfo[] GetMembers(); public abstract PropertyInfo GetProperty(string name); public abstract bool IsAssignableFrom(ITypeInfo typeInfo); public abstract bool IsClass { get; } public abstract bool IsInterface { get; } public abstract bool IsAbstract { get; } public abstract bool IsSealed { get; } public abstract bool IsEnum { get; } public abstract bool IsValueType { get; } public abstract ConstructorInfo GetConstructor(ITypeInfo[] paramTypes); public abstract object[] GetCustomAttributes(bool inherit); public abstract object[] GetCustomAttributes(ITypeInfo attributeType, bool inherit); public abstract bool ContainsGenericParameters { get; } public abstract bool IsGenericTypeDefinition { get; } public abstract bool IsGenericType {get;} public abstract Type GetGenericTypeDefinition(); public abstract Type[] GetGenericArguments(); public bool IsArray { get { return this._type.IsArray; } } public object EnumToObject(object value) { return Enum.ToObject(this._type, value); } public ITypeInfo EnumGetUnderlyingType() { return TypeFactory.GetTypeInfo(Enum.GetUnderlyingType(this._type)); } public object CreateInstance() { return Activator.CreateInstance(this._type); } public Array ArrayCreateInstance(int length) { return Array.CreateInstance(this._type, length); } public ITypeInfo GetElementType() { return TypeFactory.GetTypeInfo(this._type.GetElementType()); } public string FullName { get { return this._type.FullName; } } public string Name { get { return this._type.Name; } } } } }
217
aws-sdk-net
aws
C#
 namespace Amazon.Util.Internal.PlatformServices { public interface IApplicationInfo { string AppTitle { get; } string AppVersionName { get; } string AppVersionCode { get; } string PackageName { get; } } }
12
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Amazon.Util.Internal.PlatformServices { public enum ApplicationSettingsMode { None, Local, Roaming } public interface IApplicationSettings { void SetValue(string key, string value, ApplicationSettingsMode mode); string GetValue(string key, ApplicationSettingsMode mode); void RemoveValue(string key, ApplicationSettingsMode mode); } }
24
aws-sdk-net
aws
C#
 namespace Amazon.Util.Internal.PlatformServices { public interface IEnvironmentInfo { string Platform { get; } string PlatformUserAgent { get; } string FrameworkUserAgent { get; } } }
11
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Amazon.Util.Internal.PlatformServices { public enum NetworkStatus { NotReachable, ReachableViaCarrierDataNetwork, ReachableViaWiFiNetwork } public class NetworkStatusEventArgs : EventArgs { public NetworkStatus Status { get; private set; } public NetworkStatusEventArgs(NetworkStatus status) { this.Status = status; } } public interface INetworkReachability { NetworkStatus NetworkStatus { get; } event EventHandler<NetworkStatusEventArgs> NetworkReachabilityChanged; } }
32
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Amazon.Util.Internal.PlatformServices { public class ServiceFactory { internal const string NotImplementedErrorMessage = "This functionality is not implemented in the portable version of this assembly. "+ "You should reference the AWSSDK.Core NuGet package from your main application project in order to reference the platform-specific implementation."; enum InstantiationModel { Singleton, InstancePerCall } private static readonly object _lock = new object(); private static bool _factoryInitialized = false; private static IDictionary<Type, Type> _mappings = new Dictionary<Type, Type>() { {typeof(IApplicationSettings),typeof(ApplicationSettings)}, {typeof(INetworkReachability),typeof(NetworkReachability)}, {typeof(IApplicationInfo),typeof(ApplicationInfo)}, {typeof(IEnvironmentInfo),typeof(EnvironmentInfo)} }; private IDictionary<Type, InstantiationModel> _instantationMappings = new Dictionary<Type, InstantiationModel>() { {typeof(IApplicationSettings), InstantiationModel.InstancePerCall}, {typeof(INetworkReachability), InstantiationModel.Singleton}, {typeof(IApplicationInfo),InstantiationModel.Singleton}, {typeof(IEnvironmentInfo),InstantiationModel.Singleton} }; private IDictionary<Type, object> _singletonServices = new Dictionary<Type, object>(); private ServiceFactory() { // Instantiate services registered as singletons. foreach (var service in _instantationMappings) { var serviceType = service.Key; if (service.Value == InstantiationModel.Singleton) { var serviceInstance = Activator.CreateInstance(_mappings[serviceType]); _singletonServices.Add(serviceType, serviceInstance); } } _factoryInitialized = true; } [SuppressMessage("Microsoft.Usage", "CA2211:NonConstantFieldsShouldNotBeVisible")] public static ServiceFactory Instance = new ServiceFactory(); public static void RegisterService<T>(Type serviceType) { if (_factoryInitialized) { throw new InvalidOperationException( "New services can only be registered before ServiceFactory is accessed by calling ServiceFactory.Instance ."); } lock (_lock) { _mappings[typeof(T)] = serviceType; } } public T GetService<T>() { var serviceType = typeof(T); if (_instantationMappings[serviceType] == InstantiationModel.Singleton) { return (T)_singletonServices[serviceType]; } var concreteType = GetServiceType<T>(); return (T)Activator.CreateInstance(concreteType); } private static Type GetServiceType<T>() { lock (_lock) { return _mappings[typeof(T)]; } } } }
97
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.CodeAnalysis; namespace Amazon.Util.Internal.PlatformServices { public class ApplicationInfo : IApplicationInfo { [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public string AppTitle { get { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public string AppVersionName { get { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public string AppVersionCode { get { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public string PackageName { get { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } } }
48
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Amazon.Util.Internal.PlatformServices { public class ApplicationSettings : IApplicationSettings { public void SetValue(string key, string value, ApplicationSettingsMode mode) { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } public string GetValue(string key, ApplicationSettingsMode mode) { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } public void RemoveValue(string key, ApplicationSettingsMode mode) { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } }
27
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.CodeAnalysis; using System.Globalization; using Microsoft.Win32; namespace Amazon.Util.Internal.PlatformServices { public class EnvironmentInfo : IEnvironmentInfo { public EnvironmentInfo() { this.Platform = Environment.OSVersion.Platform.ToString(); this.PlatformUserAgent = Environment.OSVersion.VersionString.Replace(" ", "_"); this.FrameworkUserAgent = string.Format(CultureInfo.InvariantCulture, ".NET_Runtime/{0}.{1} .NET_Framework/{2}", Environment.Version.Major, Environment.Version.MajorRevision, InternalSDKUtils.DetermineFramework()); } public string Platform { get; } public string PlatformUserAgent { get; } public string FrameworkUserAgent { get; } } }
34
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.CodeAnalysis; namespace Amazon.Util.Internal.PlatformServices { public class NetworkReachability : INetworkReachability { [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public NetworkStatus NetworkStatus { get { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public event EventHandler<NetworkStatusEventArgs> NetworkReachabilityChanged { add { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } remove { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } } }
32
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.CodeAnalysis; namespace Amazon.Util.Internal.PlatformServices { public class ApplicationInfo : IApplicationInfo { [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public string AppTitle { get { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public string AppVersionName { get { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public string AppVersionCode { get { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public string PackageName { get { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } } }
48
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Amazon.Util.Internal.PlatformServices { public class ApplicationSettings : IApplicationSettings { public void SetValue(string key, string value, ApplicationSettingsMode mode) { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } public string GetValue(string key, ApplicationSettingsMode mode) { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } public void RemoveValue(string key, ApplicationSettingsMode mode) { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } }
27
aws-sdk-net
aws
C#
 using System.Globalization; namespace Amazon.Util.Internal.PlatformServices { public class EnvironmentInfo : IEnvironmentInfo { public EnvironmentInfo() { this.Platform = InternalSDKUtils.DetermineOS(); this.PlatformUserAgent = InternalSDKUtils.PlatformUserAgent(); this.FrameworkUserAgent = InternalSDKUtils.DetermineFramework(); } public string Platform { get; } public string PlatformUserAgent { get; } public string FrameworkUserAgent { get; } } }
22
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.CodeAnalysis; namespace Amazon.Util.Internal.PlatformServices { public class NetworkReachability : INetworkReachability { [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public NetworkStatus NetworkStatus { get { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public event EventHandler<NetworkStatusEventArgs> NetworkReachabilityChanged { add { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } remove { throw new NotImplementedException(ServiceFactory.NotImplementedErrorMessage); } } } }
32
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ namespace Amazon.Util.Internal { /// <summary> /// Array extensions for cross compilation across different supported framework versions. /// </summary> static class ArrayEx { /// <summary> /// Returns an empty array. /// </summary> /// <typeparam name="T">The type of the elements of the array.</typeparam> /// <returns>An empty array.</returns> public static T[] Empty<T>() { return EmptyArray<T>.Value; } private static class EmptyArray<T> { #pragma warning disable CA1825 // this is the implementation of ArrayEx.Empty<T>() internal static readonly T[] Value = new T[0]; #pragma warning restore CA1825 } } }
40
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using System.Text; using Microsoft.Win32; using System.Globalization; namespace Amazon.Util.Internal { public static partial class InternalSDKUtils { private const string MobileServicesFolderName = "AWS Mobile Services"; #if BCL45 static string _userAgentBaseName = "aws-sdk-dotnet-45"; #else static string _userAgentBaseName = "aws-sdk-dotnet-35"; #endif public static string DetermineFramework() { try { if (Environment.Version.Major >= 4 && Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Net Framework Setup\\NDP\\v4") != null) return "4.0"; if (Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Net Framework Setup\\NDP\\v3.5") != null) return "3.5"; if (Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Net Framework Setup\\NDP\\v3.0") != null) return "3.0"; if (Registry.LocalMachine.OpenSubKey(@"Software\\Microsoft\\Net Framework Setup\\NDP\\v2.0.50727") != null) return "2.0"; } catch { } return "Unknown"; } public static string DetermineAppLocalStoragePath() { if (string.IsNullOrEmpty(AWSConfigs.ApplicationName)) throw new InvalidOperationException("AWSConfigs.ApplicationName does not have a valid value."); var basePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), MobileServicesFolderName); var basePathForApp = System.IO.Path.Combine(basePath, AWSConfigs.ApplicationName); return basePathForApp; } public static string DetermineAppLocalStoragePath(string fileName) { return System.IO.Path.Combine(DetermineAppLocalStoragePath(), fileName); } } }
77
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Amazon.Util.Internal { public static partial class TypeFactory { class TypeInfoWrapper : AbstractTypeInfo { internal TypeInfoWrapper(Type type) : base(type) { } public override Type BaseType { get { return this._type.BaseType; } } public override FieldInfo GetField(string name) { return this._type.GetField(name); } public override Type GetInterface(string name) { return this._type.GetInterfaces().FirstOrDefault(x => (x.Namespace + "." + x.Name) == name); } public override Type[] GetInterfaces() { return this._type.GetInterfaces(); } public override IEnumerable<PropertyInfo> GetProperties() { return this._type.GetProperties(); } public override IEnumerable<FieldInfo> GetFields() { return this._type.GetFields(); } public override MemberInfo[] GetMembers() { return this._type.GetMembers(); } public override bool IsClass { get { return this._type.IsClass; } } public override bool IsValueType { get { return this._type.IsValueType; } } public override bool IsInterface { get { return this._type.IsInterface; } } public override bool IsAbstract { get { return this._type.IsAbstract; } } public override bool IsSealed { get { return this._type.IsSealed; } } public override bool IsEnum { get { return this._type.IsEnum; } } public override MethodInfo GetMethod(string name) { return this._type.GetMethod(name); } public override MethodInfo GetMethod(string name, ITypeInfo[] paramTypes) { Type[] types = new Type[paramTypes.Length]; for (int i = 0; i < paramTypes.Length; i++) types[i] = ((AbstractTypeInfo)paramTypes[i]).Type; return this._type.GetMethod(name, types); } public override ConstructorInfo GetConstructor(ITypeInfo[] paramTypes) { Type[] types = new Type[paramTypes.Length]; for (int i = 0; i < paramTypes.Length; i++) types[i] = ((AbstractTypeInfo)paramTypes[i]).Type; var constructor = this._type.GetConstructor(types); return constructor; } public override PropertyInfo GetProperty(string name) { return this._type.GetProperty(name); } public override bool IsAssignableFrom(ITypeInfo typeInfo) { return this._type.IsAssignableFrom(((AbstractTypeInfo)typeInfo).Type); } public override bool ContainsGenericParameters { get { return this._type.ContainsGenericParameters; } } public override bool IsGenericTypeDefinition { get { return this._type.IsGenericTypeDefinition; } } public override bool IsGenericType { get { return this._type.IsGenericType; } } public override Type GetGenericTypeDefinition() { return this._type.GetGenericTypeDefinition(); } public override Type[] GetGenericArguments() { return this._type.GetGenericArguments(); } public override object[] GetCustomAttributes(bool inherit) { return this._type.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(ITypeInfo attributeType, bool inherit) { return this._type.GetCustomAttributes(((TypeInfoWrapper)attributeType)._type, inherit); } public override Assembly Assembly { get { return this._type.Assembly; } } } } }
180
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using System; using System.Runtime.CompilerServices; namespace Amazon.Util.Internal { /// <summary> /// Array extensions for cross compilation across different supported framework versions. /// </summary> static class ArrayEx { /// <summary> /// Returns an empty array. /// </summary> /// <typeparam name="T">The type of the elements of the array.</typeparam> /// <returns>An empty array.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T[] Empty<T>() { return Array.Empty<T>(); } } }
37
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; namespace Amazon.Util.Internal { public static partial class InternalSDKUtils { private const string UnknownPlaceholder = "Unknown"; private const string UnknownPlatform = "unknown_platform"; private static string _userAgentBaseName = "aws-sdk-dotnet-coreclr"; private static readonly string SpecialPlatformInformation; #pragma warning disable CA1810 // Initialize reference type static fields inline static InternalSDKUtils() #pragma warning restore CA1810 // Initialize reference type static fields inline { if (GetExecutionEnvironment() == null) { try { SpecialPlatformInformation = GetXamarinInformation() ?? GetUnityInformation(); } #pragma warning disable CA1031 // Do not catch general exception types catch #pragma warning restore CA1031 // Do not catch general exception types { SpecialPlatformInformation = null; } } } private static string GetXamarinInformation() { var xamarinDevice = Type.GetType("Xamarin.Forms.Device, Xamarin.Forms.Core"); if (xamarinDevice == null) { return null; } var runtime = xamarinDevice.GetProperty("RuntimePlatform")?.GetValue(null)?.ToString() ?? ""; var idiom = xamarinDevice.GetProperty("Idiom")?.GetValue(null)?.ToString() ?? ""; var platform = runtime + idiom; if (string.IsNullOrEmpty(platform)) { platform = UnknownPlatform; } return string.Format(CultureInfo.InvariantCulture, "Xamarin_{0}", "Xamarin"); } private static string GetUnityInformation() { var unityApplication = Type.GetType("UnityEngine.Application, UnityEngine.CoreModule"); if (unityApplication == null) { return null; } var platform = unityApplication.GetProperty("platform")?.GetValue(null)?.ToString() ?? UnknownPlatform; return string.Format(CultureInfo.InvariantCulture, "Unity_{0}", platform); } private static string GetValidSubstringOrUnknown(string str, int start, int end) { if ((start != -1) && (end != -1) && (0 <= start) && (end <= str.Length)) { string substr = str.Substring(start, end-start); if (!string.IsNullOrWhiteSpace(substr)) { return substr.Trim().Replace(' ', '_'); } } return UnknownPlaceholder; } /// <summary> /// Returns the type of platform and version.!-- If on a special platform, a static "0" is used as the version since /// we have nothing more specific that actually means anything. Otherwise, asks InteropServices RuntimeInformation for /// the OSDescription and trims off the OS name. /// </summary> public static string DetermineFramework() { if (SpecialPlatformInformation != null) { if(SpecialPlatformInformation.StartsWith("Xamarin")) { return "Xamarin/0"; } if (SpecialPlatformInformation.StartsWith("Unity")) { return "Unity/0"; } } try { var desc = RuntimeInformation.FrameworkDescription.Trim(); return string.Format(CultureInfo.InvariantCulture, ".NET_Core/{0}", GetValidSubstringOrUnknown(desc, desc.LastIndexOf(' ') + 1, desc.Length)); } catch { return UnknownPlaceholder; } } /// <summary> /// Returns the special platform information (e.g. Unity_OSXEditor, Xamarin_AndroidTablet) if /// on those platforms, otherwise asks InteropServices RuntimeInformation for the OSDescription /// and trims off the version. /// </summary> public static string DetermineOS() { if (SpecialPlatformInformation != null) { return SpecialPlatformInformation; } try { var desc = RuntimeInformation.OSDescription.Trim(); return GetValidSubstringOrUnknown(desc, 0, desc.LastIndexOf(' ')); } catch { return UnknownPlaceholder; } } /// <summary> /// Returns the special platform information (e.g. Unity_OSXEditor, Xamarin_AndroidTablet) if /// on those platforms, otherwise asks InteropServices RuntimeInformation for the OSDescription, /// keeping the version tail. /// </summary> public static string PlatformUserAgent() { try { var desc = SpecialPlatformInformation ?? RuntimeInformation.OSDescription; if (!string.IsNullOrWhiteSpace(desc)) { return desc.Trim().Replace(' ', '_'); } return UnknownPlaceholder; } catch { return UnknownPlaceholder; } } } }
179
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Amazon.Util.Internal { public static partial class TypeFactory { class TypeInfoWrapper : AbstractTypeInfo { TypeInfo _typeInfo; internal TypeInfoWrapper(Type type) : base(type) { this._typeInfo = type.GetTypeInfo(); } public override Type BaseType { get { return _typeInfo.BaseType; } } public override Type GetInterface(string name) { return this._typeInfo.ImplementedInterfaces.FirstOrDefault(x => (x.Namespace + "." + x.Name) == name); } public override Type[] GetInterfaces() { return this._typeInfo.ImplementedInterfaces.ToArray(); } public override IEnumerable<PropertyInfo> GetProperties() { return this._type.GetProperties(); } public override IEnumerable<FieldInfo> GetFields() { return this._type.GetFields(); } public override FieldInfo GetField(string name) { return this._type.GetField(name); } public override MemberInfo[] GetMembers() { var members = GetMembers_Helper(this._typeInfo).Distinct().ToArray(); return members; } private static readonly Type objectType = typeof(object); private static bool IsBackingField(MemberInfo mi) { var isBackingField = mi.Name.IndexOf("k__BackingField", StringComparison.Ordinal) >= 0; return isBackingField; } private static IEnumerable<MemberInfo> GetMembers_Helper(TypeInfo ti) { // Keep track of properties already returned. This makes sure properties that are overridden in sub classes are not returned back multiple times. var processedProperties = new HashSet<string>(); Func<MemberInfo, bool> alreadyProcessProperty = (member) => { return (member is PropertyInfo) && !processedProperties.Add(member.Name); }; var members = ti.DeclaredMembers; foreach (var member in members) { if (!IsBackingField(member) && !alreadyProcessProperty(member)) yield return member; } var baseType = ti.BaseType; var isObject = (baseType == objectType); if (baseType != null && !isObject) { var baseTi = baseType.GetTypeInfo(); var baseMembers = GetMembers_Helper(baseTi).ToList(); foreach (var baseMember in baseMembers) { if(!alreadyProcessProperty(baseMember)) { yield return baseMember; } } } } public override bool IsClass { get { return this._typeInfo.IsClass; } } public override bool IsValueType { get { return this._typeInfo.IsValueType; } } public override bool IsInterface { get { return this._typeInfo.IsInterface; } } public override bool IsAbstract { get { return this._typeInfo.IsAbstract; } } public override bool IsSealed { get { return this._typeInfo.IsSealed; } } public override bool IsEnum { get { return this._typeInfo.IsEnum; } } public override MethodInfo GetMethod(string name) { return this._type.GetMethod(name); } public override bool ContainsGenericParameters { get { return this._typeInfo.ContainsGenericParameters; } } public override bool IsGenericTypeDefinition { get { return this._typeInfo.IsGenericTypeDefinition; } } public override bool IsGenericType { get { return this._typeInfo.IsGenericType; } } public override Type GetGenericTypeDefinition() { return this._typeInfo.GetGenericTypeDefinition(); } public override Type[] GetGenericArguments() { return this._typeInfo.GenericTypeArguments; } public override MethodInfo GetMethod(string name, ITypeInfo[] paramTypes) { Type[] types = new Type[paramTypes.Length]; for (int i = 0; i < paramTypes.Length; i++) types[i] = ((AbstractTypeInfo)paramTypes[i]).Type; return this._type.GetMethod(name, types); } public override PropertyInfo GetProperty(string name) { return this._type.GetProperty(name); } public override bool IsAssignableFrom(ITypeInfo typeInfo) { return this._typeInfo.IsAssignableFrom(((TypeInfoWrapper)typeInfo)._typeInfo); } public override object[] GetCustomAttributes(bool inherit) { return CustomAttributeExtensions.GetCustomAttributes(this.Type.GetTypeInfo(), inherit).ToArray<object>(); } public override object[] GetCustomAttributes(ITypeInfo attributeType, bool inherit) { return CustomAttributeExtensions.GetCustomAttributes(this.Type.GetTypeInfo(), attributeType.Type, inherit).ToArray<object>(); } public override Assembly Assembly { get { return this._typeInfo.Assembly; } } public override ConstructorInfo GetConstructor(ITypeInfo[] paramTypes) { Type[] types = new Type[paramTypes.Length]; for (int i = 0; i < paramTypes.Length; i++) types[i] = ((AbstractTypeInfo)paramTypes[i]).Type; return this._type.GetConstructor(types); } } } }
223
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * */ using Amazon.Runtime; using System; using System.Collections.Generic; using Amazon.Util.Internal; namespace Amazon.Util { #region Basic sections /// <summary> /// Settings for configuring a proxy for the SDK to use. /// </summary> public partial class ProxyConfig { internal void Configure(ProxySection section) { if (section.ElementInformation.IsPresent) { Host = section.Host; Port = section.Port; Username = section.Username; Password = section.Password; BypassList = new List<string>(section.BypassList); BypassOnLocal = section.BypassOnLocal.GetValueOrDefault(); } } } /// <summary> /// Settings for logging in the SDK. /// </summary> public partial class LoggingConfig { internal void Configure(LoggingSection section) { if (section.ElementInformation.IsPresent) { LogTo = section.LogTo; LogResponses = section.LogResponses; LogResponsesSizeLimit = section.LogResponsesSizeLimit ?? LoggingConfig.DefaultLogResponsesSizeLimit; LogMetrics = section.LogMetrics.GetValueOrDefault(false); LogMetricsFormat = section.LogMetricsFormat; if (section.LogMetricsCustomFormatter != null && typeof(IMetricsFormatter).IsAssignableFrom(section.LogMetricsCustomFormatter)) { LogMetricsCustomFormatter = Activator.CreateInstance(section.LogMetricsCustomFormatter) as IMetricsFormatter; } } } } /// <summary> /// Settings for configuring CSM in the SDK. /// </summary> public partial class CSMConfig { internal void Configure(CSMSection section) { if (section.ElementInformation.IsPresent) { CSMEnabled = section.CSMEnabled; CSMClientId = section.CSMClientId; if (section.CSMPort.HasValue) { CSMPort = section.CSMPort.GetValueOrDefault(); } } } } #endregion }
96
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using System.Text; using Microsoft.Win32; using System.Globalization; namespace Amazon.Util { public static partial class AWSSDKUtils { public static void ForceCanonicalPathAndQuery(Uri uri) { try { string paq = uri.PathAndQuery; // need to access PathAndQuery FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic); ulong flags = (ulong)flagsFieldInfo.GetValue(uri); flags &= ~((ulong)0x30); // Flags.PathNotCanonical|Flags.QueryNotCanonical flagsFieldInfo.SetValue(uri, flags); } catch { } } static readonly object _preserveStackTraceLookupLock = new object(); static bool _preserveStackTraceLookup = false; static MethodInfo _preserveStackTrace = null; /// <summary> /// This method is used preserve the stacktrace used from clients that support async calls. This /// make sure that exceptions thrown during EndXXX methods has the orignal stacktrace that happen /// in the background thread. /// </summary> /// <param name="exception"></param> public static void PreserveStackTrace(Exception exception) { if (!_preserveStackTraceLookup) { lock (_preserveStackTraceLookupLock) { _preserveStackTraceLookup = true; try { _preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic); } catch { } } } if (_preserveStackTrace != null) { _preserveStackTrace.Invoke(exception, null); } } private const int _defaultDefaultConnectionLimit = 2; internal static int GetConnectionLimit(int? clientConfigValue) { // Connection limit has been explicitly set on the client. if (clientConfigValue.HasValue) return clientConfigValue.Value; // If default has been left at the system default return the SDK default. if (ServicePointManager.DefaultConnectionLimit == _defaultDefaultConnectionLimit) return AWSSDKUtils.DefaultConnectionLimit; // The system default has been explicitly changed so we will honor that value. return ServicePointManager.DefaultConnectionLimit; } private const int _defaultMaxIdleTime = 100 * 1000; internal static int GetMaxIdleTime(int? clientConfigValue) { // MaxIdleTime has been explicitly set on the client. if (clientConfigValue.HasValue) return clientConfigValue.Value; // If default has been left at the system default return the SDK default. if (ServicePointManager.MaxServicePointIdleTime == _defaultMaxIdleTime) return AWSSDKUtils.DefaultMaxIdleTime; // The system default has been explicitly changed so we will honor that value. return ServicePointManager.MaxServicePointIdleTime; } public static void Sleep(int ms) { System.Threading.Thread.Sleep(ms); } } }
114
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Runtime; using Amazon.Util.Internal; using System; using System.Globalization; using System.Security.Cryptography; using System.Text; namespace Amazon.Util { public static partial class CryptoUtilFactory { partial class CryptoUtil : ICryptoUtil { /// <summary> /// Computes a hash-based message authentication code /// </summary> /// <param name="data">Input to compute the hash code for</param> /// <param name="key">Signing key</param> /// <param name="algorithmName">Hashing algorithm to use</param> /// <returns>Computed hash code in base-64</returns> public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException("key", "Please specify a Secret Signing Key."); if (data == null || data.Length == 0) throw new ArgumentNullException("data", "Please specify data to sign."); KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture)); if (null == algorithm) throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use."); try { algorithm.Key = Encoding.UTF8.GetBytes(key); byte[] bytes = algorithm.ComputeHash(data); return Convert.ToBase64String(bytes); } finally { algorithm.Clear(); } } /// <summary> /// Computes a hash-based message authentication code /// </summary> /// <param name="data">Input to compute the hash code for</param> /// <param name="key">Signing key</param> /// <param name="algorithmName">Hashing algorithm to use</param> /// <returns>Computed hash code in bytes</returns> public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName) { if (key == null || key.Length == 0) throw new ArgumentNullException("key", "Please specify a Secret Signing Key."); if (data == null || data.Length == 0) throw new ArgumentNullException("data", "Please specify data to sign."); KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture)); if (null == algorithm) throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use."); try { algorithm.Key = key; byte[] bytes = algorithm.ComputeHash(data); return bytes; } finally { algorithm.Clear(); } } [ThreadStatic] private static HashAlgorithm _hashAlgorithm = null; private static HashAlgorithm SHA256HashAlgorithmInstance { get { if (null == _hashAlgorithm) { _hashAlgorithm = CreateSHA256Instance(); } return _hashAlgorithm; } } internal static HashAlgorithm CreateSHA256Instance() { try { return HashAlgorithm.Create("SHA-256"); } catch (Exception) // Managed Hash Provider is not FIPS compliant. { return new SHA256CryptoServiceProvider(); } } } } }
118
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; namespace Amazon.Util { /// <summary> /// AwsHttpClient is a wrapper around HttpClient class of the System.Net.Http library. /// The wrapper has been added so as to remove System.Net.Http dependencies from the Services /// and migrate it to a Core level dependecy only. This avoids version clashes when a service /// and the Core depends on different versions of the System.Net.Http library. This is a Service /// level utility method /// </summary> public class AWSHttpClient : IDisposable { private HttpClient _httpClient; private bool disposed = false; /// <summary> /// AWSHttpClient wrapper that is wrapped around /// HttpClient default wrapper. /// </summary> public AWSHttpClient() { _httpClient = new HttpClient(); } internal AWSHttpClient(IWebProxy proxy, bool useProxy) { _httpClient = new HttpClient(new HttpClientHandler { Proxy = proxy, UseProxy = useProxy }); } internal AWSHttpClient(HttpMessageHandler handler) { _httpClient = new HttpClient(handler); } internal AWSHttpClient(HttpMessageHandler handler, bool disposeHandler) { _httpClient = new HttpClient(handler, disposeHandler); } /// <summary> /// AWSHttpClient BaseAddress property that is wrapper for /// HttpClient BaseAddress property. /// </summary> public Uri BaseAddress { get { return _httpClient.BaseAddress; } set { _httpClient.BaseAddress = value; } } /// <summary> /// AWSHttpClient Timeout property that is wrapper for /// HttpClient Timeout property. /// </summary> public TimeSpan Timeout { get { return _httpClient.Timeout; } set { _httpClient.Timeout = value; } } /// <summary> /// AWSHttpClient MaxResponseContentBufferSize property that is wrapper for /// HttpClient MaxResponseContentBufferSize property. /// </summary> public long MaxResponseContentBufferSize { get { return _httpClient.MaxResponseContentBufferSize; } set { _httpClient.MaxResponseContentBufferSize = value; } } /// <summary> /// AWSHttpClient GetStreamAsync that accepts the requester's URI /// and make a HttpClient.GetStreamAsync call. /// </summary> /// <param name="requestUri">Requester Uri</param> public Task<Stream> GetStreamAsync(string requestUri) { return _httpClient.GetStreamAsync(requestUri); } /// <summary> /// Wrapper method that accepts a request uri, stream content and headers and makes a sendAsync call. /// </summary> /// <param name="requestUri"></param> /// <param name="content"></param> public Task PutRequestUriAsync(string requestUri, AWSStreamContent content, IDictionary<string, string> requestHeaders) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, requestUri); request.Content = content.StreamContent; foreach (var header in requestHeaders) request.Headers.TryAddWithoutValidation(header.Key, header.Value); return _httpClient.SendAsync(request); } /// <summary> /// Wrapper for HttpClient's HttpRequestMessage and SendAsync methods. /// </summary> /// <param name="httpMethodValue"></param> /// <param name="url"></param> /// <returns>Returns response headers information- header name,value and status code</returns> public async Task<List<Tuple<string, IEnumerable<string>, HttpStatusCode>>> GetResponseHeadersAsync(string httpMethodValue, string url) { HttpMethod httpMethod = new HttpMethod(httpMethodValue); var headers = new List<Tuple<string, IEnumerable<string>, HttpStatusCode>>(); var request = new HttpRequestMessage(httpMethod, url); var response = await _httpClient.SendAsync(request).ConfigureAwait(false); foreach (var header in response.Headers) { headers.Add(new Tuple<string, IEnumerable<string>, HttpStatusCode>(header.Key, header.Value, response.StatusCode)); } return headers; } /// <summary> /// Wrapper for HttpClient Dispose. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { _httpClient.Dispose(); } disposed = true; } /// <summary> /// Method that checks if the passed exception is of type /// HttpRequestException /// </summary> /// <param name="exception"></param> /// <returns></returns> public static bool IsHttpInnerException(Exception exception) { return (exception is HttpRequestException); } } }
196
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Amazon.Util { /// <summary> /// AWSStreamContent is a wrapper for StreamContent class in /// the System.Net.Http library.The wrapper has been added so as to /// remove System.Net.Http dependencies from the Services /// and migrate it to a Core level dependecy only. This avoids version clashes when a service /// and the Core depends on different versions of the System.Net.Http library. This is a Service /// level utility method /// </summary> public class AWSStreamContent : IDisposable { private bool disposed = false; internal StreamContent StreamContent { get; set; } /// <summary> /// Wrapper for StreamContent constructor /// for stream content /// </summary> /// <param name="content"></param> public AWSStreamContent(Stream content) { StreamContent = new StreamContent(content); } /// <summary> /// Wrapper for StreamContent constructor /// for stream content and bufferSize /// </summary> /// <param name="content"></param> /// <param name="bufferSize"></param> public AWSStreamContent(Stream content, int bufferSize) { StreamContent = new StreamContent(content, bufferSize); } /// <summary> /// Wrapper to allow Services to remove StreamContent Headers /// </summary> /// <param name="name"></param> /// <returns></returns> public bool RemoveHttpContentHeader(string name) { return StreamContent.Headers.Remove(name); } /// <summary> /// Wrapper to allow Services to add StreamContent Headers /// </summary> /// <param name="name"></param> /// <returns></returns> public void AddHttpContentHeader(string name, string value) { StreamContent.Headers.Add(name, value); } /// <summary> /// Wrapper for StreamContent Dispose. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { StreamContent.Dispose(); } disposed = true; } } }
109
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using System.Text; using Microsoft.Win32; using System.Globalization; namespace Amazon.Util { public static partial class AWSSDKUtils { public static void ForceCanonicalPathAndQuery(Uri uri) { } /// <summary> /// This method is used preserve the stacktrace used from clients that support async calls. This /// make sure that exceptions thrown during EndXXX methods has the orignal stacktrace that happen /// in the background thread. /// </summary> /// <param name="exception"></param> public static void PreserveStackTrace(Exception exception) { } internal static int GetConnectionLimit(int? clientConfigValue) { if (clientConfigValue.HasValue) return clientConfigValue.Value; return AWSSDKUtils.DefaultConnectionLimit; } public static void Sleep(int ms) { System.Threading.Thread.Sleep(ms); } } }
62
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using Amazon.Runtime; using Amazon.Util.Internal; using System; using System.Security.Cryptography; using System.Text; namespace Amazon.Util { public static partial class CryptoUtilFactory { partial class CryptoUtil : ICryptoUtil { public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName) { if (String.IsNullOrEmpty(key)) throw new ArgumentNullException("key", "Please specify a Secret Signing Key."); if (data == null || data.Length == 0) throw new ArgumentNullException("data", "Please specify data to sign."); KeyedHashAlgorithm algorithm = CreateKeyedHashAlgorithm(algorithmName); if (null == algorithm) throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use."); try { algorithm.Key = Encoding.UTF8.GetBytes(key); byte[] bytes = algorithm.ComputeHash(data); return Convert.ToBase64String(bytes); } finally { algorithm.Dispose(); } } public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName) { if (key == null || key.Length == 0) throw new ArgumentNullException("key", "Please specify a Secret Signing Key."); if (data == null || data.Length == 0) throw new ArgumentNullException("data", "Please specify data to sign."); KeyedHashAlgorithm algorithm = CreateKeyedHashAlgorithm(algorithmName); if (null == algorithm) throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use."); try { algorithm.Key = key; byte[] bytes = algorithm.ComputeHash(data); return bytes; } finally { algorithm.Dispose(); } } KeyedHashAlgorithm CreateKeyedHashAlgorithm(SigningAlgorithm algorithmName) { KeyedHashAlgorithm algorithm; switch (algorithmName) { case SigningAlgorithm.HmacSHA256: algorithm = new HMACSHA256(); break; case SigningAlgorithm.HmacSHA1: algorithm = new HMACSHA1(); break; default: throw new Exception(string.Format("KeyedHashAlgorithm {0} was not found.", algorithmName.ToString())); } return algorithm; } [ThreadStatic] private static HashAlgorithm _hashAlgorithm = null; private static HashAlgorithm SHA256HashAlgorithmInstance { get { if (null == _hashAlgorithm) { _hashAlgorithm = CreateSHA256Instance(); } return _hashAlgorithm; } } internal static HashAlgorithm CreateSHA256Instance() { return SHA256.Create(); } } } }
120
aws-sdk-net
aws
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; namespace Amazon.Util { internal static class Extensions { internal static string ToUpper(this String str, CultureInfo culture) { if (culture != CultureInfo.InvariantCulture) throw new ArgumentException("The extension method ToUpper only works for invariant culture"); return str.ToUpperInvariant(); } } }
19
aws-sdk-net
aws
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.Core")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Core Runtime")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Core Runtime")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Core Runtime")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Core Runtime")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.107.9")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif #if BCL45 // Setting SecurityRules to level 1 to match .NET 2.0 rules and allow the // Amazon.Util.Settings.UserCrypto methods to work in .NET 4.5 [assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)] #endif
57
aws-sdk-net
aws
C#
using Amazon.Runtime; using System; namespace Amazon.Internal { /// <summary> /// Customizations for <see cref="IRegionEndpoint.GetEndpointForService(string,GetEndpointForServiceOptions)"/> /// </summary> [Obsolete("This class is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public class GetEndpointForServiceOptions { /// <summary> /// If true a dualstack endpoint is returned. It is the user's responsibility to verify that the given service /// supports a dualstack endpoint for the region. /// </summary> public bool DualStack { get; set; } /// <summary> /// If true an endpoint that supports FIPS is returned. It is the user's responsibility to verify that the given service /// supports a FIPS endpoint for the region. For background, see https://aws.amazon.com/compliance/fips/ /// </summary> public bool FIPS { get; set; } } [Obsolete("This class is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public static class GetEndpointForServiceOptionsExtensions { public static GetEndpointForServiceOptions ToGetEndpointForServiceOptions(this IClientConfig config) { return new GetEndpointForServiceOptions { DualStack = config.UseDualstackEndpoint, FIPS = config.UseFIPSEndpoint }; } public static RegionEndpoint.Endpoint GetEndpointForService(this RegionEndpoint endpoint, IClientConfig config) { return endpoint.GetEndpointForService(config.RegionEndpointServiceName, config.ToGetEndpointForServiceOptions()); } } }
41
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * */ using System; using System.Collections.Generic; namespace Amazon.Internal { public interface IRegionEndpoint { string RegionName { get; } string DisplayName { get; } [Obsolete("Use GetEndpointForService(string serviceName, GetEndpointForServiceOptions options) instead", error: false)] Amazon.RegionEndpoint.Endpoint GetEndpointForService(string serviceName, bool dualStack); /// <summary> /// Gets the endpoint for a service in a region. /// <para /> /// For forwards compatibility, if the service being requested for isn't known in the region, this method /// will generate an endpoint using the AWS endpoint heuristics. In this case, it is not guaranteed the /// endpoint will point to a valid service endpoint. /// </summary> /// <param name="serviceName"> /// The services system name. Service system names can be obtained from the /// RegionEndpointServiceName member of the ClientConfig-derived class for the service. /// </param> /// <param name="options"> /// Specify additional requirements on the <see cref="RegionEndpoint.Endpoint"/> to be returned. /// </param> [Obsolete("This operation is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] Amazon.RegionEndpoint.Endpoint GetEndpointForService(string serviceName, GetEndpointForServiceOptions options); } [Obsolete("This interface is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public interface IRegionEndpointProvider { IEnumerable<IRegionEndpoint> AllRegionEndpoints { get; } IRegionEndpoint GetRegionEndpoint(string regionName); string GetDnsSuffixForPartition(string partition); } }
61
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * */ using Amazon.Internal; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Threading; using ThirdParty.Json.LitJson; namespace Amazon { /// <summary> /// This class contains region information used to lazily compute the service endpoints. The static constants representing the /// regions can be used while constructing the AWS client instead of looking up the exact endpoint URL. /// </summary> public partial class RegionEndpoint { #region Statics private static Dictionary<string, RegionEndpoint> _hashBySystemName = new Dictionary<string, RegionEndpoint>(StringComparer.OrdinalIgnoreCase); private static ReaderWriterLockSlim _regionEndpointOverrideLock = new ReaderWriterLockSlim(); // controls access to _hashRegionEndpointOverride /// <summary> /// Represents the endpoint overridding rules in the endpoints.json /// Is used to map private region (ie us-east-1-regional) to public regions (us-east-1) /// For signing purposes. Map is keyed by region SystemName. /// </summary> private static Dictionary<string, RegionEndpoint> _hashRegionEndpointOverride = new Dictionary<string, RegionEndpoint>(); /// <summary> /// Enumerate through all the regions. /// </summary> public static IEnumerable<RegionEndpoint> EnumerableAllRegions { get { List<RegionEndpoint> list = new List<RegionEndpoint>(); foreach (IRegionEndpoint endpoint in RegionEndpointProvider.AllRegionEndpoints) { list.Add(GetEndpoint(endpoint.RegionName, endpoint.DisplayName)); } return list; } } /// <summary> /// Gets the region based on its system name like "us-west-1" /// </summary> /// <param name="systemName">The system name of the service like "us-west-1"</param> /// <returns></returns> public static RegionEndpoint GetBySystemName(string systemName) { return GetEndpoint(systemName, null); } /// <summary> /// Gets the region endpoint override if exists /// </summary> /// <param name="regionEndpoint">The region endpoint to find the possible override for</param> /// <returns></returns> [Obsolete("This operation is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public static RegionEndpoint GetRegionEndpointOverride(RegionEndpoint regionEndpoint) { try { _regionEndpointOverrideLock.EnterReadLock(); if (!_hashRegionEndpointOverride.TryGetValue(regionEndpoint.SystemName, out var regionEndpointOverride)) { return null; } return regionEndpointOverride; } finally { _regionEndpointOverrideLock.ExitReadLock(); } } /// <summary> /// Force the SDK to load and apply the given endpoints details /// (eg: an updated endpoints.json file). /// Service clients created after this call will be set up with /// endpoints based on this information. /// /// This function should only be used at application startup, before /// creating service clients. /// /// Known Caveats: /// * static readonly fields (eg: <see cref="RegionEndpoint.USEast1"/>) are not updated. /// If you use this function, you should use <see cref="RegionEndpoint.GetEndpoint"/> with /// explicit region system names to ensure you work with RegionEndpoint objects containing /// the reloaded data. RegionEndpoint objects returned from GetEndpoint will generally /// fail Equality comparisons against the static fields. /// * Service clients created before calling Reload have no guarantee around /// which endpoint data will be used. /// </summary> /// <param name="stream">Stream containing an Endpoints manifest to reload in the SDK. /// Pass null in to reset the SDK, so that it uses its built-in manifest instead.</param> [Obsolete("This operation is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public static void Reload(Stream stream) { if (stream == null) { _regionEndpointProvider = null; } else { JsonData rootData = null; using (StreamReader reader = new StreamReader(stream)) { rootData = JsonMapper.ToObject(reader); } var manifestVersion = rootData?["version"]?.ToString(); if (manifestVersion == "3") { _regionEndpointProvider = new RegionEndpointProviderV3(rootData); } else { throw new NotSupportedException("Endpoints data format is not supported by reload"); } } // Reset static lookup maps that may contain objects relating to old endpoint data lock (_hashBySystemName) { _hashBySystemName.Clear(); // Add the .NET/S3-specific legacy region back to the lookup map GetEndpoint("us-east-1-regional", "US East (Virginia) regional"); } ResetRegionEndpointOverride(); } /// <summary> /// Rebuilds the endpoint override map, referencing the SDK's current Region Endpoint data. /// </summary> private static void ResetRegionEndpointOverride() { try { _regionEndpointOverrideLock.EnterWriteLock(); _hashRegionEndpointOverride.Clear(); _hashRegionEndpointOverride.Add(USEast1Regional.SystemName, GetEndpoint(USEast1.SystemName, null)); } finally { _regionEndpointOverrideLock.ExitWriteLock(); } } /// <summary> /// Returns the DNS suffix for the given partition, or /// an empty string if a matching partition was not found in endpoints.json /// </summary> /// <param name="partition">partition</param> /// <returns>DNS suffix for the given partition, empty string if a matching partition was not found</returns> [Obsolete("This operation is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public static string GetDnsSuffixForPartition(string partition) { return RegionEndpointProvider.GetDnsSuffixForPartition(partition); } private static RegionEndpoint GetEndpoint(string systemName, string displayName) { RegionEndpoint regionEndpoint = null; if (displayName == null) { lock (_hashBySystemName) { if (_hashBySystemName.TryGetValue(systemName, out regionEndpoint)) return regionEndpoint; } // GetRegionEndpoint will always return a non-null value. If the the region(systemName) is unknown, // the providers will create a fallback instance that will generate an endpoint to the best // of its knowledge. displayName = RegionEndpointProvider.GetRegionEndpoint(systemName).DisplayName; } lock (_hashBySystemName) { if (_hashBySystemName.TryGetValue(systemName, out regionEndpoint)) return regionEndpoint; regionEndpoint = new RegionEndpoint(systemName, displayName); _hashBySystemName.Add(regionEndpoint.SystemName, regionEndpoint); } return regionEndpoint; } private static IRegionEndpointProvider _regionEndpointProvider; private static IRegionEndpointProvider RegionEndpointProvider { get { if (_regionEndpointProvider == null) { // If the existing customer provided the endpoints.json file via // <aws endpointDefinition=""/>, it's in v2 format. We we will create // a v2 provider which does a fall through during LoadEndpointDefinitions() // and loads from the override file provided by the user. // // Else, we are loading from the assembly resource. In which case we use the // latest provider. // // It's actually a bug that _regionEndpointProvider is a static member variable // since the IEndpointProvider should respect the AWSConfigs.EndpointDefinition // _at_ the time of the service client instantiation. However, since this is // the existing behavior with v2 endpoint file format, we will preserve this behavior as is. if (!string.IsNullOrEmpty(AWSConfigs.EndpointDefinition)) { _regionEndpointProvider = new RegionEndpointProviderV2(); } else { _regionEndpointProvider = new RegionEndpointProviderV3(); } } return _regionEndpointProvider; } } #endregion private RegionEndpoint(string systemName, string displayName) { this.SystemName = systemName; this.OriginalSystemName = systemName; this.DisplayName = displayName; } /// <summary> /// Gets the system name of a region. /// </summary> public string SystemName { get; private set; } [Obsolete("It should not be necessary to use this property. To support upgrading to Endpoint Variants, " + "ClientConfig will manipulate the assigned RegionEndpoint. To support the Polly PreSigner, it's still necessary" + "to check the OriginalSystemName to determine if a PseudoRegion was assigned.",error: false)] public string OriginalSystemName { get; internal set; } /// <summary> /// Gets the display name of a region. /// </summary> public string DisplayName { get; private set; } /// <summary> /// Gets the partition name the region is in. For example for us-east-1 the partition name is aws. For cn-northwest-1 the partition name is aws-cn. /// </summary> public string PartitionName { get { var regionEndpointV3 = this.InternedRegionEndpoint as RegionEndpointV3; return regionEndpointV3?.PartitionName; } } /// <summary> /// Gets the dns suffix for the region endpoints in a partition. For example the aws partition's suffix is amazonaws.com. The aws-cn partition's suffix is amazonaws.com.cn. /// </summary> public string PartitionDnsSuffix { get { var regionEndpointV3 = this.InternedRegionEndpoint as RegionEndpointV3; return regionEndpointV3?.PartitionDnsSuffix; } } private IRegionEndpoint InternedRegionEndpoint { get { return RegionEndpointProvider.GetRegionEndpoint(SystemName); } } /// <summary> /// Gets the endpoint for a service in a region. /// </summary> /// <param name="serviceName"> /// The services system name. Service system names can be obtained from the /// RegionEndpointServiceName member of the ClientConfig-derived class for the service. /// </param> /// <param> /// For forwards compatibility, if the service being requested for isn't known in the region, this method /// will generate an endpoint using the AWS endpoint heuristics. In this case, it is not guaranteed the /// endpoint will point to a valid service endpoint. /// </param> /// <returns></returns> [Obsolete("This operation is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public Endpoint GetEndpointForService(string serviceName) { return GetEndpointForService(serviceName, new GetEndpointForServiceOptions()); } /// <summary> /// Gets the endpoint for a service in a region, optionally selecting a dualstack compatible endpoint. /// </summary> /// <param name="serviceName"> /// The services system name. Service system names can be obtained from the /// RegionEndpointServiceName member of the ClientConfig-derived class for the service. /// </param> /// <param name="dualStack"> /// If true a dualstack endpoint is returned. It is the user's responsibility to verify that the given service /// supports a dualstack endpoint for the region. /// </param> /// <param> /// For forwards compatibility, if the service being requested for isn't known in the region, this method /// will generate an endpoint using the AWS endpoint heuristics. In this case, it is not guaranteed the /// endpoint will point to a valid service endpoint. /// </param> [Obsolete("Use GetEndpointForService(string serviceName, GetEndpointForServiceOptions options) instead", error: false)] public Endpoint GetEndpointForService(string serviceName, bool dualStack) { return GetEndpointForService(serviceName, new GetEndpointForServiceOptions {DualStack = dualStack}); } /// <summary> /// Gets the endpoint for a service in a region. /// <para /> /// For forwards compatibility, if the service being requested for isn't known in the region, this method /// will generate an endpoint using the AWS endpoint heuristics. In this case, it is not guaranteed the /// endpoint will point to a valid service endpoint. /// </summary> /// <param name="serviceName"> /// The services system name. Service system names can be obtained from the /// RegionEndpointServiceName member of the ClientConfig-derived class for the service. /// </param> /// <param name="options"> /// Specify additional requirements on the <see cref="Endpoint"/> to be returned. /// </param> [Obsolete("This operation is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public Endpoint GetEndpointForService(string serviceName, GetEndpointForServiceOptions options) { return InternedRegionEndpoint.GetEndpointForService(serviceName, options); } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0} ({1})", this.DisplayName, this.SystemName); } /// <summary> /// This class defines an endpoints hostname and which protocols it supports. /// </summary> [Obsolete("This class is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public class Endpoint { internal Endpoint(string hostname, string authregion, string signatureVersionOverride, string dnsSuffix, bool deprecated) { this.Hostname = hostname; this.AuthRegion = authregion; this.SignatureVersionOverride = signatureVersionOverride; this.Deprecated = deprecated; this.DnsSuffix = dnsSuffix; } /// <summary> /// Gets the hostname for the service. /// </summary> public string Hostname { get; private set; } /// <summary> /// Gets the DNS suffix for the service. /// </summary> public string DnsSuffix { get; private set; } /// <summary> /// The authentication region to be used in request signing. /// </summary> public string AuthRegion { get; private set; } public override string ToString() { return this.Hostname; } /// <summary> /// This property is only set for S3 endpoints. For all other services this property returns null. /// For S3 endpoints, if the endpoint supports signature version 2 this property will be "2", otherwise it will be "4". /// </summary> public string SignatureVersionOverride { get; private set; } /// <summary> /// Gets the hostname for the service. /// </summary> public bool Deprecated { get; private set; } } } }
450
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * */ namespace Amazon { /// <summary> /// This class contains region information used to lazily compute the service endpoints. The static constants representing the /// regions can be used while constructing the AWS client instead of looking up the exact endpoint URL. /// </summary> public partial class RegionEndpoint { /// <summary> /// The US East (Virginia) regional endpoint. /// S3-specific, use for backward compatibility only. /// </summary> private static readonly RegionEndpoint USEast1Regional = GetEndpoint("us-east-1-regional", "US East (Virginia) regional"); /// <summary> /// The Africa (Cape Town) endpoint. /// </summary> public static readonly RegionEndpoint AFSouth1 = GetEndpoint("af-south-1", "Africa (Cape Town)"); /// <summary> /// The Asia Pacific (Hong Kong) endpoint. /// </summary> public static readonly RegionEndpoint APEast1 = GetEndpoint("ap-east-1", "Asia Pacific (Hong Kong)"); /// <summary> /// The Asia Pacific (Tokyo) endpoint. /// </summary> public static readonly RegionEndpoint APNortheast1 = GetEndpoint("ap-northeast-1", "Asia Pacific (Tokyo)"); /// <summary> /// The Asia Pacific (Seoul) endpoint. /// </summary> public static readonly RegionEndpoint APNortheast2 = GetEndpoint("ap-northeast-2", "Asia Pacific (Seoul)"); /// <summary> /// The Asia Pacific (Osaka) endpoint. /// </summary> public static readonly RegionEndpoint APNortheast3 = GetEndpoint("ap-northeast-3", "Asia Pacific (Osaka)"); /// <summary> /// The Asia Pacific (Mumbai) endpoint. /// </summary> public static readonly RegionEndpoint APSouth1 = GetEndpoint("ap-south-1", "Asia Pacific (Mumbai)"); /// <summary> /// The Asia Pacific (Hyderabad) endpoint. /// </summary> public static readonly RegionEndpoint APSouth2 = GetEndpoint("ap-south-2", "Asia Pacific (Hyderabad)"); /// <summary> /// The Asia Pacific (Singapore) endpoint. /// </summary> public static readonly RegionEndpoint APSoutheast1 = GetEndpoint("ap-southeast-1", "Asia Pacific (Singapore)"); /// <summary> /// The Asia Pacific (Sydney) endpoint. /// </summary> public static readonly RegionEndpoint APSoutheast2 = GetEndpoint("ap-southeast-2", "Asia Pacific (Sydney)"); /// <summary> /// The Asia Pacific (Jakarta) endpoint. /// </summary> public static readonly RegionEndpoint APSoutheast3 = GetEndpoint("ap-southeast-3", "Asia Pacific (Jakarta)"); /// <summary> /// The Asia Pacific (Melbourne) endpoint. /// </summary> public static readonly RegionEndpoint APSoutheast4 = GetEndpoint("ap-southeast-4", "Asia Pacific (Melbourne)"); /// <summary> /// The Canada (Central) endpoint. /// </summary> public static readonly RegionEndpoint CACentral1 = GetEndpoint("ca-central-1", "Canada (Central)"); /// <summary> /// The Europe (Frankfurt) endpoint. /// </summary> public static readonly RegionEndpoint EUCentral1 = GetEndpoint("eu-central-1", "Europe (Frankfurt)"); /// <summary> /// The Europe (Zurich) endpoint. /// </summary> public static readonly RegionEndpoint EUCentral2 = GetEndpoint("eu-central-2", "Europe (Zurich)"); /// <summary> /// The Europe (Stockholm) endpoint. /// </summary> public static readonly RegionEndpoint EUNorth1 = GetEndpoint("eu-north-1", "Europe (Stockholm)"); /// <summary> /// The Europe (Milan) endpoint. /// </summary> public static readonly RegionEndpoint EUSouth1 = GetEndpoint("eu-south-1", "Europe (Milan)"); /// <summary> /// The Europe (Spain) endpoint. /// </summary> public static readonly RegionEndpoint EUSouth2 = GetEndpoint("eu-south-2", "Europe (Spain)"); /// <summary> /// The Europe (Ireland) endpoint. /// </summary> public static readonly RegionEndpoint EUWest1 = GetEndpoint("eu-west-1", "Europe (Ireland)"); /// <summary> /// The Europe (London) endpoint. /// </summary> public static readonly RegionEndpoint EUWest2 = GetEndpoint("eu-west-2", "Europe (London)"); /// <summary> /// The Europe (Paris) endpoint. /// </summary> public static readonly RegionEndpoint EUWest3 = GetEndpoint("eu-west-3", "Europe (Paris)"); /// <summary> /// The Middle East (UAE) endpoint. /// </summary> public static readonly RegionEndpoint MECentral1 = GetEndpoint("me-central-1", "Middle East (UAE)"); /// <summary> /// The Middle East (Bahrain) endpoint. /// </summary> public static readonly RegionEndpoint MESouth1 = GetEndpoint("me-south-1", "Middle East (Bahrain)"); /// <summary> /// The South America (Sao Paulo) endpoint. /// </summary> public static readonly RegionEndpoint SAEast1 = GetEndpoint("sa-east-1", "South America (Sao Paulo)"); /// <summary> /// The US East (N. Virginia) endpoint. /// </summary> public static readonly RegionEndpoint USEast1 = GetEndpoint("us-east-1", "US East (N. Virginia)"); /// <summary> /// The US East (Ohio) endpoint. /// </summary> public static readonly RegionEndpoint USEast2 = GetEndpoint("us-east-2", "US East (Ohio)"); /// <summary> /// The US West (N. California) endpoint. /// </summary> public static readonly RegionEndpoint USWest1 = GetEndpoint("us-west-1", "US West (N. California)"); /// <summary> /// The US West (Oregon) endpoint. /// </summary> public static readonly RegionEndpoint USWest2 = GetEndpoint("us-west-2", "US West (Oregon)"); /// <summary> /// The China (Beijing) endpoint. /// </summary> public static readonly RegionEndpoint CNNorth1 = GetEndpoint("cn-north-1", "China (Beijing)"); /// <summary> /// The China (Ningxia) endpoint. /// </summary> public static readonly RegionEndpoint CNNorthWest1 = GetEndpoint("cn-northwest-1", "China (Ningxia)"); /// <summary> /// The AWS GovCloud (US-East) endpoint. /// </summary> public static readonly RegionEndpoint USGovCloudEast1 = GetEndpoint("us-gov-east-1", "AWS GovCloud (US-East)"); /// <summary> /// The AWS GovCloud (US-West) endpoint. /// </summary> public static readonly RegionEndpoint USGovCloudWest1 = GetEndpoint("us-gov-west-1", "AWS GovCloud (US-West)"); /// <summary> /// The US ISO East endpoint. /// </summary> public static readonly RegionEndpoint USIsoEast1 = GetEndpoint("us-iso-east-1", "US ISO East"); /// <summary> /// The US ISO WEST endpoint. /// </summary> public static readonly RegionEndpoint USIsoWest1 = GetEndpoint("us-iso-west-1", "US ISO WEST"); /// <summary> /// The US ISOB East (Ohio) endpoint. /// </summary> public static readonly RegionEndpoint USIsobEast1 = GetEndpoint("us-isob-east-1", "US ISOB East (Ohio)"); } }
206
aws-sdk-net
aws
C#
/******************************************************************************* * Copyright Amazon.com, 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Threading; using System.Xml; using System.Xml.Linq; using Amazon.Runtime; using System.Globalization; using Amazon.Runtime.Internal.Util; using Amazon.Util.Internal; using ThirdParty.Json.LitJson; using System.Linq; namespace Amazon.Internal { [Obsolete("This class is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public class RegionEndpointProviderV2 : IRegionEndpointProvider { /// <summary> /// Allows to configure the proxy used for HTTP requests. The default value is null. /// </summary> public static IWebProxy Proxy { get; set; } public IEnumerable<IRegionEndpoint> AllRegionEndpoints { get { return RegionEndpoint.EnumerableAllRegions as IEnumerable<IRegionEndpoint>; } } /// <summary> /// Returns the DNS suffix for the given partition, or /// an empty string if a matching partition was not found /// </summary> /// <param name="partition">partition</param> /// <returns>DNS suffix for the given partition, empty string if a matching partition was not found</returns> public string GetDnsSuffixForPartition(string partition) { switch (partition) { case "aws": case "aws-us-gov": return "amazonaws.com"; case "aws-cn": return "amazonaws.com.cn"; case "aws-iso": return "c2s.ic.gov"; case "aws-iso-b": return "sc2s.sgov.gov"; default: throw new AmazonClientException($"Unable to determine the DNS suffix for partition {partition} using {nameof(RegionEndpointProviderV2)}"); } } public IRegionEndpoint GetRegionEndpoint(string regionName) { return RegionEndpoint.GetBySystemName(regionName); } #region RegionEndpoint /// <summary> /// This class contains the endpoints available to the AWS clients. The static constants representing the /// regions can be used while constructing the AWS client instead of looking up the exact endpoint URL. /// </summary> public class RegionEndpoint : IRegionEndpoint { #if NETSTANDARD // The shared endpoint rules used by other AWS SDKs. const string REGIONS_FILE = "Core.endpoints.json"; // The .NET SDK specific customization to support legacy decisions made for endpoints. const string REGIONS_CUSTOMIZATIONS_FILE = "Core.endpoints.customizations.json"; #else // The shared endpoint rules used by other AWS SDKs. const string REGIONS_FILE = "Amazon.endpoints.json"; // The .NET SDK specific customization to support legacy decisions made for endpoints. const string REGIONS_CUSTOMIZATIONS_FILE = "Amazon.endpoints.customizations.json"; #endif const string DEFAULT_RULE = "*/*"; #region Statics static Dictionary<string, JsonData> _documentEndpoints; const int MAX_DOWNLOAD_RETRIES = 3; static bool loaded = false; static readonly object LOCK_OBJECT = new object(); // Dictionary of regions by system name private static Dictionary<string, RegionEndpoint> hashBySystemName = new Dictionary<string, RegionEndpoint>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets the endpoint for a service in a region. /// </summary> /// <param name="serviceName">The services system name.</param> /// <param name="dualStack">If true returns the endpoint for dualstack</param> /// <exception cref="System.ArgumentException">Thrown when the request service does not have a valid endpoint in the region.</exception> [Obsolete("Use GetEndpointForService(string serviceName, GetEndpointForServiceOptions options) instead", error: false)] public Amazon.RegionEndpoint.Endpoint GetEndpointForService(string serviceName, bool dualStack) { return GetEndpointForService(serviceName, new GetEndpointForServiceOptions { DualStack = dualStack }); } /// <summary> /// Gets the endpoint for a service in a region. /// </summary> /// <param name="serviceName">The services system name.</param> /// <param name="options"> Specify additional requirements on the <see cref="Amazon.RegionEndpoint.Endpoint"/> to be returned.</param> /// <exception cref="System.ArgumentException">Thrown when the request service does not have a valid endpoint in the region.</exception> public Amazon.RegionEndpoint.Endpoint GetEndpointForService(string serviceName, GetEndpointForServiceOptions options) { if (options?.FIPS == true) throw new NotSupportedException($"{typeof(RegionEndpointProviderV2)} does not support FIPS"); if (!RegionEndpoint.loaded) RegionEndpoint.LoadEndpointDefinitions(); var rule = GetEndpointRule(serviceName); var endpointTemplate = rule["endpoint"].ToString(); if (options?.DualStack == true) { // We need special handling for S3's s3.amazonaws.com endpoint, which doesn't // support dualstack (need to transform to s3.dualstack.us-east-1.amazonaws.com). // Other endpoints that begin s3-* need to transform to s3.* for dualstack support. // S3's 'external' endpoints do not support dualstack and should not be transformed. if (serviceName.Equals("s3", StringComparison.OrdinalIgnoreCase)) { if (endpointTemplate.Equals("s3.amazonaws.com", StringComparison.OrdinalIgnoreCase)) endpointTemplate = "s3.dualstack.us-east-1.amazonaws.com"; else { var isExternalEndpoint = endpointTemplate.StartsWith("s3-external-", StringComparison.OrdinalIgnoreCase); if (!isExternalEndpoint) { // transform fixed s3-<region> to s3.<region> and then onto s3.dualstack.<region>, // bypassing endpoints that do not start with the expected tags. if (endpointTemplate.StartsWith("s3-", StringComparison.OrdinalIgnoreCase)) endpointTemplate = "s3." + endpointTemplate.Substring(3); if (endpointTemplate.StartsWith("s3.", StringComparison.OrdinalIgnoreCase)) endpointTemplate = endpointTemplate.Replace("s3.", "s3.dualstack."); } } } else endpointTemplate = endpointTemplate.Replace("{region}", "dualstack.{region}"); } var hostName = endpointTemplate.Replace("{region}", this.SystemName).Replace("{service}", serviceName); string signatureVersion = null; if (rule["signature-version"] != null) signatureVersion = rule["signature-version"].ToString(); string authRegion; if (rule["auth-region"] != null) authRegion = rule["auth-region"].ToString(); else authRegion = Amazon.Util.AWSSDKUtils.DetermineRegion(hostName); if (string.Equals(authRegion, this.SystemName, StringComparison.OrdinalIgnoreCase)) authRegion = null; // v2 doesn't support the 'deprecated' and 'dnsSuffix' property var deprecated = false; string dnsSuffix = null; return new Amazon.RegionEndpoint.Endpoint(hostName, authRegion, signatureVersion, dnsSuffix, deprecated); } JsonData GetEndpointRule(string serviceName) { JsonData rule = null; if (_documentEndpoints.TryGetValue(string.Format(CultureInfo.InvariantCulture, "{0}/{1}", this.SystemName, serviceName), out rule)) return rule; if (_documentEndpoints.TryGetValue(string.Format(CultureInfo.InvariantCulture, "{0}/*", this.SystemName), out rule)) return rule; if (_documentEndpoints.TryGetValue(string.Format(CultureInfo.InvariantCulture, "*/{0}", serviceName), out rule)) return rule; return _documentEndpoints[DEFAULT_RULE]; } // Creates a new RegionEndpoint and stores it in the hash private static RegionEndpoint GetEndpoint(string systemName, string displayName) { RegionEndpoint regionEndpoint = null; lock (hashBySystemName) { if (hashBySystemName.TryGetValue(systemName, out regionEndpoint)) return regionEndpoint; regionEndpoint = new RegionEndpoint(systemName, displayName); hashBySystemName.Add(regionEndpoint.SystemName, regionEndpoint); } return regionEndpoint; } /// <summary> /// Enumerate through all the regions. /// </summary> public static IEnumerable<RegionEndpoint> EnumerableAllRegions { get { if (!RegionEndpoint.loaded) RegionEndpoint.LoadEndpointDefinitions(); lock (hashBySystemName) { return hashBySystemName.Values.ToList(); } } } /// <summary> /// Gets the region based on its system name like "us-west-1" /// </summary> /// <param name="systemName">The system name of the service like "us-west-1"</param> /// <returns></returns> public static RegionEndpoint GetBySystemName(string systemName) { if (!RegionEndpoint.loaded) RegionEndpoint.LoadEndpointDefinitions(); RegionEndpoint region = null; lock(hashBySystemName) { if (!hashBySystemName.TryGetValue(systemName, out region)) { var logger = Amazon.Runtime.Internal.Util.Logger.GetLogger(typeof(RegionEndpoint)); logger.InfoFormat("Region system name {0} was not found in region data bundled with SDK; assuming new region.", systemName); if (systemName.StartsWith("cn-", StringComparison.Ordinal)) return GetEndpoint(systemName, "China (Unknown)"); return GetEndpoint(systemName, "Unknown"); } } return region; } static void LoadEndpointDefinitions() { LoadEndpointDefinitions(AWSConfigs.EndpointDefinition); } public static void LoadEndpointDefinitions(string endpointsPath) { lock (LOCK_OBJECT) { if (RegionEndpoint.loaded) return; _documentEndpoints = new Dictionary<string, JsonData>(); if (string.IsNullOrEmpty(endpointsPath)) { if (TryLoadEndpointDefinitionsFromAssemblyDir()) { RegionEndpoint.loaded = true; return; } LoadEndpointDefinitionsFromEmbeddedResource(); } else if (endpointsPath.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { LoadEndpointDefinitionFromWeb(endpointsPath); } else { LoadEndpointDefinitionFromFilePath(endpointsPath); } RegionEndpoint.loaded = true; } } static void ReadEndpointFile(Stream stream) { using (var reader = new StreamReader(stream)) { var root = JsonMapper.ToObject(reader); var endpoints = root["endpoints"]; foreach (var ruleName in endpoints.PropertyNames) { _documentEndpoints[ruleName] = endpoints[ruleName]; } } } static void LoadEndpointDefinitionsFromEmbeddedResource() { using (var stream = Amazon.Util.Internal.TypeFactory.GetTypeInfo(typeof(RegionEndpoint)).Assembly.GetManifestResourceStream(REGIONS_FILE)) { ReadEndpointFile(stream); } using (var stream = Amazon.Util.Internal.TypeFactory.GetTypeInfo(typeof(RegionEndpoint)).Assembly.GetManifestResourceStream(REGIONS_CUSTOMIZATIONS_FILE)) { ReadEndpointFile(stream); } } static bool TryLoadEndpointDefinitionsFromAssemblyDir() { string endpointsFile; try { var assembly = typeof(Amazon.RegionEndpoint).Assembly; var codeBase = assembly.CodeBase; if (string.IsNullOrEmpty(codeBase)) return false; var uri = new Uri(codeBase); var dirPath = Path.GetDirectoryName(uri.LocalPath); var dirInfo = new DirectoryInfo(dirPath); if (!dirInfo.Exists) return false; var files = dirInfo.GetFiles(REGIONS_FILE, SearchOption.TopDirectoryOnly); if (files.Length != 1) return false; endpointsFile = files[0].FullName; } catch { endpointsFile = null; } if (string.IsNullOrEmpty(endpointsFile)) return false; LoadEndpointDefinitionFromFilePath(endpointsFile); return true; } static void LoadEndpointDefinitionFromFilePath(string path) { if (!System.IO.File.Exists(path)) throw new AmazonServiceException(string.Format(CultureInfo.InvariantCulture, "Local endpoint configuration file {0} override was not found.", path)); using (var stream = File.OpenRead(path)) { ReadEndpointFile(stream); } } static void LoadEndpointDefinitionFromWeb(string url) { int retries = 0; while (retries < MAX_DOWNLOAD_RETRIES) { try { using (var stream = Amazon.Util.AWSSDKUtils.OpenStream(new Uri(url), Proxy)) { ReadEndpointFile(stream); return; } } catch (Exception e) { retries++; if (retries == MAX_DOWNLOAD_RETRIES) throw new AmazonServiceException(string.Format(CultureInfo.InvariantCulture, "Error downloading regions definition file from {0}.", url), e); } int delay = (int)(Math.Pow(4, retries) * 100); delay = Math.Min(delay, 30 * 1000); Util.AWSSDKUtils.Sleep(delay); } } /// <summary> /// This is a testing method and should not be called by production applications. /// </summary> public static void UnloadEndpointDefinitions() { lock (LOCK_OBJECT) { _documentEndpoints.Clear(); RegionEndpoint.loaded = false; } } #endregion internal RegionEndpoint(string systemName, string displayName) { this.SystemName = systemName; this.DisplayName = displayName; } /// <summary> /// Gets the system name of a region. /// </summary> public string SystemName { get; private set; } /// <summary> /// Gets the display name of a region. /// </summary> public string DisplayName { get; private set; } #region IRegionEndpoint public string RegionName { get { return SystemName; } } #endregion public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0} ({1})", this.DisplayName, this.SystemName); } } #endregion } }
459
aws-sdk-net
aws
C#
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ using Amazon.Runtime; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using ThirdParty.Json.LitJson; namespace Amazon.Internal { [Obsolete("This class is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public class RegionEndpointV3 : IRegionEndpoint { private ServiceMap _serviceMap = new ServiceMap(); public string RegionName { get; private set; } public string DisplayName { get; private set; } public string PartitionName { get { return (string)_partitionJsonData["partition"]; } } public string PartitionDnsSuffix { get { return (string)_partitionJsonData["dnsSuffix"]; } } private JsonData _partitionJsonData; private JsonData _servicesJsonData; private bool _servicesLoaded = false; public RegionEndpointV3(string regionName, string displayName, JsonData partition, JsonData services) { RegionName = regionName; DisplayName = displayName; _partitionJsonData = partition; _servicesJsonData = services; } /// <summary> /// Retrieves the endpoint for the given service in the current region /// </summary> /// <param name="serviceName">Name of the service in endpoints.json</param> /// <param name="dualStack">Whether to retrieve the dual-stack variant</param> /// <returns>Matching endpoint from endpoints.json, or a computed endpoint if possible</returns> [Obsolete("Use GetEndpointForService(string serviceName, GetEndpointForServiceOptions options) instead", error: false)] public RegionEndpoint.Endpoint GetEndpointForService(string serviceName, bool dualStack) { return GetEndpointForService(serviceName, new GetEndpointForServiceOptions { DualStack = dualStack }); } /// <summary> /// Retrieves the endpoint for the given service in the current region /// </summary> /// <param name="serviceName">Name of the service in endpoints.json</param> /// <param name="options"> Specify additional requirements on the <see cref="RegionEndpoint.Endpoint"/> to be returned.</param> /// <returns>Matching endpoint from endpoints.json, or a computed endpoint if possible</returns> public RegionEndpoint.Endpoint GetEndpointForService(string serviceName, GetEndpointForServiceOptions options) { var variants = BuildVariantHashSet(options); return GetEndpointForService(serviceName, variants); } /// <summary> /// Retrieves the endpoint for the given service in the current region /// </summary> /// <param name="serviceName">Name of the service in endpoints.json</param> /// <param name="variants">Set of tags describing an endpoint variant</param> /// <returns>Matching endpoint from endpoints.json, or a computed endpoint if possible</returns> public RegionEndpoint.Endpoint GetEndpointForService(string serviceName, HashSet<string> variants) { RegionEndpoint.Endpoint endpointObject = null; // lock on _partitionJsonData because: // a) ParseAllServices() will mutate _partitionJsonData, so it needs to be run inside a critical section. // b) RegionEndpointV3 objects are exclusively built by RegionEndpointProviderV3, which will // constructor inject the _same instance_ of _servicesJsonData and _partitionJsonData into all // RegionEndpointProviderV3. // c) This provides thread-safety if multiple RegionEndpointV3 instances were to be initialized at // the same time: https://github.com/aws/aws-sdk-net/issues/1939 lock (_partitionJsonData) { if (!_servicesLoaded) { ParseAllServices(); _servicesLoaded = true; } if (!_serviceMap.TryGetEndpoint(serviceName, variants, out endpointObject)) { // For all current variants (dual-stack and FIPS) SDKs cannot // fall back to normal endpoints and must raise an error. if (variants?.Count > 0) { throw new AmazonClientException($"Requested endpoint for {serviceName} with variants [{string.Join(", ", variants.ToArray())}] could not be found."); } // Do a fallback of creating an unknown endpoint based on the // current region's hostname template. endpointObject = CreateUnknownEndpoint(serviceName); } } return endpointObject; } private RegionEndpoint.Endpoint CreateUnknownEndpoint(string serviceName) { string template = (string)_partitionJsonData["defaults"]["hostname"]; string dnsSuffix = (string)_partitionJsonData["dnsSuffix"]; string hostname = template.Replace("{service}", serviceName) .Replace("{region}", RegionName) .Replace("{dnsSuffix}", dnsSuffix); return new RegionEndpoint.Endpoint(hostname, null, null, dnsSuffix, deprecated: false); } private void ParseAllServices() { foreach (string serviceName in _servicesJsonData.PropertyNames) { if (_servicesJsonData[serviceName] != null && _servicesJsonData[serviceName].Count > 0) { AddServiceToMap(_servicesJsonData[serviceName], serviceName); } } } private void AddServiceToMap(JsonData service, string serviceName) { var partitionEndpoint = service["partitionEndpoint"] != null ? (string)service["partitionEndpoint"] : ""; var isRegionalized = service["isRegionalized"] != null ? (bool)service["isRegionalized"] : true; var regionKey = RegionName; // Use the partition's default endpoint if the service is not regionalized, like Route53, and there is no // endpoint defined for the this service name. if (!isRegionalized && service["endpoints"][regionKey] == null && !string.IsNullOrEmpty(partitionEndpoint)) { regionKey = partitionEndpoint; } var regionEndpoint = service["endpoints"][regionKey]; var mergedEndpoint = new JsonData(); var variantJsonData = new Dictionary<HashSet<string>, JsonData>(HashSet<string>.CreateSetComparer()); // Create the merged endpoint definitions for both the normal endpoint and variants MergeJsonData(mergedEndpoint, regionEndpoint, variantJsonData); // first prioritizing the service+region object MergeJsonData(mergedEndpoint, service["defaults"], variantJsonData); // then service-level defaults MergeJsonData(mergedEndpoint, _partitionJsonData["defaults"], variantJsonData); // then partition-level defaults // Preserve existing behavior of short circuiting the normal endpoint if there isn't a region-specific entry if (regionEndpoint != null) { AddNormalEndpointToServiceMap(mergedEndpoint, RegionName, serviceName); } AddVariantEndpointsToServiceMap(mergedEndpoint, RegionName, serviceName, variantJsonData); } private static void MergeJsonData(JsonData target, JsonData source, Dictionary<HashSet<string>, JsonData> variants) { if (source == null || target == null) { return; } foreach (var propertyName in source.PropertyNames) { if (propertyName != "variants") { if (target[propertyName] == null) { target[propertyName] = source[propertyName]; } } else // Variants need special handling because they are identified by the "tags" within the { // variant object. First build the key, and then merge the rest of the json properties for a given variant. foreach (JsonData variant in source["variants"]) { var tagsKey = new HashSet<string>(); foreach (JsonData label in variant["tags"]) { tagsKey.Add((string)label); } if (variants.ContainsKey(tagsKey)) { // We've encountered this variant at a lower level in the hierarchy // so only merge properties which are still null foreach (var variantProperty in variant.PropertyNames) { if (variants[tagsKey][variantProperty] == null) { variants[tagsKey][variantProperty] = variant[variantProperty]; } } } else // First time encountering this variant, so merge the entire object { variants[tagsKey] = variant; } } } } } private void AddNormalEndpointToServiceMap(JsonData mergedEndpoint, string regionName, string serviceName) { string template = (string)mergedEndpoint["hostname"]; string dnsSuffix = (string)_partitionJsonData["dnsSuffix"]; string hostname = template.Replace("{service}", serviceName) .Replace("{region}", regionName) .Replace("{dnsSuffix}", dnsSuffix); string authRegion = null; JsonData credentialScope = mergedEndpoint["credentialScope"]; if (credentialScope != null) { authRegion = DetermineAuthRegion(credentialScope); } JsonData deprecatedJson = mergedEndpoint["deprecated"]; var deprecated = deprecatedJson?.IsBoolean == true ? (bool) deprecatedJson : false; var signatureOverride = DetermineSignatureOverride(mergedEndpoint, serviceName); RegionEndpoint.Endpoint endpoint = new RegionEndpoint.Endpoint(hostname, authRegion, signatureOverride, dnsSuffix, deprecated); _serviceMap.Add(serviceName, endpoint); } private void AddVariantEndpointsToServiceMap(JsonData mergedEndpoint, string regionName, string serviceName, Dictionary<HashSet<string>, JsonData> mergedVariants) { string authRegion = null; JsonData credentialScope = mergedEndpoint["credentialScope"]; if (credentialScope != null) { authRegion = DetermineAuthRegion(credentialScope); } JsonData deprecatedJson = mergedEndpoint["deprecated"]; var deprecated = deprecatedJson?.IsBoolean == true ? (bool)deprecatedJson : false; string signatureOverride = DetermineSignatureOverride(mergedEndpoint, serviceName); foreach (var tagsKey in mergedVariants.Keys) { var variantHostnameTemplate = (string)mergedVariants[tagsKey]["hostname"]; if (string.IsNullOrEmpty(variantHostnameTemplate)) { throw new AmazonClientException($"Unable to determine the hostname for {serviceName} with variants [{string.Join(", ", tagsKey.ToArray())}]."); } if (variantHostnameTemplate.Contains("{region}") && string.IsNullOrEmpty(regionName)) { throw new AmazonClientException($"Unable to determine the region for {serviceName} with variants [{string.Join(", ", tagsKey.ToArray())}]."); } var variantDnsSuffix = mergedVariants[tagsKey]["dnsSuffix"] != null ? (string)mergedVariants[tagsKey]["dnsSuffix"] : (string)_partitionJsonData["dnsSuffix"]; if (variantHostnameTemplate.Contains("{dnsSuffix}") && string.IsNullOrEmpty(variantDnsSuffix)) { throw new AmazonClientException($"Unable to determine the dnsSuffix for {serviceName} with variants [{string.Join(", ", tagsKey.ToArray())}]."); } var variantHostname = variantHostnameTemplate.Replace("{service}", serviceName) .Replace("{region}", regionName) .Replace("{dnsSuffix}", variantDnsSuffix); _serviceMap.Add(serviceName, new RegionEndpoint.Endpoint(variantHostname, authRegion, signatureOverride, variantDnsSuffix, deprecated), tagsKey); } } private static string DetermineSignatureOverride(JsonData defaults, string serviceName) { if (string.Equals(serviceName, "s3", StringComparison.OrdinalIgnoreCase)) { bool supportsSigV2 = false; foreach (JsonData element in defaults["signatureVersions"]) { string sig = (string)element; if (string.Equals(sig, "s3", StringComparison.OrdinalIgnoreCase)) { supportsSigV2 = true; break; } } return (supportsSigV2 ? "2" : "4"); } return null; } private static string DetermineAuthRegion(JsonData credentialScope) { string authRegion = null; if (credentialScope["region"] != null) { authRegion = (string)credentialScope["region"]; } return authRegion; } /// <summary> /// Builds the set used to identify a specific endpoint variant /// </summary> /// <param name="dualStack">Whether to use a dualstack (IPv6 enabled) endpoint</param> /// <param name="fips">Whether to use a FIPS-compliant endpoint</param> /// <returns>Set used to identify the combined variant in endpoints.json</returns> private static HashSet<string> BuildVariantHashSet(GetEndpointForServiceOptions options) { options = options ?? new GetEndpointForServiceOptions(); if (!options.DualStack && !options.FIPS) { return null; } var variants = new HashSet<string>(); if (options.DualStack) { variants.Add("dualstack"); } if (options.FIPS) { variants.Add("fips"); } return variants; } class ServiceMap { /// <summary> /// Stores the plain endpoints for each service in the current region /// </summary> private Dictionary<string, RegionEndpoint.Endpoint> _serviceMap = new Dictionary<string, RegionEndpoint.Endpoint>(); /// <summary> /// Stores the variants for each service in the current region, identified by the set of variant tags. /// </summary> private Dictionary<string, Dictionary<HashSet<string>, RegionEndpoint.Endpoint>> _variantMap = new Dictionary<string, Dictionary<HashSet<string>, RegionEndpoint.Endpoint>>(); public bool ContainsKey(string serviceName) { return _serviceMap.ContainsKey(serviceName); } public void Add(string serviceName, RegionEndpoint.Endpoint endpoint, HashSet<string> variants = null) { if (variants == null || variants.Count == 0) { _serviceMap.Add(serviceName, endpoint); } else { if (!_variantMap.ContainsKey(serviceName) || _variantMap[serviceName] == null) { _variantMap.Add(serviceName, new Dictionary<HashSet<string>, RegionEndpoint.Endpoint>(HashSet<string>.CreateSetComparer())); } _variantMap[serviceName].Add(variants, endpoint); } } public bool TryGetEndpoint(string serviceName, HashSet<string> variants, out RegionEndpoint.Endpoint endpoint) { if (variants == null || variants.Count == 0) { return _serviceMap.TryGetValue(serviceName, out endpoint); } else { if (!_variantMap.ContainsKey(serviceName)) { endpoint = default(RegionEndpoint.Endpoint); return false; } else { return _variantMap[serviceName].TryGetValue(variants, out endpoint); } } } } } [Obsolete("This class is obsoleted because as of version 3.7.100 endpoint is resolved using a newer system that uses request level parameters to resolve the endpoint.")] public class RegionEndpointProviderV3 : IRegionEndpointProvider, IDisposable { #if NETSTANDARD private const string ENDPOINT_JSON_RESOURCE = "Core.endpoints.json"; #else private const string ENDPOINT_JSON_RESOURCE = "Amazon.endpoints.json"; #endif private const string ENDPOINT_JSON = "endpoints.json"; private JsonData _root; private Dictionary<string, IRegionEndpoint> _regionEndpointMap = new Dictionary<string, IRegionEndpoint>(); private Dictionary<string, IRegionEndpoint> _nonStandardRegionNameToObjectMap = new Dictionary<string, IRegionEndpoint>(); private ReaderWriterLockSlim _readerWriterLock = new ReaderWriterLockSlim(); public RegionEndpointProviderV3() { using (var stream = GetEndpointJsonSourceStream()) using (StreamReader reader = new StreamReader(stream)) { _root = JsonMapper.ToObject(reader); } } public RegionEndpointProviderV3(JsonData root) { _root = root; } private static Stream GetEndpointJsonSourceStream() { // // If the endpoints.json file has been provided next to the assembly: // string assemblyLocation = typeof(RegionEndpointProviderV3).Assembly.Location; if (!string.IsNullOrEmpty(assemblyLocation)) { string endpointsPath = Path.Combine(Path.GetDirectoryName(assemblyLocation), ENDPOINT_JSON); if (File.Exists(endpointsPath)) { return File.Open(endpointsPath, FileMode.Open, FileAccess.Read); } } // // Default to endpoints.json file provided in the resource manifest: // return Amazon.Util.Internal.TypeFactory.GetTypeInfo(typeof(RegionEndpointProviderV3)).Assembly.GetManifestResourceStream(ENDPOINT_JSON_RESOURCE); } private IEnumerable<IRegionEndpoint> _allRegionEndpoints; public IEnumerable<IRegionEndpoint> AllRegionEndpoints { get { if (_allRegionEndpoints == null) { try { _readerWriterLock.EnterWriteLock(); if (_allRegionEndpoints == null) { JsonData partitions = _root["partitions"]; List<IRegionEndpoint> endpoints = new List<IRegionEndpoint>(); foreach (JsonData partition in partitions) { JsonData regions = partition["regions"]; foreach (string regionName in regions.PropertyNames) { IRegionEndpoint endpoint; if (!_regionEndpointMap.TryGetValue(regionName, out endpoint)) { endpoint = new RegionEndpointV3(regionName, (string)regions[regionName]["description"], partition, partition["services"]); _regionEndpointMap.Add(regionName, endpoint); } endpoints.Add(endpoint); } } _allRegionEndpoints = endpoints; } } finally { if (_readerWriterLock.IsWriteLockHeld) { _readerWriterLock.ExitWriteLock(); } } } return _allRegionEndpoints; } } private object _allRegionRegexLock = new object(); private IEnumerable<string> _allRegionRegex; public IEnumerable<string> AllRegionRegex { get { if (_allRegionRegex == null) { try { _readerWriterLock.EnterWriteLock(); if (_allRegionRegex == null) { JsonData partitions = _root["partitions"]; var allRegionRegex = new List<string>(); foreach (JsonData partition in partitions) { var regionRegex = (string)partition["regionRegex"]; allRegionRegex.Add(regionRegex); } _allRegionRegex = allRegionRegex; } } finally { if (_readerWriterLock.IsWriteLockHeld) { _readerWriterLock.ExitWriteLock(); } } } return _allRegionRegex; } } private static string GetUnknownRegionDescription(string regionName) { if (regionName.StartsWith("cn-", StringComparison.OrdinalIgnoreCase) || regionName.EndsWith("cn-global", StringComparison.OrdinalIgnoreCase)) { return "China (Unknown)"; } else { return "Unknown"; } } private static bool IsRegionInPartition(string regionName, JsonData partition, out string description) { JsonData regionsData = partition["regions"]; string regionPattern = (string)partition["regionRegex"]; // see if the region name is a real region if (regionsData[regionName] != null) { description = (string)regionsData[regionName]["description"]; return true; } // see if the region is global region by concatenating the partition and "-global" to construct the global name // for the partition else if (regionName.Equals(string.Concat((string)partition["partition"], "-global"), StringComparison.OrdinalIgnoreCase)) { description = "Global"; return true; } // no region key in the entry, but it matches the pattern in this partition. // we can try to construct an endpoint based on the heuristics described in endpoints.json else if (new Regex(regionPattern).Match(regionName).Success) { description = GetUnknownRegionDescription(regionName); return true; } else { description = GetUnknownRegionDescription(regionName); return false; } } public IRegionEndpoint GetRegionEndpoint(string regionName) { try { try { _readerWriterLock.EnterReadLock(); IRegionEndpoint endpoint; if (_regionEndpointMap.TryGetValue(regionName, out endpoint)) { return endpoint; } } finally { if (_readerWriterLock.IsReadLockHeld) { _readerWriterLock.ExitReadLock(); } } try { _readerWriterLock.EnterWriteLock(); IRegionEndpoint endpoint; // Check again to see if region is in cache in case another thread got the write lock before and filled the cache. if (_regionEndpointMap.TryGetValue(regionName, out endpoint)) { return endpoint; } JsonData partitions = _root["partitions"]; foreach (JsonData partition in partitions) { string description; if (IsRegionInPartition(regionName, partition, out description)) { endpoint = new RegionEndpointV3(regionName, description, partition, partition["services"]); _regionEndpointMap.Add(regionName, endpoint); return endpoint; } } } finally { if (_readerWriterLock.IsWriteLockHeld) { _readerWriterLock.ExitWriteLock(); } } } catch (Exception) { throw new AmazonClientException("Invalid endpoint.json format."); } return GetNonstandardRegionEndpoint(regionName); } /// <summary> /// This region name is non-standard. Search the whole endpoints.json file to /// determine the partition this region is in. /// </summary> private IRegionEndpoint GetNonstandardRegionEndpoint(string regionName) { try { _readerWriterLock.EnterReadLock(); IRegionEndpoint regionEndpoint; if (_nonStandardRegionNameToObjectMap.TryGetValue(regionName, out regionEndpoint)) { return regionEndpoint; } } finally { if (_readerWriterLock.IsReadLockHeld) { _readerWriterLock.ExitReadLock(); } } try { _readerWriterLock.EnterWriteLock(); IRegionEndpoint regionEndpoint; // Check again to see if region is in cache in case another thread got the write lock before and filled the cache. if (_nonStandardRegionNameToObjectMap.TryGetValue(regionName, out regionEndpoint)) { return regionEndpoint; } // default to "aws" partition JsonData partitionData = _root["partitions"][0]; string regionDescription = GetUnknownRegionDescription(regionName); JsonData servicesData = partitionData["services"]; bool foundContainingPartition = false; const string validRegionRegexStr = @"^[a-zA-Z0-9]([a-zA-Z0-9\-]*[a-zA-Z0-9])?$"; var match = Regex.Match(regionName, validRegionRegexStr, RegexOptions.Compiled); foreach (JsonData partition in _root["partitions"]) { JsonData partitionServices = partition["services"]; foreach (string service in partitionServices.PropertyNames) { if (partitionServices[service] != null && partitionServices[service].Count > 0) { JsonData serviceData = partitionServices[service]; if (serviceData != null && serviceData["endpoints"][regionName] != null) { partitionData = partition; servicesData = partitionServices; foundContainingPartition = true; break; } } } } if (!foundContainingPartition && !match.Success) { throw new ArgumentException("Invalid region endpoint provided"); } regionEndpoint = new RegionEndpointV3(regionName, regionDescription, partitionData, servicesData); _nonStandardRegionNameToObjectMap.Add(regionName, regionEndpoint); return regionEndpoint; } finally { if (_readerWriterLock.IsWriteLockHeld) { _readerWriterLock.ExitWriteLock(); } } } private static JsonData _emptyDictionaryJsonData = JsonMapper.ToObject("{}"); private bool disposedValue; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _readerWriterLock.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } /// <summary> /// Returns the DNS suffix for the given partition, or /// an empty string if a matching partition was not found in endpoints.json /// </summary> /// <param name="partition">partition</param> /// <returns>DNS suffix for the given partition, empty string if a matching partition was not found</returns> public string GetDnsSuffixForPartition(string partition) { foreach (JsonData currentPartition in _root["partitions"]) { if ((string)currentPartition["partition"] == partition) { return (string)currentPartition["dnsSuffix"]; } } return ""; } } }
773
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System.IO; namespace ThirdParty.BouncyCastle.Asn1 { public abstract class Asn1Encodable { public abstract Asn1Object ToAsn1Object(); } }
31
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System; using System.Collections; using ThirdParty.BouncyCastle.Utilities; namespace ThirdParty.BouncyCastle.Asn1 { public class Asn1EncodableVector : IEnumerable { private IList v = Platform.CreateArrayList(); public static Asn1EncodableVector FromEnumerable( IEnumerable e) { Asn1EncodableVector v = new Asn1EncodableVector(); foreach (Asn1Encodable obj in e) { v.Add(obj); } return v; } public Asn1EncodableVector( params Asn1Encodable[] v) { Add(v); } public void Add( params Asn1Encodable[] objs) { foreach (Asn1Encodable obj in objs) { v.Add(obj); } } public void AddOptional( params Asn1Encodable[] objs) { if (objs != null) { foreach (Asn1Encodable obj in objs) { if (obj != null) { v.Add(obj); } } } } public Asn1Encodable this[ int index] { get { return (Asn1Encodable) v[index]; } } [Obsolete("Use 'object[index]' syntax instead")] public Asn1Encodable Get( int index) { return this[index]; } [Obsolete("Use 'Count' property instead")] public int Size { get { return v.Count; } } public int Count { get { return v.Count; } } public IEnumerator GetEnumerator() { return v.GetEnumerator(); } } }
105
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System; using System.Diagnostics; using System.IO; using ThirdParty.BouncyCastle.Asn1.Utilities; using ThirdParty.BouncyCastle.Utilities.IO; namespace ThirdParty.BouncyCastle.Asn1 { /** * a general purpose ASN.1 decoder - note: this class differs from the * others in that it returns null after it has read the last object in * the stream. If an ASN.1 Null is encountered a Der/BER Null object is * returned. */ public class Asn1InputStream : FilterStream { public const int Constructed = 0x20; public const int Integer = 0x02; private readonly int limit; internal static int FindLimit(Stream input) { if (input is MemoryStream) { MemoryStream mem = (MemoryStream)input; return (int)(mem.Length - mem.Position); } return int.MaxValue; } public Asn1InputStream( Stream inputStream) : this(inputStream, FindLimit(inputStream)) { } /** * Create an ASN1InputStream where no DER object will be longer than limit. * * @param input stream containing ASN.1 encoded data. * @param limit maximum size of a DER encoded object. */ public Asn1InputStream( Stream inputStream, int limit) : base(inputStream) { this.limit = limit; } /** * Create an ASN1InputStream based on the input byte array. The length of DER objects in * the stream is automatically limited to the length of the input array. * * @param input array containing ASN.1 encoded data. */ public Asn1InputStream( byte[] input) : this(new MemoryStream(input, false), input.Length) { } /** * build an object given its tag and the number of bytes to construct it from. */ private Asn1Object BuildObject( int tag, int tagNo, int length) { bool isConstructed = (tag & Constructed) != 0; if (isConstructed) { return CreateDerSequence(this); } else { byte[] bytes = new byte[length]; this.Read(bytes, 0, bytes.Length); return CreatePrimitiveDerObject(tagNo, bytes); } } internal Asn1EncodableVector BuildEncodableVector() { Asn1EncodableVector v = new Asn1EncodableVector(); Asn1Object o; while ((o = ReadObject()) != null) { v.Add(o); } return v; } internal virtual Asn1EncodableVector BuildDerEncodableVector( Stream dIn) { return new Asn1InputStream(dIn).BuildEncodableVector(); } internal virtual DerSequence CreateDerSequence( Stream dIn) { return DerSequence.FromVector(BuildDerEncodableVector(dIn)); } public Asn1Object ReadObject() { int tag = ReadByte(); if (tag <= 0) { if (tag == 0) throw new IOException("unexpected end-of-contents marker"); return null; } // // calculate tag number // int tagNo = ReadTagNumber(this, tag); bool isConstructed = (tag & Constructed) != 0; // // calculate length // int length = ReadLength(this, limit); try { return BuildObject(tag, tagNo, length); } catch (ArgumentException e) { throw new Exception("corrupted stream detected", e); } } internal static int ReadTagNumber( Stream s, int tag) { int tagNo = tag & 0x1f; // // with tagged object tag number is bottom 5 bits, or stored at the start of the content // if (tagNo == 0x1f) { tagNo = 0; int b = s.ReadByte(); // X.690-0207 8.1.2.4.2 // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." if ((b & 0x7f) == 0) // Note: -1 will pass { throw new IOException("Corrupted stream - invalid high tag number found"); } while ((b >= 0) && ((b & 0x80) != 0)) { tagNo |= (b & 0x7f); tagNo <<= 7; b = s.ReadByte(); } if (b < 0) throw new EndOfStreamException("EOF found inside tag value."); tagNo |= (b & 0x7f); } return tagNo; } internal static int ReadLength( Stream s, int limit) { int length = s.ReadByte(); if (length < 0) throw new EndOfStreamException("EOF found when length expected"); if (length == 0x80) return -1; // indefinite-length encoding if (length > 127) { int size = length & 0x7f; // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here if (size > 4) throw new IOException("DER length more than 4 bytes: " + size); length = 0; for (int i = 0; i < size; i++) { int next = s.ReadByte(); if (next < 0) throw new EndOfStreamException("EOF found reading length"); length = (length << 8) + next; } if (length < 0) throw new IOException("Corrupted stream - negative length found"); if (length >= limit) // after all we must have read at least 1 byte throw new IOException("Corrupted stream - out of bounds length found"); } return length; } internal static Asn1Object CreatePrimitiveDerObject( int tagNo, byte[] bytes) { switch (tagNo) { case Integer: return new DerInteger(bytes); default: throw new Exception("Unknown primitive tag"); } } } }
263
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System; using System.IO; namespace ThirdParty.BouncyCastle.Asn1 { public abstract class Asn1Object : Asn1Encodable { /// <summary>Create a base ASN.1 object from a byte array.</summary> /// <param name="data">The byte array to parse.</param> /// <returns>The base ASN.1 object represented by the byte array.</returns> /// <exception cref="IOException">If there is a problem parsing the data.</exception> public static Asn1Object FromByteArray( byte[] data) { try { return new Asn1InputStream(data).ReadObject(); } catch (InvalidCastException) { throw new IOException("cannot recognise object in stream"); } } /// <summary>Read a base ASN.1 object from a stream.</summary> /// <param name="inStr">The stream to parse.</param> /// <returns>The base ASN.1 object represented by the byte array.</returns> /// <exception cref="IOException">If there is a problem parsing the data.</exception> public static Asn1Object FromStream( Stream inStr) { try { return new Asn1InputStream(inStr).ReadObject(); } catch (InvalidCastException) { throw new IOException("cannot recognise object in stream"); } } public sealed override Asn1Object ToAsn1Object() { return this; } } }
71
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System; using System.Collections; using System.IO; using ThirdParty.BouncyCastle.Utilities; namespace ThirdParty.BouncyCastle.Asn1 { public abstract class Asn1Sequence : Asn1Object, IEnumerable { private readonly IList seq; protected internal Asn1Sequence( int capacity) { seq = Platform.CreateArrayList(capacity); } public virtual IEnumerator GetEnumerator() { return seq.GetEnumerator(); } [Obsolete("Use GetEnumerator() instead")] public IEnumerator GetObjects() { return GetEnumerator(); } /** * return the object at the sequence position indicated by index. * * @param index the sequence number (starting at zero) of the object * @return the object at the sequence position indicated by index. */ public virtual Asn1Encodable this[int index] { get { return (Asn1Encodable) seq[index]; } } [Obsolete("Use 'object[index]' syntax instead")] public Asn1Encodable GetObjectAt( int index) { return this[index]; } [Obsolete("Use 'Count' property instead")] public int Size { get { return Count; } } public virtual int Count { get { return seq.Count; } } private Asn1Encodable GetCurrent(IEnumerator e) { Asn1Encodable encObj = (Asn1Encodable)e.Current; return encObj; } protected internal void AddObject( Asn1Encodable obj) { seq.Add(obj); } } }
100
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System; using ThirdParty.BouncyCastle.Math; using ThirdParty.BouncyCastle.Utilities; namespace ThirdParty.BouncyCastle.Asn1 { public class DerInteger : Asn1Object { private readonly byte[] bytes; public DerInteger( int value) { bytes = BigInteger.ValueOf(value).ToByteArray(); } public DerInteger( BigInteger value) { if (value == null) throw new ArgumentNullException("value"); bytes = value.ToByteArray(); } public DerInteger( byte[] bytes) { this.bytes = bytes; } public byte[] Bytes { get { return this.bytes; } } public BigInteger Value { get { return new BigInteger(bytes); } } public override string ToString() { return Value.ToString(); } } }
72
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System.Collections; using System.IO; namespace ThirdParty.BouncyCastle.Asn1 { public class DerSequence : Asn1Sequence { public static readonly DerSequence Empty = new DerSequence(); public static DerSequence FromVector( Asn1EncodableVector v) { return v.Count < 1 ? Empty : new DerSequence(v); } /** * create an empty sequence */ public DerSequence() : base(0) { } /** * create a sequence containing one object */ public DerSequence( Asn1Encodable obj) : base(1) { AddObject(obj); } public DerSequence( params Asn1Encodable[] v) : base(v.Length) { foreach (Asn1Encodable ae in v) { AddObject(ae); } } /** * create a sequence containing a vector of objects. */ public DerSequence( Asn1EncodableVector v) : base(v.Count) { foreach (Asn1Encodable ae in v) { AddObject(ae); } } } }
80
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System; using System.IO; namespace ThirdParty.BouncyCastle.Asn1.Utilities { public class FilterStream : Stream { public FilterStream(Stream s) { this.s = s; } public override bool CanRead { get { return s.CanRead; } } public override bool CanSeek { get { return s.CanSeek; } } public override bool CanWrite { get { return s.CanWrite; } } public override long Length { get { return s.Length; } } public override long Position { get { return s.Position; } set { s.Position = value; } } public override void Close() { s.Close(); } public override void Flush() { s.Flush(); } public override long Seek(long offset, SeekOrigin origin) { return s.Seek(offset, origin); } public override void SetLength(long value) { s.SetLength(value); } public override int Read(byte[] buffer, int offset, int count) { return s.Read(buffer, offset, count); } public override int ReadByte() { return s.ReadByte(); } public override void Write(byte[] buffer, int offset, int count) { s.Write(buffer, offset, count); } public override void WriteByte(byte value) { s.WriteByte(value); } protected readonly Stream s; } }
89
aws-sdk-net
aws
C#
using System.Collections.Generic; namespace ThirdParty.BouncyCastle.Utilities { internal abstract class Platform { internal static System.Collections.IList CreateArrayList() { return new List<object>(); } internal static System.Collections.IList CreateArrayList(int capacity) { return new List<object>(capacity); } internal static System.Collections.IList CreateArrayList(System.Collections.ICollection collection) { System.Collections.IList result = new List<object>(collection.Count); foreach (object o in collection) { result.Add(o); } return result; } internal static System.Collections.IList CreateArrayList(System.Collections.IEnumerable collection) { System.Collections.IList result = new List<object>(); foreach (object o in collection) { result.Add(o); } return result; } } }
34
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Text; using ThirdParty.BouncyCastle.Utilities; namespace ThirdParty.BouncyCastle.Math { public class BigInteger { private const long IMASK = 0xffffffffL; private static readonly int[] ZeroMagnitude = new int[0]; private static readonly byte[] ZeroEncoding = new byte[0]; public static readonly BigInteger Zero = new BigInteger(0, ZeroMagnitude, false); public static readonly BigInteger One = createUValueOf(1); public static readonly BigInteger Two = createUValueOf(2); public static readonly BigInteger Three = createUValueOf(3); public static readonly BigInteger Ten = createUValueOf(10); private static readonly Random RandomSource = new Random(); private const int BitsPerByte = 8; private const int BitsPerInt = 32; private const int BytesPerInt = 4; private int sign; // -1 means -ve; +1 means +ve; 0 means 0; private int[] magnitude; // array of ints with [0] being the most significant private int nBitLength = -1; // cache calcBitLength() value private static int GetByteLength( int nBits) { return (nBits + BitsPerByte - 1) / BitsPerByte; } private BigInteger() { } private BigInteger( int signum, int[] mag, bool checkMag) { if (checkMag) { int i = 0; while (i < mag.Length && mag[i] == 0) { ++i; } if (i == mag.Length) { // this.sign = 0; this.magnitude = ZeroMagnitude; } else { this.sign = signum; if (i == 0) { this.magnitude = mag; } else { // strip leading 0 words this.magnitude = new int[mag.Length - i]; Array.Copy(mag, i, this.magnitude, 0, this.magnitude.Length); } } } else { this.sign = signum; this.magnitude = mag; } } public BigInteger( byte[] bytes) : this(bytes, 0, bytes.Length) { } public BigInteger( byte[] bytes, int offset, int length) { if (length == 0) throw new FormatException("Zero length BigInteger"); // TODO Move this processing into MakeMagnitude (provide sign argument) if ((sbyte)bytes[offset] < 0) { this.sign = -1; int end = offset + length; int iBval; // strip leading sign bytes for (iBval = offset; iBval < end && ((sbyte)bytes[iBval] == -1); iBval++) { } if (iBval >= end) { this.magnitude = One.magnitude; } else { int numBytes = end - iBval; byte[] inverse = new byte[numBytes]; int index = 0; while (index < numBytes) { inverse[index++] = (byte)~bytes[iBval++]; } while (inverse[--index] == byte.MaxValue) { inverse[index] = byte.MinValue; } inverse[index]++; this.magnitude = MakeMagnitude(inverse, 0, inverse.Length); } } else { // strip leading zero bytes and return magnitude bytes this.magnitude = MakeMagnitude(bytes, offset, length); this.sign = this.magnitude.Length > 0 ? 1 : 0; } } private static int[] MakeMagnitude( byte[] bytes, int offset, int length) { int end = offset + length; // strip leading zeros int firstSignificant; for (firstSignificant = offset; firstSignificant < end && bytes[firstSignificant] == 0; firstSignificant++) { } if (firstSignificant >= end) { return ZeroMagnitude; } int nInts = (end - firstSignificant + 3) / BytesPerInt; int bCount = (end - firstSignificant) % BytesPerInt; if (bCount == 0) { bCount = BytesPerInt; } if (nInts < 1) { return ZeroMagnitude; } int[] mag = new int[nInts]; int v = 0; int magnitudeIndex = 0; for (int i = firstSignificant; i < end; ++i) { v <<= 8; v |= bytes[i] & 0xff; bCount--; if (bCount <= 0) { mag[magnitudeIndex] = v; magnitudeIndex++; bCount = BytesPerInt; v = 0; } } if (magnitudeIndex < mag.Length) { mag[magnitudeIndex] = v; } return mag; } private static readonly byte[] rndMask = { 255, 127, 63, 31, 15, 7, 3, 1 }; /** * return a = a + b - b preserved. */ private static int[] AddMagnitudes( int[] a, int[] b) { int tI = a.Length - 1; int vI = b.Length - 1; long m = 0; while (vI >= 0) { m += ((long)(uint)a[tI] + (long)(uint)b[vI--]); a[tI--] = (int)m; m = (long)((ulong)m >> 32); } if (m != 0) { while (tI >= 0 && ++a[tI--] == 0) { } } return a; } private BigInteger AddToMagnitude( int[] magToAdd) { int[] big, small; if (this.magnitude.Length < magToAdd.Length) { big = magToAdd; small = this.magnitude; } else { big = this.magnitude; small = magToAdd; } // Conservatively avoid over-allocation when no overflow possible uint limit = uint.MaxValue; if (big.Length == small.Length) limit -= (uint) small[0]; bool possibleOverflow = (uint) big[0] >= limit; int[] bigCopy; if (possibleOverflow) { bigCopy = new int[big.Length + 1]; big.CopyTo(bigCopy, 1); } else { bigCopy = (int[]) big.Clone(); } bigCopy = AddMagnitudes(bigCopy, small); return new BigInteger(this.sign, bigCopy, possibleOverflow); } private int calcBitLength( int indx, int[] mag) { for (;;) { if (indx >= mag.Length) return 0; if (mag[indx] != 0) break; ++indx; } // bit length for everything after the first int int bitLength = 32 * ((mag.Length - indx) - 1); // and determine bitlength of first int int firstMag = mag[indx]; bitLength += BitLen(firstMag); // Check for negative powers of two if (sign < 0 && ((firstMag & -firstMag) == firstMag)) { do { if (++indx >= mag.Length) { --bitLength; break; } } while (mag[indx] == 0); } return bitLength; } public int BitLength { get { if (nBitLength == -1) { nBitLength = sign == 0 ? 0 : calcBitLength(0, magnitude); } return nBitLength; } } // // BitLen(value) is the number of bits in value. // private static int BitLen( int w) { // Binary search - decision tree (5 tests, rarely 6) return (w < 1 << 15 ? (w < 1 << 7 ? (w < 1 << 3 ? (w < 1 << 1 ? (w < 1 << 0 ? (w < 0 ? 32 : 0) : 1) : (w < 1 << 2 ? 2 : 3)) : (w < 1 << 5 ? (w < 1 << 4 ? 4 : 5) : (w < 1 << 6 ? 6 : 7))) : (w < 1 << 11 ? (w < 1 << 9 ? (w < 1 << 8 ? 8 : 9) : (w < 1 << 10 ? 10 : 11)) : (w < 1 << 13 ? (w < 1 << 12 ? 12 : 13) : (w < 1 << 14 ? 14 : 15)))) : (w < 1 << 23 ? (w < 1 << 19 ? (w < 1 << 17 ? (w < 1 << 16 ? 16 : 17) : (w < 1 << 18 ? 18 : 19)) : (w < 1 << 21 ? (w < 1 << 20 ? 20 : 21) : (w < 1 << 22 ? 22 : 23))) : (w < 1 << 27 ? (w < 1 << 25 ? (w < 1 << 24 ? 24 : 25) : (w < 1 << 26 ? 26 : 27)) : (w < 1 << 29 ? (w < 1 << 28 ? 28 : 29) : (w < 1 << 30 ? 30 : 31))))); } public int CompareTo( object obj) { return CompareTo((BigInteger)obj); } /** * unsigned comparison on two arrays - note the arrays may * start with leading zeros. */ private static int CompareTo( int xIndx, int[] x, int yIndx, int[] y) { while (xIndx != x.Length && x[xIndx] == 0) { xIndx++; } while (yIndx != y.Length && y[yIndx] == 0) { yIndx++; } return CompareNoLeadingZeroes(xIndx, x, yIndx, y); } private static int CompareNoLeadingZeroes( int xIndx, int[] x, int yIndx, int[] y) { int diff = (x.Length - y.Length) - (xIndx - yIndx); if (diff != 0) { return diff < 0 ? -1 : 1; } // lengths of magnitudes the same, test the magnitude values while (xIndx < x.Length) { uint v1 = (uint)x[xIndx++]; uint v2 = (uint)y[yIndx++]; if (v1 != v2) return v1 < v2 ? -1 : 1; } return 0; } public int CompareTo( BigInteger value) { return sign < value.sign ? -1 : sign > value.sign ? 1 : sign == 0 ? 0 : sign * CompareNoLeadingZeroes(0, magnitude, 0, value.magnitude); } public override bool Equals( object obj) { if (obj == this) return true; BigInteger biggie = obj as BigInteger; if (biggie == null) return false; if (biggie.sign != sign || biggie.magnitude.Length != magnitude.Length) return false; for (int i = 0; i < magnitude.Length; i++) { if (biggie.magnitude[i] != magnitude[i]) { return false; } } return true; } public override int GetHashCode() { int hc = magnitude.Length; if (magnitude.Length > 0) { hc ^= magnitude[0]; if (magnitude.Length > 1) { hc ^= magnitude[magnitude.Length - 1]; } } return sign < 0 ? ~hc : hc; } // TODO Make public? private BigInteger Inc() { if (this.sign == 0) return One; if (this.sign < 0) return new BigInteger(-1, doSubBigLil(this.magnitude, One.magnitude), true); return AddToMagnitude(One.magnitude); } public BigInteger Negate() { if (sign == 0) return this; return new BigInteger(-sign, magnitude, false); } public BigInteger Not() { return Inc().Negate(); } /** * returns x = x - y - we assume x is >= y */ private static int[] Subtract( int xStart, int[] x, int yStart, int[] y) { int iT = x.Length; int iV = y.Length; long m; int borrow = 0; do { m = (x[--iT] & IMASK) - (y[--iV] & IMASK) + borrow; x[iT] = (int) m; // borrow = (m < 0) ? -1 : 0; borrow = (int)(m >> 63); } while (iV > yStart); if (borrow != 0) { while (--x[--iT] == -1) { } } return x; } private static int[] doSubBigLil( int[] bigMag, int[] lilMag) { int[] res = (int[]) bigMag.Clone(); return Subtract(0, res, 0, lilMag); } public byte[] ToByteArray() { return ToByteArray(false); } public byte[] ToByteArrayUnsigned() { return ToByteArray(true); } private byte[] ToByteArray( bool unsigned) { unchecked { if (sign == 0) return unsigned ? ZeroEncoding : new byte[1]; int nBits = (unsigned && sign > 0) ? BitLength : BitLength + 1; int nBytes = GetByteLength(nBits); byte[] bytes = new byte[nBytes]; int magIndex = magnitude.Length; int bytesIndex = bytes.Length; if (sign > 0) { while (magIndex > 1) { uint mag = (uint) magnitude[--magIndex]; bytes[--bytesIndex] = (byte) mag; bytes[--bytesIndex] = (byte)(mag >> 8); bytes[--bytesIndex] = (byte)(mag >> 16); bytes[--bytesIndex] = (byte)(mag >> 24); } uint lastMag = (uint) magnitude[0]; while (lastMag > byte.MaxValue) { bytes[--bytesIndex] = (byte) lastMag; lastMag >>= 8; } bytes[--bytesIndex] = (byte) lastMag; } else // sign < 0 { bool carry = true; while (magIndex > 1) { uint mag = ~((uint) magnitude[--magIndex]); if (carry) { carry = (++mag == uint.MinValue); } bytes[--bytesIndex] = (byte) mag; bytes[--bytesIndex] = (byte)(mag >> 8); bytes[--bytesIndex] = (byte)(mag >> 16); bytes[--bytesIndex] = (byte)(mag >> 24); } uint lastMag = (uint) magnitude[0]; if (carry) { // Never wraps because magnitude[0] != 0 --lastMag; } while (lastMag > byte.MaxValue) { bytes[--bytesIndex] = (byte) ~lastMag; lastMag >>= 8; } bytes[--bytesIndex] = (byte) ~lastMag; if (bytesIndex > 0) { bytes[--bytesIndex] = byte.MaxValue; } } return bytes; } } private static BigInteger createUValueOf( ulong value) { int msw = (int)(value >> 32); int lsw = (int)value; if (msw != 0) return new BigInteger(1, new int[] { msw, lsw }, false); if (lsw != 0) { BigInteger n = new BigInteger(1, new int[] { lsw }, false); return n; } return Zero; } private static BigInteger createValueOf( long value) { if (value < 0) { if (value == long.MinValue) return createValueOf(~value).Not(); return createValueOf(-value).Negate(); } return createUValueOf((ulong)value); } public static BigInteger ValueOf( long value) { switch (value) { case 0: return Zero; case 1: return One; case 2: return Two; case 3: return Three; case 10: return Ten; } return createValueOf(value); } } }
696
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Text; using System.Security.Cryptography; using ThirdParty.BouncyCastle.Asn1; using ThirdParty.BouncyCastle.Utilities; using ThirdParty.BouncyCastle.Utilities.IO.Pem; namespace ThirdParty.BouncyCastle.OpenSsl { public class PemReader : ThirdParty.BouncyCastle.Utilities.IO.Pem.PemReader { public PemReader( TextReader reader) : base(reader) { } public RSAParameters ReadPrivatekey() { PemObject pemObject = ReadPemObject(); string type = pemObject.Type.Substring(0, pemObject.Type.Length - "PRIVATE KEY".Length).Trim(); byte[] keyBytes = pemObject.Content; Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(keyBytes); if (seq.Count != 9) throw new Exception("malformed sequence in RSA private key"); return convertSequenceToRSAParameters(seq); } RSAParameters convertSequenceToRSAParameters(Asn1Sequence seq) { var rsaParams = new RSAParameters(); var modules = ((DerInteger)seq[1]).Value.ToByteArrayUnsigned(); var alignmentValue = GetAlignmentValue(modules); rsaParams.Modulus = FixAlignment(modules, alignmentValue); rsaParams.Exponent = ((DerInteger)seq[2]).Value.ToByteArrayUnsigned(); rsaParams.D = FixAlignment(((DerInteger)seq[3]).Value.ToByteArrayUnsigned(), alignmentValue); rsaParams.P = FixAlignment(((DerInteger)seq[4]).Value.ToByteArrayUnsigned(), alignmentValue / 2); rsaParams.Q = FixAlignment(((DerInteger)seq[5]).Value.ToByteArrayUnsigned(), alignmentValue / 2); rsaParams.DP = FixAlignment(((DerInteger)seq[6]).Value.ToByteArrayUnsigned(), alignmentValue / 2); rsaParams.DQ = FixAlignment(((DerInteger)seq[7]).Value.ToByteArrayUnsigned(), alignmentValue / 2); rsaParams.InverseQ = FixAlignment(((DerInteger)seq[8]).Value.ToByteArrayUnsigned(), alignmentValue / 2); return rsaParams; } private int GetAlignmentValue(Byte[] modules) { int bits = modules.Length * 8; double logbase = System.Math.Log(bits, 2); if (logbase != (int)logbase) { bits = (int)(logbase + 1.0); bits = (int)(System.Math.Pow(2, bits)); } return bits / 8; } public static byte[] FixAlignment(byte[] inputBytes, int alignment) { if (inputBytes.Length == alignment) return inputBytes; byte[] buf = new byte[alignment]; System.Array.Copy(inputBytes, 0, buf, alignment - inputBytes.Length, inputBytes.Length); return buf; } } }
105
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System; namespace ThirdParty.BouncyCastle.Utilities.IO.Pem { #if !NETSTANDARD [Serializable] #endif public class PemGenerationException : Exception { public PemGenerationException() : base() { } public PemGenerationException( string message) : base(message) { } public PemGenerationException( string message, Exception exception) : base(message, exception) { } } }
51
aws-sdk-net
aws
C#
/* * Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ using System; namespace ThirdParty.BouncyCastle.Utilities.IO.Pem { public class PemHeader { private string name; private string val; public PemHeader(string name, string val) { this.name = name; this.val = val; } public virtual string Name { get { return name; } } public virtual string Value { get { return val; } } public override int GetHashCode() { return GetHashCode(this.name) + 31 * GetHashCode(this.val); } public override bool Equals(object obj) { if (obj == this) return true; if (!(obj is PemHeader)) return false; PemHeader other = (PemHeader)obj; return string.Equals(this.name, other.name) && string.Equals(this.val, other.val); } private int GetHashCode(string s) { if (s == null) { return 1; } return s.GetHashCode(); } } }
77