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# | /*
* 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 System.Text;
using ThirdParty.Json.LitJson;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Runtime.Internal.Transform
{
/// <summary>
/// Wraps a json string for unmarshalling.
///
/// Each <c>Read()</c> operation gets the next token.
/// <c>TestExpression()</c> is used to match the current key-chain
/// to an xpath expression. The general pattern looks like this:
/// <code>
/// JsonUnmarshallerContext context = new JsonUnmarshallerContext(jsonString);
/// while (context.Read())
/// {
/// if (context.IsKey)
/// {
/// if (context.TestExpresion("path/to/element"))
/// {
/// myObject.stringMember = stringUnmarshaller.GetInstance().Unmarshall(context);
/// continue;
/// }
/// }
/// }
/// </code>
/// </summary>
public class JsonUnmarshallerContext : UnmarshallerContext
{
private const string DELIMITER = "/";
#region Private members
private StreamReader streamReader = null;
private JsonReader jsonReader = null;
private JsonPathStack stack = new JsonPathStack();
private string currentField;
private JsonToken? currentToken = null;
private bool disposed = false;
private bool wasPeeked = false;
#endregion
#region Constructors
/// <summary>
/// Wrap the jsonstring for unmarshalling.
/// </summary>
/// <param name="responseStream">Stream that contains the JSON for unmarshalling</param>
/// <param name="maintainResponseBody"> If set to true, maintains a copy of the complete response body constraint to log response size as the stream is being read.</param>
/// <param name="responseData">Response data coming back from the request</param>
/// <param name="isException">If set to true, maintains a copy of the complete response body as the stream is being read.</param>
public JsonUnmarshallerContext(
Stream responseStream,
bool maintainResponseBody,
IWebResponseData responseData,
bool isException = false)
: this(responseStream, maintainResponseBody, responseData, isException, null)
{ }
/// <summary>
/// Wrap the jsonstring for unmarshalling.
/// </summary>
/// <param name="responseStream">Stream that contains the JSON for unmarshalling</param>
/// <param name="maintainResponseBody"> If set to true, maintains a copy of the complete response body constraint to log response size as the stream is being read.</param>
/// <param name="responseData">Response data coming back from the request</param>
/// <param name="isException">If set to true, maintains a copy of the complete response body as the stream is being read.</param>
/// <param name="requestContext">Context for the request that produced this response</param>
public JsonUnmarshallerContext(
Stream responseStream,
bool maintainResponseBody,
IWebResponseData responseData,
bool isException,
IRequestContext requestContext)
{
if (isException)
{
this.WrappingStream = new CachingWrapperStream(responseStream);
}
else if (maintainResponseBody)
{
this.WrappingStream = new CachingWrapperStream(responseStream, AWSConfigs.LoggingConfig.LogResponsesSizeLimit);
}
if (isException || maintainResponseBody)
{
responseStream = this.WrappingStream;
}
this.WebResponseData = responseData;
this.MaintainResponseBody = maintainResponseBody;
this.IsException = isException;
//if the json unmarshaller context is being called internally without there being a http response then the response data would be null
if(responseData != null)
{
long contentLength;
bool parsedContentLengthHeader = long.TryParse(responseData.GetHeaderValue("Content-Length"), out contentLength);
// Temporary work around checking Content-Encoding for an issue with NetStandard on Linux returning Content-Length for a gzipped response.
// Causing the SDK to attempt a CRC check over the gzipped response data with a CRC value for the uncompressed value.
// The Content-Encoding check can be removed with the following github issue is shipped.
// https://github.com/dotnet/corefx/issues/6796
if (parsedContentLengthHeader && responseData.ContentLength.Equals(contentLength) &&
string.IsNullOrEmpty(responseData.GetHeaderValue("Content-Encoding")))
{
base.SetupCRCStream(responseData, responseStream, contentLength);
base.SetupFlexibleChecksumStream(responseData, CrcStream ?? responseStream, contentLength, requestContext);
}
}
if (this.FlexibleChecksumStream != null) // either just flexible checksum, or flexible checksum wrapping the older CRC stream
streamReader = new StreamReader(this.FlexibleChecksumStream);
else if (this.CrcStream != null)
streamReader = new StreamReader(this.CrcStream);
else
streamReader = new StreamReader(responseStream);
jsonReader = new JsonReader(streamReader);
}
#endregion
#region Overrides
/// <summary>
/// Are we at the start of the json document.
/// </summary>
public override bool IsStartOfDocument
{
get
{
return (CurrentTokenType == JsonToken.None) && (!streamReader.EndOfStream);
}
}
/// <summary>
/// Is the current token the end of an object
/// </summary>
public override bool IsEndElement
{
get { return CurrentTokenType == JsonToken.ObjectEnd; }
}
/// <summary>
/// Is the current token the start of an object
/// </summary>
public override bool IsStartElement
{
get { return CurrentTokenType == JsonToken.ObjectStart; }
}
/// <summary>
/// Returns the element depth of the parser's current position in the json
/// document being parsed.
/// </summary>
public override int CurrentDepth
{
get
{
return this.stack.CurrentDepth;
}
}
/// <summary>
/// The current Json path that is being unmarshalled.
/// </summary>
public override string CurrentPath
{
get
{
return this.stack.CurrentPath;
}
}
/// <summary>
/// Reads to the next token in the json document, and updates the context
/// accordingly.
/// </summary>
/// <returns>
/// True if a token was read, false if there are no more tokens to read.
/// </returns>
public override bool Read()
{
if (wasPeeked)
{
wasPeeked = false;
return currentToken == null;
}
bool result = jsonReader.Read();
if (result)
{
currentToken = jsonReader.Token;
UpdateContext();
}
else
{
currentToken = null;
}
wasPeeked = false;
return result;
}
/// <summary>
/// Peeks at the next token. This peek implementation
/// reads the next token and makes the subsequent Read() return the same data.
/// If Peek is called successively, it will return the same data.
/// Only the first one calls Read(), subsequent calls
/// will return the same data until a Read() call is made.
/// </summary>
/// <param name="token">Token to peek.</param>
/// <returns>Returns true if the peeked token matches given token.</returns>
public bool Peek(JsonToken token)
{
if (wasPeeked)
return currentToken != null && currentToken == token;
if (Read())
{
wasPeeked = true;
return currentToken == token;
}
return false;
}
/// <summary>
/// Returns the text contents of the current token being parsed.
/// </summary>
/// <returns>
/// The text contents of the current token being parsed.
/// </returns>
public override string ReadText()
{
object data = jsonReader.Value;
string text;
switch (currentToken)
{
case JsonToken.Null:
text = null;
break;
case JsonToken.String:
case JsonToken.PropertyName:
text = data as string;
break;
case JsonToken.Boolean:
case JsonToken.Int:
case JsonToken.UInt:
case JsonToken.Long:
case JsonToken.ULong:
IFormattable iformattable = data as IFormattable;
if (iformattable != null)
text = iformattable.ToString(null, CultureInfo.InvariantCulture);
else
text = data.ToString();
break;
case JsonToken.Double:
var formattable = data as IFormattable;
if (formattable != null)
text = formattable.ToString("R", CultureInfo.InvariantCulture);
else
text = data.ToString();
break;
default:
throw new AmazonClientException(
"We expected a VALUE token but got: " + currentToken);
}
return text;
}
#endregion
#region Public properties
/// <summary>
/// The type of the current token
/// </summary>
public JsonToken CurrentTokenType
{
get { return currentToken.Value; }
}
#endregion
#region Internal methods/properties
/// <summary>
/// Get the base stream of the jsonStream.
/// </summary>
public Stream Stream
{
get { return streamReader.BaseStream; }
}
/// <summary>
/// Peeks at the next (non-whitespace) character in the jsonStream.
/// </summary>
/// <returns>The next (non-whitespace) character in the jsonStream, or -1 if at the end.</returns>
public int Peek()
{
// Per MSDN documentation on StreamReader.Peek(), it's perfectly acceptable to cast
// int returned by Peek() to char.
unchecked
{
while (Char.IsWhiteSpace((char) StreamPeek()))
{
streamReader.Read();
}
}
return StreamPeek();
}
#endregion
#region Private methods
/// <summary>
/// Peeks at the next character in the stream.
/// If the data isn't buffered into the StreamReader (Peek() returns -1),
/// we flush the buffered data and try one more time.
/// </summary>
/// <returns></returns>
private int StreamPeek()
{
int peek = streamReader.Peek();
if (peek == -1)
{
streamReader.DiscardBufferedData();
peek = streamReader.Peek();
}
return peek;
}
private void UpdateContext()
{
if (!currentToken.HasValue) return;
if (currentToken.Value == JsonToken.ObjectStart || currentToken.Value == JsonToken.ArrayStart)
{
// Push '/' for object start and array start.
stack.Push(new PathSegment
{
SegmentType = PathSegmentType.Delimiter,
Value = DELIMITER
});
}
else if (currentToken.Value == JsonToken.ObjectEnd || currentToken.Value == JsonToken.ArrayEnd)
{
if (stack.Peek().SegmentType == PathSegmentType.Delimiter)
{
// Pop '/' associated with corresponding object start and array start.
stack.Pop();
if (stack.Count > 0 && stack.Peek().SegmentType != PathSegmentType.Delimiter)
{
// Pop the property name associated with the
// object or array if present.
// e.g. {"a":["1","2","3"]}
stack.Pop();
}
}
currentField = null;
}
else if (currentToken.Value == JsonToken.PropertyName)
{
string t = ReadText();
// Push property name, it's appended to the stack's CurrentPath,
// it this does not affect the depth.
stack.Push(new PathSegment
{
SegmentType = PathSegmentType.Value,
Value = t
});
}
else if (currentToken.Value != JsonToken.None && stack.Peek().SegmentType != PathSegmentType.Delimiter)
{
// Pop if you encounter a simple data type or null
// This will pop the property name associated with it in cases like {"a":"b"}.
// Exclude the case where it's a value in an array so we dont end poping the start of array and
// property name e.g. {"a":["1","2","3"]}
stack.Pop();
}
}
#endregion
public JsonData ToJsonData()
{
var data = JsonMapper.ToObject(jsonReader);
if (stack.Count > 0)
stack.Pop();
return data;
}
protected override void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (streamReader != null)
{
streamReader.Dispose();
streamReader = null;
}
}
disposed = true;
}
base.Dispose(disposing);
}
private enum PathSegmentType
{
Value,
Delimiter
}
private struct PathSegment
{
internal PathSegmentType SegmentType { get; set; }
internal string Value { get; set; }
}
private class JsonPathStack
{
private Stack<PathSegment> stack = new Stack<PathSegment>();
int currentDepth = 0;
private StringBuilder stackStringBuilder = new StringBuilder(128);
private string stackString;
public int CurrentDepth
{
get { return this.currentDepth; }
}
public string CurrentPath
{
get
{
if (this.stackString == null)
this.stackString = this.stackStringBuilder.ToString();
return this.stackString;
}
}
internal void Push(PathSegment segment)
{
if (segment.SegmentType == PathSegmentType.Delimiter)
{
currentDepth++;
}
stackStringBuilder.Append(segment.Value);
stackString = null;
stack.Push(segment);
}
internal PathSegment Pop()
{
var segment = this.stack.Pop();
if (segment.SegmentType == PathSegmentType.Delimiter)
{
currentDepth--;
}
stackStringBuilder.Remove(stackStringBuilder.Length - segment.Value.Length, segment.Value.Length);
stackString = null;
return segment;
}
internal PathSegment Peek()
{
return this.stack.Peek();
}
public int Count
{
get { return this.stack.Count; }
}
}
}
}
| 507 |
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;
using System.Net;
using System.Xml;
using System.IO;
using Amazon.Util;
using Amazon.Runtime.Internal.Util;
using System.Globalization;
namespace Amazon.Runtime.Internal.Transform
{
/// <summary>
/// Abstract class for unmarshalling service responses.
/// </summary>
public abstract class ResponseUnmarshaller : IResponseUnmarshaller<AmazonWebServiceResponse, UnmarshallerContext>
{
public virtual UnmarshallerContext CreateContext(IWebResponseData response, bool readEntireResponse, Stream stream, RequestMetrics metrics, bool isException)
{
return CreateContext(response, readEntireResponse, stream, metrics, isException, null);
}
public virtual UnmarshallerContext CreateContext(IWebResponseData response, bool readEntireResponse, Stream stream, RequestMetrics metrics, bool isException, IRequestContext requestContext)
{
if (response == null)
{
throw new AmazonServiceException("The Web Response for a successful request is null!");
}
UnmarshallerContext context;
// If the request is using the flexible checksum feature to verify a response checksum,
// then both the service package and core will support the ConstructUnmarshallerContext
// override with 5 parameters
if (requestContext?.OriginalRequest?.CoreChecksumMode != CoreChecksumResponseBehavior.DISABLED)
{
context = ConstructUnmarshallerContext(stream,
ShouldReadEntireResponse(response, readEntireResponse),
response,
isException,
requestContext);
}
else // Otherwise it's okay to skip passing in requestContext, because
// it's only currently used when validating a response checksum. This will also
// preserve existing behavior for a core package version with flexible checksum
// support alongside an older service package version.
{
context = ConstructUnmarshallerContext(stream,
ShouldReadEntireResponse(response, readEntireResponse),
response,
isException);
}
return context;
}
public virtual bool HasStreamingProperty
{
get { return false; }
}
#region IResponseUnmarshaller<AmazonWebServiceResponse,UnmarshallerContext> Members
public virtual AmazonServiceException UnmarshallException(UnmarshallerContext input, Exception innerException, HttpStatusCode statusCode)
{
throw new NotImplementedException();
}
#endregion
public AmazonWebServiceResponse UnmarshallResponse(UnmarshallerContext context)
{
var response = this.Unmarshall(context);
response.ContentLength = context.ResponseData.ContentLength;
response.HttpStatusCode = context.ResponseData.StatusCode;
return response;
}
#region IUnmarshaller<AmazonWebServiceResponse,UnmarshallerContext> Members
public abstract AmazonWebServiceResponse Unmarshall(UnmarshallerContext input);
#endregion
public static string GetDefaultErrorMessage<T>() where T : Exception
{
return string.Format(CultureInfo.InvariantCulture, "An exception of type {0}, please check the error log for mode details.", typeof(T).Name);
}
protected abstract UnmarshallerContext ConstructUnmarshallerContext(
Stream responseStream, bool maintainResponseBody, IWebResponseData response, bool isException);
protected abstract UnmarshallerContext ConstructUnmarshallerContext(
Stream responseStream, bool maintainResponseBody, IWebResponseData response, bool isException, IRequestContext requestContext);
protected virtual bool ShouldReadEntireResponse(IWebResponseData response, bool readEntireResponse)
{
return readEntireResponse;
}
}
/// <summary>
/// Class for unmarshalling XML service responses.
/// </summary>
public abstract class XmlResponseUnmarshaller : ResponseUnmarshaller
{
public override AmazonWebServiceResponse Unmarshall(UnmarshallerContext input)
{
XmlUnmarshallerContext context = input as XmlUnmarshallerContext;
if (context == null)
throw new InvalidOperationException("Unsupported UnmarshallerContext");
AmazonWebServiceResponse response = this.Unmarshall(context);
if (context.ResponseData.IsHeaderPresent(HeaderKeys.RequestIdHeader) &&
!string.IsNullOrEmpty(context.ResponseData.GetHeaderValue(HeaderKeys.RequestIdHeader)))
{
if (response.ResponseMetadata == null)
response.ResponseMetadata = new ResponseMetadata();
response.ResponseMetadata.RequestId = context.ResponseData.GetHeaderValue(HeaderKeys.RequestIdHeader);
}
else if (context.ResponseData.IsHeaderPresent(HeaderKeys.XAmzRequestIdHeader) &&
!string.IsNullOrEmpty(context.ResponseData.GetHeaderValue(HeaderKeys.XAmzRequestIdHeader)))
{
if (response.ResponseMetadata == null)
response.ResponseMetadata = new ResponseMetadata();
response.ResponseMetadata.RequestId = context.ResponseData.GetHeaderValue(HeaderKeys.XAmzRequestIdHeader);
}
return response;
}
public override AmazonServiceException UnmarshallException(UnmarshallerContext input, Exception innerException, HttpStatusCode statusCode)
{
XmlUnmarshallerContext context = input as XmlUnmarshallerContext;
if (context == null)
throw new InvalidOperationException("Unsupported UnmarshallerContext");
return this.UnmarshallException(context, innerException, statusCode);
}
public abstract AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext input);
public abstract AmazonServiceException UnmarshallException(XmlUnmarshallerContext input, Exception innerException, HttpStatusCode statusCode);
protected override UnmarshallerContext ConstructUnmarshallerContext(Stream responseStream, bool maintainResponseBody, IWebResponseData response, bool isException)
{
return new XmlUnmarshallerContext(responseStream, maintainResponseBody, response, isException, null);
}
protected override UnmarshallerContext ConstructUnmarshallerContext(Stream responseStream, bool maintainResponseBody, IWebResponseData response, bool isException, IRequestContext requestContext)
{
return new XmlUnmarshallerContext(responseStream, maintainResponseBody, response, isException, requestContext);
}
}
/// <summary>
/// Class for unmarshalling EC2 service responses.
/// </summary>
public abstract class EC2ResponseUnmarshaller : XmlResponseUnmarshaller
{
public override AmazonWebServiceResponse Unmarshall(UnmarshallerContext input)
{
// Unmarshall response
var response = base.Unmarshall(input);
// Make sure ResponseMetadata is set
if (response.ResponseMetadata == null)
response.ResponseMetadata = new ResponseMetadata();
// Populate RequestId
var ec2UnmarshallerContext = input as EC2UnmarshallerContext;
if (ec2UnmarshallerContext != null && !string.IsNullOrEmpty(ec2UnmarshallerContext.RequestId))
{
response.ResponseMetadata.RequestId = ec2UnmarshallerContext.RequestId;
}
return response;
}
protected override UnmarshallerContext ConstructUnmarshallerContext(Stream responseStream, bool maintainResponseBody, IWebResponseData response, bool isException)
{
return new EC2UnmarshallerContext(responseStream, maintainResponseBody, response, isException, null);
}
protected override UnmarshallerContext ConstructUnmarshallerContext(Stream responseStream, bool maintainResponseBody, IWebResponseData response, bool isException, IRequestContext requestContext)
{
return new EC2UnmarshallerContext(responseStream, maintainResponseBody, response, isException, requestContext);
}
}
/// <summary>
/// Class for unmarshalling JSON service responses.
/// </summary>
public abstract class JsonResponseUnmarshaller : ResponseUnmarshaller
{
public override AmazonWebServiceResponse Unmarshall(UnmarshallerContext input)
{
JsonUnmarshallerContext context = input as JsonUnmarshallerContext;
if (context == null)
throw new InvalidOperationException("Unsupported UnmarshallerContext");
string requestId = context.ResponseData.GetHeaderValue(HeaderKeys.RequestIdHeader);
try
{
var response = this.Unmarshall(context);
response.ResponseMetadata = new ResponseMetadata();
response.ResponseMetadata.RequestId = requestId;
return response;
}
catch (Exception e)
{
throw new AmazonUnmarshallingException(requestId, context.CurrentPath, e, context.ResponseData.StatusCode);
}
}
public override AmazonServiceException UnmarshallException(UnmarshallerContext input, Exception innerException, HttpStatusCode statusCode)
{
JsonUnmarshallerContext context = input as JsonUnmarshallerContext;
if (context == null)
throw new InvalidOperationException("Unsupported UnmarshallerContext");
var responseException = this.UnmarshallException(context, innerException, statusCode);
responseException.RequestId = context.ResponseData.GetHeaderValue(HeaderKeys.RequestIdHeader);
return responseException;
}
public abstract AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext input);
public abstract AmazonServiceException UnmarshallException(JsonUnmarshallerContext input, Exception innerException, HttpStatusCode statusCode);
protected override UnmarshallerContext ConstructUnmarshallerContext(Stream responseStream, bool maintainResponseBody, IWebResponseData response, bool isException)
{
return new JsonUnmarshallerContext(responseStream, maintainResponseBody, response, isException, null);
}
protected override UnmarshallerContext ConstructUnmarshallerContext(Stream responseStream, bool maintainResponseBody, IWebResponseData response, bool isException, IRequestContext requestContext)
{
return new JsonUnmarshallerContext(responseStream, maintainResponseBody, response, isException, requestContext);
}
protected override bool ShouldReadEntireResponse(IWebResponseData response, bool readEntireResponse)
{
return readEntireResponse && response.ContentType != "application/octet-stream";
}
}
}
| 261 |
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;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Internal.Transform
{
static class SimpleTypeUnmarshaller<T>
{
public static T Unmarshall(XmlUnmarshallerContext context)
{
string text = context.ReadText();
return (T)Convert.ChangeType(text, typeof(T), CultureInfo.InvariantCulture);
}
public static T Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
string text = context.ReadText();
if (text == null)
return default(T);
return (T)Convert.ChangeType(text, typeof(T), CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Unmarshaller for int fields
/// </summary>
public class IntUnmarshaller : IUnmarshaller<int, XmlUnmarshallerContext>, IUnmarshaller<int, JsonUnmarshallerContext>
{
private IntUnmarshaller() { }
private static IntUnmarshaller _instance = new IntUnmarshaller();
public static IntUnmarshaller Instance
{
get
{
return _instance;
}
}
public static IntUnmarshaller GetInstance()
{
return IntUnmarshaller.Instance;
}
public int Unmarshall(XmlUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<int>.Unmarshall(context);
}
public int Unmarshall(JsonUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<int>.Unmarshall(context);
}
}
/// <summary>
/// Unmarshaller for nullable int fields. Implemented only for JSON context
/// to handle cases where value can be null e.g. {'Priority': null}.
/// This unmarshaller is not implemented for XML context, as XML responses
/// will null elements (xsi:nil='true') will be skipped by the XML parser.
/// </summary>
public class NullableIntUnmarshaller : IUnmarshaller<int?, JsonUnmarshallerContext>
{
private NullableIntUnmarshaller() { }
private static NullableIntUnmarshaller _instance = new NullableIntUnmarshaller();
public static NullableIntUnmarshaller Instance
{
get
{
return _instance;
}
}
public static NullableIntUnmarshaller GetInstance()
{
return NullableIntUnmarshaller.Instance;
}
public int? Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
string text = context.ReadText();
if (text == null)
{
return null;
}
return int.Parse(text, CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Unmarshaller for long fields
/// </summary>
public class LongUnmarshaller : IUnmarshaller<long, XmlUnmarshallerContext>, IUnmarshaller<long, JsonUnmarshallerContext>
{
private LongUnmarshaller() { }
private static LongUnmarshaller _instance = new LongUnmarshaller();
public static LongUnmarshaller Instance
{
get
{
return _instance;
}
}
public static LongUnmarshaller GetInstance()
{
return LongUnmarshaller.Instance;
}
public long Unmarshall(XmlUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<long>.Unmarshall(context);
}
public long Unmarshall(JsonUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<long>.Unmarshall(context);
}
}
/// <summary>
/// Unmarshaller for float fields
/// </summary>
public class FloatUnmarshaller : IUnmarshaller<float, XmlUnmarshallerContext>, IUnmarshaller<float, JsonUnmarshallerContext>
{
private FloatUnmarshaller() { }
private static FloatUnmarshaller _instance = new FloatUnmarshaller();
public static FloatUnmarshaller Instance
{
get
{
return _instance;
}
}
public static FloatUnmarshaller GetInstance()
{
return FloatUnmarshaller.Instance;
}
public float Unmarshall(XmlUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<float>.Unmarshall(context);
}
public float Unmarshall(JsonUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<float>.Unmarshall(context);
}
}
/// <summary>
/// Unmarshaller for double fields
/// </summary>
public class DoubleUnmarshaller : IUnmarshaller<double, XmlUnmarshallerContext>, IUnmarshaller<double, JsonUnmarshallerContext>
{
private DoubleUnmarshaller() { }
private static DoubleUnmarshaller _instance = new DoubleUnmarshaller();
public static DoubleUnmarshaller Instance
{
get
{
return _instance;
}
}
public static DoubleUnmarshaller GetInstance()
{
return DoubleUnmarshaller.Instance;
}
public double Unmarshall(XmlUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<double>.Unmarshall(context);
}
public double Unmarshall(JsonUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<double>.Unmarshall(context);
}
}
/// <summary>
/// Unmarshaller for decimal fields
/// </summary>
public class DecimalUnmarshaller : IUnmarshaller<decimal, XmlUnmarshallerContext>, IUnmarshaller<decimal, JsonUnmarshallerContext>
{
private DecimalUnmarshaller() { }
private static DecimalUnmarshaller _instance = new DecimalUnmarshaller();
public static DecimalUnmarshaller Instance
{
get
{
return _instance;
}
}
public static DecimalUnmarshaller GetInstance()
{
return DecimalUnmarshaller.Instance;
}
public decimal Unmarshall(XmlUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<decimal>.Unmarshall(context);
}
public decimal Unmarshall(JsonUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<decimal>.Unmarshall(context);
}
}
/// <summary>
/// Unmarshaller for bool fields
/// </summary>
public class BoolUnmarshaller : IUnmarshaller<bool, XmlUnmarshallerContext>, IUnmarshaller<bool, JsonUnmarshallerContext>
{
private BoolUnmarshaller() { }
private static BoolUnmarshaller _instance = new BoolUnmarshaller();
public static BoolUnmarshaller Instance
{
get
{
return _instance;
}
}
public static BoolUnmarshaller GetInstance()
{
return BoolUnmarshaller.Instance;
}
public bool Unmarshall(XmlUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<bool>.Unmarshall(context);
}
public bool Unmarshall(JsonUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<bool>.Unmarshall(context);
}
}
/// <summary>
/// Unmarshaller for string fields
/// </summary>
public class StringUnmarshaller : IUnmarshaller<string, XmlUnmarshallerContext>, IUnmarshaller<string, JsonUnmarshallerContext>
{
private StringUnmarshaller() { }
private static StringUnmarshaller _instance = new StringUnmarshaller();
public static StringUnmarshaller Instance
{
get
{
return _instance;
}
}
public static StringUnmarshaller GetInstance()
{
return StringUnmarshaller.Instance;
}
public string Unmarshall(XmlUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<string>.Unmarshall(context);
}
public string Unmarshall(JsonUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<string>.Unmarshall(context);
}
}
/// <summary>
/// Unmarshaller for byte fields
/// </summary>
public class ByteUnmarshaller : IUnmarshaller<byte, XmlUnmarshallerContext>, IUnmarshaller<byte, JsonUnmarshallerContext>
{
private ByteUnmarshaller() { }
private static ByteUnmarshaller _instance = new ByteUnmarshaller();
public static ByteUnmarshaller Instance
{
get
{
return _instance;
}
}
public static ByteUnmarshaller GetInstance()
{
return ByteUnmarshaller.Instance;
}
public byte Unmarshall(XmlUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<byte>.Unmarshall(context);
}
public byte Unmarshall(JsonUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<byte>.Unmarshall(context);
}
}
/// <summary>
/// Unmarshaller for DateTime fields
/// </summary>
public class DateTimeUnmarshaller : IUnmarshaller<DateTime, XmlUnmarshallerContext>, IUnmarshaller<DateTime, JsonUnmarshallerContext>
{
private DateTimeUnmarshaller() { }
private static DateTimeUnmarshaller _instance = new DateTimeUnmarshaller();
public static DateTimeUnmarshaller Instance
{
get
{
return _instance;
}
}
public static DateTimeUnmarshaller GetInstance()
{
return DateTimeUnmarshaller.Instance;
}
public DateTime Unmarshall(XmlUnmarshallerContext context)
{
string text = context.ReadText();
return UnmarshallInternal(text, treatAsNullable: false).Value;
}
public DateTime Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
string text = context.ReadText();
return UnmarshallInternal(text, treatAsNullable: false).Value;
}
/// <summary>
/// Unmarshalls given string as a DateTime. Handles cases where we want to unmarshall
/// as just a DateTime or a nullable Datetime.
/// </summary>
/// <param name="text">Value to be parsed</param>
/// <param name="treatAsNullable">If true, the method will return null if text is null.
/// If false, the method will return default(DateTime), if text is null.</param>
/// <returns></returns>
internal static DateTime? UnmarshallInternal(string text, bool treatAsNullable)
{
Double seconds;
if (Double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out seconds))
{
return AWSSDKUtils.EPOCH_START.AddSeconds(seconds);
}
else
{
if (text == null)
{
if (treatAsNullable) { return null; }
else { return default(DateTime); }
}
return DateTime.Parse(text, CultureInfo.InvariantCulture);
}
}
}
/// <summary>
/// Unmarshaller for nullable DateTime fields. Implemented only for JSON context
/// to handle cases where value can be null e.g. {'Priority': null}.
/// This unmarshaller is not implemented for XML context, as XML responses
/// will null elements (xsi:nil='true') will be skipped by the XML parser.
/// </summary>
public class NullableDateTimeUnmarshaller : IUnmarshaller<DateTime?, JsonUnmarshallerContext>
{
private NullableDateTimeUnmarshaller() { }
private static NullableDateTimeUnmarshaller _instance = new NullableDateTimeUnmarshaller();
public static NullableDateTimeUnmarshaller Instance
{
get
{
return _instance;
}
}
public static NullableDateTimeUnmarshaller GetInstance()
{
return NullableDateTimeUnmarshaller.Instance;
}
public DateTime? Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
string text = context.ReadText();
return DateTimeUnmarshaller.UnmarshallInternal(text, treatAsNullable: true);
}
}
public class DateTimeEpochLongMillisecondsUnmarshaller : IUnmarshaller<DateTime, XmlUnmarshallerContext>, IUnmarshaller<DateTime, JsonUnmarshallerContext>
{
private DateTimeEpochLongMillisecondsUnmarshaller() { }
private static DateTimeEpochLongMillisecondsUnmarshaller _instance = new DateTimeEpochLongMillisecondsUnmarshaller();
public static DateTimeEpochLongMillisecondsUnmarshaller Instance
{
get
{
return _instance;
}
}
public static DateTimeEpochLongMillisecondsUnmarshaller GetInstance()
{
return DateTimeEpochLongMillisecondsUnmarshaller.Instance;
}
public DateTime Unmarshall(XmlUnmarshallerContext context)
{
return SimpleTypeUnmarshaller<DateTime>.Unmarshall(context);
}
public DateTime Unmarshall(JsonUnmarshallerContext context)
{
long millseconds = LongUnmarshaller.Instance.Unmarshall(context);
var ret = Amazon.Util.AWSSDKUtils.EPOCH_START.AddMilliseconds(millseconds);
return ret;
}
}
/// <summary>
/// Unmarshaller for MemoryStream fields
/// </summary>
public class MemoryStreamUnmarshaller : IUnmarshaller<MemoryStream, XmlUnmarshallerContext>, IUnmarshaller<MemoryStream, JsonUnmarshallerContext>
{
private MemoryStreamUnmarshaller() { }
private static MemoryStreamUnmarshaller _instance = new MemoryStreamUnmarshaller();
public static MemoryStreamUnmarshaller Instance
{
get
{
return _instance;
}
}
public static MemoryStreamUnmarshaller GetInstance()
{
return MemoryStreamUnmarshaller.Instance;
}
public MemoryStream Unmarshall(XmlUnmarshallerContext context)
{
byte[] bytes = Convert.FromBase64String(context.ReadText());
MemoryStream stream = new MemoryStream(bytes);
return stream;
}
public MemoryStream Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
byte[] bytes = Convert.FromBase64String(context.ReadText());
MemoryStream stream = new MemoryStream(bytes);
return stream;
}
}
/// <summary>
/// Unmarshaller for ResponseMetadata
/// </summary>
public class ResponseMetadataUnmarshaller : IUnmarshaller<ResponseMetadata, XmlUnmarshallerContext>, IUnmarshaller<ResponseMetadata, JsonUnmarshallerContext>
{
private ResponseMetadataUnmarshaller() { }
private static ResponseMetadataUnmarshaller _instance = new ResponseMetadataUnmarshaller();
public static ResponseMetadataUnmarshaller Instance
{
get
{
return _instance;
}
}
public static ResponseMetadataUnmarshaller GetInstance()
{
return ResponseMetadataUnmarshaller.Instance;
}
public ResponseMetadata Unmarshall(XmlUnmarshallerContext context)
{
ResponseMetadata metadata = new ResponseMetadata();
int depth = context.CurrentDepth;
while (depth <= context.CurrentDepth)
{
context.Read();
if (context.IsStartElement)
{
if (context.TestExpression("ResponseMetadata/RequestId"))
metadata.RequestId = StringUnmarshaller.GetInstance().Unmarshall(context);
else
metadata.Metadata.Add(context.CurrentPath.Substring(context.CurrentPath.LastIndexOf('/') + 1), StringUnmarshaller.GetInstance().Unmarshall(context));
}
}
return metadata;
}
public ResponseMetadata Unmarshall(JsonUnmarshallerContext context)
{
ResponseMetadata metadata = new ResponseMetadata();
int depth = context.CurrentDepth;
while (context.CurrentDepth >= depth)
{
context.Read();
if (context.TestExpression("ResponseMetadata/RequestId"))
{
metadata.RequestId = StringUnmarshaller.GetInstance().Unmarshall(context);
}
}
return metadata;
}
}
public class KeyValueUnmarshaller<K, V, KUnmarshaller, VUnmarshaller> :
IUnmarshaller<KeyValuePair<K, V>, XmlUnmarshallerContext>,
IUnmarshaller<KeyValuePair<K, V>, JsonUnmarshallerContext>
where KUnmarshaller : IUnmarshaller<K, XmlUnmarshallerContext>, IUnmarshaller<K, JsonUnmarshallerContext>
where VUnmarshaller : IUnmarshaller<V, XmlUnmarshallerContext>, IUnmarshaller<V, JsonUnmarshallerContext>
{
private KUnmarshaller keyUnmarshaller;
private VUnmarshaller valueUnmarshaller;
public KeyValueUnmarshaller(KUnmarshaller keyUnmarshaller, VUnmarshaller valueUnmarshaller)
{
this.keyUnmarshaller = keyUnmarshaller;
this.valueUnmarshaller = valueUnmarshaller;
}
public KeyValuePair<K, V> Unmarshall(XmlUnmarshallerContext context)
{
K key = default(K);
V value = default(V);
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
while (context.Read())
{
if (context.TestExpression("key", targetDepth))
{
key = this.keyUnmarshaller.Unmarshall(context);
}
else if (context.TestExpression("name", targetDepth))
{
key = this.keyUnmarshaller.Unmarshall(context);
}
else if (context.TestExpression("value", targetDepth))
{
value = this.valueUnmarshaller.Unmarshall(context);
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
break;
}
}
return new KeyValuePair<K, V>(key, value);
}
public KeyValuePair<K, V> Unmarshall(JsonUnmarshallerContext context)
{
K key = this.keyUnmarshaller.Unmarshall(context);
V value = this.valueUnmarshaller.Unmarshall(context);
return new KeyValuePair<K, V>(key, value);
}
}
public class ListUnmarshaller<I, IUnmarshaller> : IUnmarshaller<List<I>, XmlUnmarshallerContext>, IUnmarshaller<List<I>, JsonUnmarshallerContext>
where IUnmarshaller : IUnmarshaller<I, XmlUnmarshallerContext>, IUnmarshaller<I, JsonUnmarshallerContext>
{
private IUnmarshaller iUnmarshaller;
public ListUnmarshaller(IUnmarshaller iUnmarshaller)
{
this.iUnmarshaller = iUnmarshaller;
}
public List<I> Unmarshall(XmlUnmarshallerContext context)
{
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
var list = new List<I>();
while (context.Read())
{
if (context.IsStartElement)
{
if (context.TestExpression("member", targetDepth))
{
var item = iUnmarshaller.Unmarshall(context);
list.Add(item);
}
}
}
return list;
}
public List<I> Unmarshall(JsonUnmarshallerContext context)
{
context.Read(); // Read [ or null
if (context.CurrentTokenType == JsonToken.Null)
return new List<I>();
// If a list is present in the response, use AlwaysSendList,
// so if the response was empty, reusing the object in the request we will
// end up sending the same empty collection back.
List<I> list = new AlwaysSendList<I>();
while (!context.Peek(JsonToken.ArrayEnd)) // Peek for ]
{
list.Add(iUnmarshaller.Unmarshall(context));
}
context.Read(); // Read ]
return list;
}
}
public class DictionaryUnmarshaller<TKey, TValue, TKeyUnmarshaller, TValueUnmarshaller> : IUnmarshaller<Dictionary<TKey, TValue>, XmlUnmarshallerContext>, IUnmarshaller<Dictionary<TKey, TValue>, JsonUnmarshallerContext>
where TKeyUnmarshaller : IUnmarshaller<TKey, XmlUnmarshallerContext>, IUnmarshaller<TKey, JsonUnmarshallerContext>
where TValueUnmarshaller : IUnmarshaller<TValue, XmlUnmarshallerContext>, IUnmarshaller<TValue, JsonUnmarshallerContext>
{
private KeyValueUnmarshaller<TKey, TValue, TKeyUnmarshaller, TValueUnmarshaller> KVUnmarshaller;
public DictionaryUnmarshaller(TKeyUnmarshaller kUnmarshaller, TValueUnmarshaller vUnmarshaller)
{
KVUnmarshaller = new KeyValueUnmarshaller<TKey, TValue, TKeyUnmarshaller, TValueUnmarshaller>(kUnmarshaller, vUnmarshaller);
}
public Dictionary<TKey, TValue> Unmarshall(XmlUnmarshallerContext context)
{
var originalDepth = context.CurrentDepth;
var targetDepth = originalDepth + 1;
// If a dictionary is present in the response, use AlwaysSendDictionary,
// so if the response was empty, reusing the object in the request we will
// end up sending the same empty collection back.
var dictionary = new AlwaysSendDictionary<TKey, TValue>();
while (context.Read())
{
if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
break;
}
var item = KVUnmarshaller.Unmarshall(context);
dictionary.Add(item.Key, item.Value);
}
return dictionary;
}
public Dictionary<TKey, TValue> Unmarshall(JsonUnmarshallerContext context)
{
context.Read(); // Read { or null
if (context.CurrentTokenType == JsonToken.Null)
return new Dictionary<TKey,TValue>();
// If a dictionary is present in the response, use AlwaysSendDictionary,
// so if the response was empty, reusing the object in the request we will
// end up sending the same empty collection back.
Dictionary<TKey, TValue> dictionary = new AlwaysSendDictionary<TKey, TValue>();
while (!context.Peek(JsonToken.ObjectEnd)) // Peek }
{
KeyValuePair<TKey, TValue> item = KVUnmarshaller.Unmarshall(context);
dictionary.Add(item.Key, item.Value);
}
context.Read(); // Read }
return dictionary;
}
}
public static class UnmarshallerExtensions
{
public static void Add<TKey, TValue>(this Dictionary<TKey, TValue> dict, KeyValuePair<TKey, TValue> item)
{
dict.Add(item.Key, item.Value);
}
//public static void Add<T>(this List<T> list, List<T> items)
//{
// list.AddRange(items);
//}
}
}
| 740 |
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;
using Amazon.Runtime.Internal.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml;
using ThirdParty.Ionic.Zlib;
namespace Amazon.Runtime.Internal.Transform
{
/// <summary>
/// Base class for the UnmarshallerContext objects that are used
/// to unmarshall a web-service response.
/// </summary>
public abstract class UnmarshallerContext : IDisposable
{
private bool disposed = false;
protected bool MaintainResponseBody { get; set; }
protected bool IsException { get; set; }
protected CrcCalculatorStream CrcStream { get; set; }
protected int Crc32Result { get; set; }
protected CoreChecksumAlgorithm ChecksumAlgorithm { get; set; }
protected HashStream FlexibleChecksumStream { get; set; }
protected string ExpectedFlexibleChecksumResult { get; set; }
protected IWebResponseData WebResponseData { get; set; }
protected CachingWrapperStream WrappingStream { get; set; }
public string ResponseBody
{
get
{
var bytes = GetResponseBodyBytes();
return System.Text.UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
}
public byte[] GetResponseBodyBytes()
{
if (IsException)
{
return this.WrappingStream.AllReadBytes.ToArray();
}
if (MaintainResponseBody)
{
return this.WrappingStream.LoggableReadBytes.ToArray();
}
else
{
return ArrayEx.Empty<byte>();
}
}
public IWebResponseData ResponseData
{
get { return WebResponseData; }
}
internal void ValidateCRC32IfAvailable()
{
if (this.CrcStream != null)
{
if (this.CrcStream.Crc32 != this.Crc32Result)
{
throw new IOException("CRC value returned with response does not match the computed CRC value for the returned response body.");
}
}
}
internal void ValidateFlexibleCheckumsIfAvailable(ResponseMetadata responseMetadata)
{
if (FlexibleChecksumStream == null)
{
return;
}
responseMetadata.ChecksumAlgorithm = ChecksumAlgorithm;
responseMetadata.ChecksumValidationStatus = ChecksumValidationStatus.PENDING_RESPONSE_READ;
if (FlexibleChecksumStream.CalculatedHash != null)
{
if (Convert.ToBase64String(FlexibleChecksumStream.CalculatedHash) != ExpectedFlexibleChecksumResult)
{
responseMetadata.ChecksumValidationStatus = ChecksumValidationStatus.INVALID;
throw new AmazonClientException("Expected hash not equal to calculated hash");
}
else
{
responseMetadata.ChecksumValidationStatus = ChecksumValidationStatus.SUCCESSFUL;
}
}
}
protected void SetupCRCStream(IWebResponseData responseData, Stream responseStream, long contentLength)
{
this.CrcStream = null;
UInt32 parsed;
if (responseData != null && UInt32.TryParse(responseData.GetHeaderValue("x-amz-crc32"), out parsed))
{
this.Crc32Result = unchecked((int) parsed);
this.CrcStream = new CrcCalculatorStream(responseStream, contentLength);
}
}
protected void SetupFlexibleChecksumStream(IWebResponseData responseData, Stream responseStream, long contentLength, IRequestContext requestContext)
{
var algorithm = ChecksumUtils.SelectChecksumForResponseValidation(requestContext?.OriginalRequest?.ChecksumResponseAlgorithms, responseData);
if (algorithm == CoreChecksumAlgorithm.NONE)
{
return;
}
ChecksumAlgorithm = algorithm;
ExpectedFlexibleChecksumResult = responseData.GetHeaderValue(ChecksumUtils.GetChecksumHeaderKey(algorithm));
var checksum = Convert.FromBase64String(ExpectedFlexibleChecksumResult);
switch (algorithm)
{
case CoreChecksumAlgorithm.CRC32C:
FlexibleChecksumStream = new HashStream<HashingWrapperCRC32C>(responseStream, checksum, contentLength);
break;
case CoreChecksumAlgorithm.CRC32:
FlexibleChecksumStream = new HashStream<HashingWrapperCRC32>(responseStream, checksum, contentLength);
break;
case CoreChecksumAlgorithm.SHA256:
FlexibleChecksumStream = new HashStream<HashingWrapperSHA256>(responseStream, checksum, contentLength);
break;
case CoreChecksumAlgorithm.SHA1:
FlexibleChecksumStream = new HashStream<HashingWrapperSHA1>(responseStream, checksum, contentLength);
break;
default:
throw new AmazonClientException($"Unsupported checksum algorithm {algorithm}");
}
}
/// <summary>
/// Tests the specified expression against the current position in the XML
/// document </summary>
/// <param name="expression">
/// The pseudo-XPath expression to test.</param>
/// <returns>
/// True if the expression matches the current position in the document,
/// false otherwise.</returns>
public bool TestExpression(string expression)
{
return TestExpression(expression, CurrentPath);
}
/// <summary>
/// Tests the specified expression against the current position in the XML
/// document being parsed, and restricts the expression to matching at the
/// specified stack depth. </summary>
/// <param name="expression">
/// The pseudo-XPath expression to test.</param>
/// <param name="startingStackDepth">
/// The depth in the stack representing where the expression must
/// start matching in order for this method to return true. </param>
/// <returns>
/// True if the specified expression matches the current position in
/// the XML document, starting from the specified depth. </returns>
public bool TestExpression(string expression, int startingStackDepth)
{
return TestExpression(expression, startingStackDepth, CurrentPath, CurrentDepth);
}
/// <summary>
/// Reads the next token at depth greater than or equal to target depth.
/// </summary>
/// <param name="targetDepth">Tokens are read at depth greater than or equal to target depth.</param>
/// <returns>True if a token was read and current depth is greater than or equal to target depth.</returns>
public bool ReadAtDepth(int targetDepth)
{
return Read() && this.CurrentDepth >= targetDepth;
}
private static bool TestExpression(string expression, string currentPath)
{
if (expression.Equals("."))
return true;
return currentPath.EndsWith(expression, StringComparison.OrdinalIgnoreCase);
}
private static bool TestExpression(string expression, int startingStackDepth, string currentPath, int currentDepth)
{
if (expression.Equals("."))
return true;
int index = -1;
while ((index = expression.IndexOf("/", index + 1, StringComparison.Ordinal)) > -1)
{
// Don't consider attributes a new depth level
if (expression[0] != '@')
{
startingStackDepth++;
}
}
return startingStackDepth == currentDepth
&& currentPath.Length > expression.Length
&& currentPath[currentPath.Length - expression.Length - 1] == '/'
&& currentPath.EndsWith(expression, StringComparison.OrdinalIgnoreCase);
}
#region Abstract members
/// <summary>
/// The current path that is being unmarshalled.
/// </summary>
public abstract string CurrentPath { get; }
/// <summary>
/// Returns the element depth of the parser's current position in the
/// document being parsed.
/// </summary>
public abstract int CurrentDepth { get; }
/// <summary>
/// Reads to the next node in the document, and updates the context accordingly.
/// </summary>
/// <returns>
/// True if a node was read, false if there are no more elements to read.
/// </returns>
public abstract bool Read();
/// <summary>
/// Returns the text contents of the current element being parsed.
/// </summary>
/// <returns>
/// The text contents of the current element being parsed.
/// </returns>
public abstract string ReadText();
/// <summary>
/// True if <c>NodeType</c> is <c>Element</c>.
/// </summary>
public abstract bool IsStartElement { get; }
/// <summary>
/// True if <c>NodeType</c> is <c>EndElement</c>.
/// </summary>
public abstract bool IsEndElement { get; }
/// <summary>
/// True if the context is at the start of the document.
/// </summary>
public abstract bool IsStartOfDocument { get; }
#endregion
#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)
{
if (this.CrcStream != null)
{
CrcStream.Dispose();
CrcStream = null;
}
if (this.WrappingStream != null)
{
WrappingStream.Dispose();
WrappingStream = null;
}
}
this.disposed = true;
}
}
/// <summary>
/// Disposes of all managed and unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
/// <summary>
/// Wrap an <c>XmltextReader</c> for simulating an event stream.
///
/// Each <c>Read()</c> operation goes either to the next element or next attribute within
/// the current element. <c>TestExpression()</c> is used to match the current event
/// to an xpath expression. The general pattern looks like this:
/// <code>
/// UnmarshallerContext context = new UnmarshallerContext(...);
/// while (context.Read())
/// {
/// if (context.TestExpresion("path/to/element"))
/// {
/// myObject.stringMember = stringUnmarshaller.GetInstance().Unmarshall(context);
/// continue;
/// }
/// if (context.TestExpression("path/to/@attribute"))
/// myObject.MyComplexTypeMember = MyComplexTypeUnmarshaller.GetInstance().Unmarshall(context);
/// }
/// </code>
/// </summary>
public class XmlUnmarshallerContext : UnmarshallerContext
{
#region Private members
private static HashSet<XmlNodeType> nodesToSkip = new HashSet<XmlNodeType>
{
XmlNodeType.None,
XmlNodeType.XmlDeclaration,
XmlNodeType.Comment,
XmlNodeType.DocumentType
};
private StreamReader streamReader;
private XmlTextReader _xmlTextReader;
private Stack<string> stack = new Stack<string>();
private string stackString = "";
private Dictionary<string, string> attributeValues;
private List<string> attributeNames;
private IEnumerator<string> attributeEnumerator;
private XmlNodeType nodeType;
private string nodeContent = String.Empty;
private bool disposed = false;
private bool currentlyProcessingEmptyElement;
public Stream Stream
{
get
{
return streamReader.BaseStream;
}
}
/// <summary>
/// Lookup of element names that are not skipped if empty within the XML response structure.
/// </summary>
public HashSet<string> AllowEmptyElementLookup { get; private set; }
/// <remarks>
/// Despite Microsoft's recommendation to use XmlReader for .NET Framework 2.0 or greater
/// (https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmltextreader#remarks), this class
/// intentionally uses XmlTextReader to handle the XML related object key constraints
/// for S3 (https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html).
/// </remarks>
private XmlTextReader XmlReader
{
get
{
if (_xmlTextReader == null)
{
_xmlTextReader = new XmlTextReader(streamReader);
_xmlTextReader.WhitespaceHandling = WhitespaceHandling.None;
#if BCL35
_xmlTextReader.ProhibitDtd = false;
#else
_xmlTextReader.DtdProcessing = DtdProcessing.Ignore;
#endif
}
return _xmlTextReader;
}
}
#endregion
#region Constructors
/// <summary>
/// Wrap an XmlTextReader with state for event-based parsing of an XML stream.
/// </summary>
/// <param name="responseStream"><c>Stream</c> with the XML from a service response.</param>
/// <param name="maintainResponseBody"> If set to true, maintains a copy of the complete response body constraint to log response size as the stream is being read.</param>
/// <param name="responseData">Response data coming back from the request</param>
/// <param name="isException">If set to true, maintains a copy of the complete response body as the stream is being read.</param>
public XmlUnmarshallerContext(Stream responseStream, bool maintainResponseBody, IWebResponseData responseData, bool isException = false)
: this(responseStream, maintainResponseBody, responseData, isException, null)
{
}
/// <summary>
/// Wrap an XmlTextReader with state for event-based parsing of an XML stream.
/// </summary>
/// <param name="responseStream"><c>Stream</c> with the XML from a service response.</param>
/// <param name="maintainResponseBody"> If set to true, maintains a copy of the complete response body constraint to log response size as the stream is being read.</param>
/// <param name="responseData">Response data coming back from the request</param>
/// <param name="isException">If set to true, maintains a copy of the complete response body as the stream is being read.</param>
/// <param name="requestContext">Context for the request that produced this response</param>
public XmlUnmarshallerContext(Stream responseStream, bool maintainResponseBody, IWebResponseData responseData, bool isException, IRequestContext requestContext)
{
if (isException)
{
this.WrappingStream = new CachingWrapperStream(responseStream);
}
else if (maintainResponseBody)
{
this.WrappingStream = new CachingWrapperStream(responseStream, AWSConfigs.LoggingConfig.LogResponsesSizeLimit);
}
if (isException || maintainResponseBody)
{
responseStream = this.WrappingStream;
}
// If the unmarshaller context is being called internally without there being a http response then the response data would be null
if (responseData != null)
{
long contentLength;
bool parsedContentLengthHeader = long.TryParse(responseData.GetHeaderValue("Content-Length"), out contentLength);
// Validate flexible checksums if we know the content length and the behavior was opted in to on the request
if (parsedContentLengthHeader && responseData.ContentLength == contentLength &&
string.IsNullOrEmpty(responseData.GetHeaderValue("Content-Encoding")) &&
requestContext?.OriginalRequest?.CoreChecksumMode == CoreChecksumResponseBehavior.ENABLED)
{
SetupFlexibleChecksumStream(responseData, responseStream, contentLength, requestContext);
}
}
streamReader = new StreamReader(this.FlexibleChecksumStream ?? responseStream);
this.WebResponseData = responseData;
this.MaintainResponseBody = maintainResponseBody;
this.IsException = isException;
this.AllowEmptyElementLookup = new HashSet<string>();
}
#endregion
#region Overrides
/// <summary>
/// The current XML path that is being unmarshalled.
/// </summary>
public override string CurrentPath
{
get { return this.stackString; }
}
/// <summary>
/// Returns the element depth of the parser's current position in the XML
/// document being parsed.
/// </summary>
public override int CurrentDepth
{
get { return stack.Count; }
}
/// <summary>
/// Reads to the next node in the XML document, and updates the context accordingly.
/// </summary>
/// <returns>
/// True if a node was read, false if there are no more elements to read./
/// </returns>
public override bool Read()
{
if (attributeEnumerator != null && attributeEnumerator.MoveNext())
{
this.nodeType = XmlNodeType.Attribute;
stackString = string.Format(CultureInfo.InvariantCulture, "{0}/@{1}", StackToPath(stack), attributeEnumerator.Current);
}
else
{
// Skip some nodes
if (nodesToSkip.Contains(XmlReader.NodeType))
XmlReader.Read();
while (XmlReader.IsEmptyElement && !AllowEmptyElementLookup.Contains(XmlReader.LocalName))
{
XmlReader.Read();
}
if (currentlyProcessingEmptyElement)
{
nodeType = XmlNodeType.EndElement;
stack.Pop();
stackString = StackToPath(stack);
XmlReader.Read();
currentlyProcessingEmptyElement = false;
}
else if(XmlReader.IsEmptyElement && AllowEmptyElementLookup.Contains(XmlReader.LocalName))
{
//This is a shorthand form of an empty element <element /> and we want to allow it
nodeType = XmlNodeType.Element;
stack.Push(XmlReader.LocalName);
stackString = StackToPath(stack);
currentlyProcessingEmptyElement = true;
//Defer reading so that on next pass we can treat this same element as the end element.
}
else
{
switch (XmlReader.NodeType)
{
case XmlNodeType.EndElement:
this.nodeType = XmlNodeType.EndElement;
stack.Pop();
stackString = StackToPath(stack);
XmlReader.Read();
break;
case XmlNodeType.Element:
nodeType = XmlNodeType.Element;
stack.Push(XmlReader.LocalName);
stackString = StackToPath(stack);
this.ReadElement();
break;
}
}
}
bool moreDataAvailable =
XmlReader.ReadState != ReadState.EndOfFile &&
XmlReader.ReadState != ReadState.Error &&
XmlReader.ReadState != ReadState.Closed;
return moreDataAvailable;
}
/// <summary>
/// Returns the text contents of the current element being parsed.
/// </summary>
/// <returns>
/// The text contents of the current element being parsed.
/// </returns>
public override string ReadText()
{
if (this.nodeType == XmlNodeType.Attribute)
{
return (attributeValues[attributeEnumerator.Current]);
}
else
{
return nodeContent;
}
}
/// <summary>
/// True if <c>NodeType</c> is <c>Element</c>.
/// </summary>
public override bool IsStartElement
{
get { return this.nodeType == XmlNodeType.Element; }
}
/// <summary>
/// True if <c>NodeType</c> is <c>EndElement</c>.
/// </summary>
public override bool IsEndElement
{
get { return this.nodeType == XmlNodeType.EndElement; }
}
/// <summary>
/// True if the context is at the start of the document.
/// </summary>
public override bool IsStartOfDocument
{
get { return XmlReader.ReadState == ReadState.Initial; }
}
#endregion
#region Public methods
/// <summary>
/// True if <c>NodeType</c> is <c>Attribute</c>.
/// </summary>
public bool IsAttribute
{
get { return this.nodeType == XmlNodeType.Attribute; }
}
#endregion
#region Private Methods
private static string StackToPath(Stack<string> stack)
{
string path = null;
foreach (string s in stack.ToArray())
{
path = null == path ? s : string.Format(CultureInfo.InvariantCulture, "{0}/{1}", s, path);
}
return "/" + path;
}
// Move to the next element, cache the attributes collection
// and attempt to cache the inner text of the element if applicable.
private void ReadElement()
{
if (XmlReader.HasAttributes)
{
attributeValues = new Dictionary<string, string>();
attributeNames = new List<string>();
while (XmlReader.MoveToNextAttribute())
{
attributeValues.Add(XmlReader.LocalName, XmlReader.Value);
attributeNames.Add(XmlReader.LocalName);
}
attributeEnumerator = attributeNames.GetEnumerator();
}
XmlReader.MoveToElement();
XmlReader.Read();
if (XmlReader.NodeType == XmlNodeType.Text)
nodeContent = XmlReader.ReadContentAsString();
else
nodeContent = String.Empty;
}
#endregion
protected override void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (streamReader != null)
{
streamReader.Dispose();
streamReader = null;
}
if (_xmlTextReader != null)
{
#if NETSTANDARD
_xmlTextReader.Dispose();
#else
_xmlTextReader.Close();
#endif
_xmlTextReader = null;
}
}
disposed = true;
}
base.Dispose(disposing);
}
}
public class EC2UnmarshallerContext : XmlUnmarshallerContext
{
/// <summary>
/// Wrap an XmlTextReader with state for event-based parsing of an XML stream.
/// </summary>
/// <param name="responseStream"><c>Stream</c> with the XML from a service response.</param>
/// <param name="maintainResponseBody"> If set to true, maintains a copy of the complete response body constraint to log response size as the stream is being read.</param>
/// <param name="responseData">Response data coming back from the request</param>
/// <param name="isException">If set to true, maintains a copy of the complete response body as the stream is being read.</param>
public EC2UnmarshallerContext(Stream responseStream, bool maintainResponseBody, IWebResponseData responseData, bool isException = false)
: base(responseStream, maintainResponseBody, responseData, isException)
{
}
/// <summary>
/// Wrap an XmlTextReader with state for event-based parsing of an XML stream.
/// </summary>
/// <param name="responseStream"><c>Stream</c> with the XML from a service response.</param>
/// <param name="maintainResponseBody"> If set to true, maintains a copy of the complete response body constraint to log response size as the stream is being read.</param>
/// <param name="responseData">Response data coming back from the request</param>
/// <param name="isException">If set to true, maintains a copy of the complete response body as the stream is being read.</param>
/// <param name="requestContext">Context for the request that produced this response</param>
public EC2UnmarshallerContext(Stream responseStream, bool maintainResponseBody, IWebResponseData responseData, bool isException, IRequestContext requestContext)
: base(responseStream, maintainResponseBody, responseData, isException, requestContext)
{
}
/// <summary>
/// RequestId value, if found in response
/// </summary>
public string RequestId { get; private set; }
/// <summary>
/// Reads to the next node in the XML document, and updates the context accordingly.
/// If node is RequestId, reads the contents and stores in RequestId property.
/// </summary>
/// <returns>
/// True if a node was read, false if there are no more elements to read./
/// </returns>
public override bool Read()
{
bool result = base.Read();
if (RequestId == null)
{
if (IsStartElement && TestExpression("RequestId", 2))
{
RequestId = StringUnmarshaller.GetInstance().Unmarshall(this);
}
}
return result;
}
}
}
| 718 |
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.Text;
namespace Amazon.Runtime.Internal.Transform
{
#if !NETSTANDARD
// This exception is marked Serializable, but its ResponseBody field is not
// serialized/deserialized.
[Serializable]
#endif
public class HttpWebRequestResponseData : IWebResponseData
{
string[] _headerNames;
Dictionary<string, string> _headers;
HashSet<string> _headerNamesSet;
[NonSerialized]
HttpWebResponseBody _responseBody;
public HttpWebRequestResponseData(HttpWebResponse response)
{
_responseBody = new HttpWebResponseBody(response);
this.StatusCode = response.StatusCode;
this.IsSuccessStatusCode = this.StatusCode >= HttpStatusCode.OK && this.StatusCode <= (HttpStatusCode)299;
this.ContentType = response.ContentType;
this.ContentLength = response.ContentLength;
CopyHeaderValues(response);
}
public HttpStatusCode StatusCode { get; private set; }
public bool IsSuccessStatusCode { get; private set; }
public string ContentType { get; private set; }
public long ContentLength { get; private set; }
public bool IsHeaderPresent(string headerName)
{
return _headerNamesSet.Contains(headerName);
}
public string[] GetHeaderNames()
{
return _headerNames;
}
public string GetHeaderValue(string name)
{
string headerValue;
if (_headers.TryGetValue(name, out headerValue))
return headerValue;
return string.Empty;
}
private void CopyHeaderValues(HttpWebResponse response)
{
var keys = response.Headers.Keys;
_headerNames = new string[keys.Count];
_headers = new Dictionary<string, string>(keys.Count, StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < keys.Count; i++)
{
var key = keys[i];
var headerValue = response.GetResponseHeader(key);
_headerNames[i] = key;
_headers.Add(key, headerValue);
}
_headerNamesSet = new HashSet<string>(_headerNames, StringComparer.OrdinalIgnoreCase);
}
public IHttpResponseBody ResponseBody
{
get { return _responseBody; }
}
/// <summary>
/// Constructs a new instance of the HttpWebRequestResponseData class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected HttpWebRequestResponseData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
if (info != null)
{
this._headerNames = (string[])info.GetValue("_headerNames", typeof(string[]));
this._headerNamesSet = (HashSet<string>)info.GetValue("_headerNamesSet", typeof(HashSet<string>));
this._headers = (Dictionary<string, string>)info.GetValue("_headers", typeof(Dictionary<string, string>));
this.StatusCode = (HttpStatusCode)info.GetValue("StatusCode", typeof(HttpStatusCode));
this.IsSuccessStatusCode = info.GetBoolean("IsSuccessStatusCode");
this.ContentType = info.GetString("ContentType");
this.ContentLength = info.GetInt64("ContentLength");
}
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
[System.Security.SecurityCritical]
public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
if (info != null)
{
info.AddValue("_headerNames", this._headerNames);
info.AddValue("_headerNamesSet", this._headerNamesSet);
info.AddValue("_headers", this._headers);
info.AddValue("StatusCode", this.StatusCode);
info.AddValue("IsSuccessStatusCode", this.IsSuccessStatusCode);
info.AddValue("ContentType", this.ContentType);
info.AddValue("ContentLength", this.ContentLength);
}
}
}
public class HttpWebResponseBody : IHttpResponseBody
{
HttpWebResponse _response;
bool _disposed = false;
public HttpWebResponseBody(HttpWebResponse response)
{
_response = response;
}
public Stream OpenResponse()
{
if (_disposed)
throw new ObjectDisposedException("HttpWebResponseBody");
return _response.GetResponseStream();
}
#if AWS_ASYNC_API
public System.Threading.Tasks.Task<Stream> OpenResponseAsync()
{
// There is no GetResponseStreamAsync on HttpWebResponse so just
// reuse the sync version.
return System.Threading.Tasks.Task.FromResult(OpenResponse());
}
#endif
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_response != null)
_response.Close();
_disposed = true;
}
}
}
}
| 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 System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Amazon.Runtime.Internal.Transform
{
public class HttpClientResponseData : IWebResponseData
{
HttpResponseMessageBody _response;
string[] _headerNames;
Dictionary<string, string> _headers;
HashSet<string> _headerNamesSet;
internal HttpClientResponseData(HttpResponseMessage response)
: this(response, null, false)
{
}
internal HttpClientResponseData(HttpResponseMessage response, HttpClient httpClient, bool disposeClient)
{
_response = new HttpResponseMessageBody(response, httpClient, disposeClient);
this.StatusCode = response.StatusCode;
this.IsSuccessStatusCode = response.IsSuccessStatusCode;
this.ContentLength = response.Content.Headers.ContentLength ?? 0;
if (response.Content.Headers.ContentType != null)
{
this.ContentType = response.Content.Headers.ContentType.MediaType;
}
CopyHeaderValues(response);
}
public HttpStatusCode StatusCode { get; private set; }
public bool IsSuccessStatusCode { get; private set; }
public string ContentType { get; private set; }
public long ContentLength { get; private set; }
public string GetHeaderValue(string headerName)
{
string headerValue;
if(_headers.TryGetValue(headerName, out headerValue))
return headerValue;
return string.Empty;
}
public bool IsHeaderPresent(string headerName)
{
return _headerNamesSet.Contains(headerName);
}
public string[] GetHeaderNames()
{
return _headerNames;
}
private void CopyHeaderValues(HttpResponseMessage response)
{
List<string> headerNames = new List<string>();
_headers = new Dictionary<string, string>(10, StringComparer.OrdinalIgnoreCase);
foreach (KeyValuePair<string, IEnumerable<string>> kvp in response.Headers)
{
headerNames.Add(kvp.Key);
var headerValue = GetFirstHeaderValue(response.Headers, kvp.Key);
_headers.Add(kvp.Key, headerValue);
}
if (response.Content != null)
{
foreach (var kvp in response.Content.Headers)
{
if (!headerNames.Contains(kvp.Key))
{
headerNames.Add(kvp.Key);
var headerValue = GetFirstHeaderValue(response.Content.Headers, kvp.Key);
_headers.Add(kvp.Key, headerValue);
}
}
}
_headerNames = headerNames.ToArray();
_headerNamesSet = new HashSet<string>(_headerNames, StringComparer.OrdinalIgnoreCase);
}
private string GetFirstHeaderValue(HttpHeaders headers, string key)
{
IEnumerable<string> headerValues = null;
if (headers.TryGetValues(key, out headerValues))
return headerValues.FirstOrDefault();
return string.Empty;
}
public IHttpResponseBody ResponseBody
{
get { return _response; }
}
}
[CLSCompliant(false)]
public class HttpResponseMessageBody : IHttpResponseBody
{
HttpClient _httpClient;
HttpResponseMessage _response;
bool _disposeClient = false;
bool _disposed = false;
public HttpResponseMessageBody(HttpResponseMessage response, HttpClient httpClient, bool disposeClient)
{
_httpClient = httpClient;
_response = response;
_disposeClient = disposeClient;
}
public Stream OpenResponse()
{
if (_disposed)
throw new ObjectDisposedException("HttpWebResponseBody");
return _response.Content.ReadAsStreamAsync().Result;
}
public Task<Stream> OpenResponseAsync()
{
if (_disposed)
throw new ObjectDisposedException("HttpWebResponseBody");
return _response.Content.ReadAsStreamAsync();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_response != null)
_response.Dispose();
if (_httpClient != null && _disposeClient)
_httpClient.Dispose();
_disposed = true;
}
}
}
}
| 181 |
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.Text;
using Amazon.Runtime;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// A stream which caches the contents of the underlying stream as it reads it.
/// </summary>
public class CachingWrapperStream : WrapperStream
{
private readonly int? _cacheLimit;
private int _cachedBytes = 0;
/// <summary>
/// All the bytes read by the stream.
/// </summary>
public List<Byte> AllReadBytes { get; private set; }
/// <summary>
/// All the bytes read by the stream constrained with _cacheLimit
/// </summary>
public List<Byte> LoggableReadBytes {
get
{
var limit = _cacheLimit ?? AWSConfigs.LoggingConfig.LogResponsesSizeLimit;
return AllReadBytes.Take(limit).ToList();
}
}
/// <summary>
/// Initializes the CachingWrapperStream with a base stream.
/// </summary>
/// <param name="baseStream">The stream to be wrapped.</param>
/// <param name="cacheLimit">Maximum number of bytes to be cached.</param>
public CachingWrapperStream(Stream baseStream, int? cacheLimit = null) : base(baseStream)
{
_cacheLimit = cacheLimit;
this.AllReadBytes = new List<byte>();
}
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position
/// within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the
/// number of bytes requested if that many bytes are not currently available,
/// or zero (0) if the end of the stream has been reached.
/// </returns>
public override int Read(byte[] buffer, int offset, int count)
{
var numberOfBytesRead = base.Read(buffer, offset, count);
UpdateCacheAfterReading(buffer, offset, numberOfBytesRead);
return numberOfBytesRead;
}
#if AWS_ASYNC_API
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var numberOfBytesRead = await base.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
UpdateCacheAfterReading(buffer, offset, numberOfBytesRead);
return numberOfBytesRead;
}
#endif
private void UpdateCacheAfterReading(byte[] buffer, int offset, int numberOfBytesRead)
{
// Limit the cached bytes to _cacheLimit
if (_cacheLimit.HasValue)
{
if (_cachedBytes < _cacheLimit.Value)
{
int remainingBytes = _cacheLimit.Value - _cachedBytes;
int bytesToCache = Math.Min(numberOfBytesRead, remainingBytes);
var readBytes = new byte[bytesToCache];
System.Array.Copy(buffer, offset, readBytes, 0, bytesToCache);
AllReadBytes.AddRange(readBytes);
_cachedBytes += bytesToCache;
}
}
else
{
var readBytes = new byte[numberOfBytesRead];
System.Array.Copy(buffer, offset, readBytes, 0, numberOfBytesRead);
AllReadBytes.AddRange(readBytes);
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// CachingWrapperStream does not support seeking, this will always be false.
/// </summary>
public override bool CanSeek
{
get
{
// Restrict random access.
return false;
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// CachingWrapperStream does not support seeking, attempting to set Position
/// will throw NotSupportedException.
/// </summary>
public override long Position
{
get
{
throw new NotSupportedException("CachingWrapperStream does not support seeking");
}
set
{
// Restrict random access, as this will break hashing.
throw new NotSupportedException("CachingWrapperStream does not support seeking");
}
}
/// <summary>
/// Sets the position within the current stream.
/// CachingWrapperStream does not support seeking, attempting to call Seek
/// will throw NotSupportedException.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">
/// A value of type System.IO.SeekOrigin indicating the reference point used
/// to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
// Restrict random access.
throw new NotSupportedException("CachingWrapperStream does not support seeking");
}
}
}
| 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.
*/
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.SharedInterfaces.Internal;
using Amazon.Util.Internal;
using System.Globalization;
using System.IO;
namespace AWSSDK.Runtime.Internal.Util
{
/// <summary>
/// Wrapper for checksum algorithms provided by the AWS Common Runtime
/// </summary>
public static class ChecksumCRTWrapper
{
private const string CRT_WRAPPER_ASSEMBLY_NAME = "AWSSDK.Extensions.CrtIntegration";
private const string CRT_WRAPPER_NUGET_PACKAGE_NAME = "AWSSDK.Extensions.CrtIntegration";
private const string CRT_WRAPPER_CLASS_NAME = "AWSSDK.Extensions.CrtIntegration.CrtChecksums";
private static readonly object _lock = new object();
private static volatile IChecksumProvider _instance;
private static IChecksumProvider Instance
{
get
{
if (_instance != null)
return _instance;
lock (_lock)
{
if (_instance == null)
{
try
{
var crtWrapperTypeInfo = ServiceClientHelpers.LoadTypeFromAssembly(CRT_WRAPPER_ASSEMBLY_NAME, CRT_WRAPPER_CLASS_NAME);
var constructor = crtWrapperTypeInfo.GetConstructor(new ITypeInfo[] { });
_instance = constructor.Invoke(null) as IChecksumProvider;
}
catch (FileNotFoundException)
{
throw new AWSCommonRuntimeException
(
string.Format(CultureInfo.InvariantCulture,
"Attempting to handle a request that requires additional checksums. Add a reference " +
$"to the {CRT_WRAPPER_NUGET_PACKAGE_NAME} NuGet package to your project to include the AWS Common Runtime checksum implementation.")
);
}
}
}
return _instance;
}
}
/// <summary>
/// Computes a CRC32 hash
/// </summary>
/// <param name="source">Data to hash</param>
/// <returns>CRC32 hash as a base64-encoded string</returns>
public static string Crc32(byte[] source)
{
return Instance.Crc32(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>
public static uint Crc32(byte[] source, uint previous)
{
return Instance.Crc32(source, previous);
}
/// <summary>
/// Computes a CRC32C hash
/// </summary>
/// <param name="source">Data to hash</param>
/// <returns>CRC32c hash as a base64-encoded string</returns>
public static string Crc32C(byte[] source)
{
return Instance.Crc32C(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>
public static uint Crc32C(byte[] source, uint previous)
{
return Instance.Crc32C(source, previous);
}
}
}
| 113 |
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.Transform;
using Amazon.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using ThirdParty.MD5;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Utilities for working with the checksums used to validate request/response integrity
/// </summary>
public static class ChecksumUtils
{
/// <summary>
/// Generates the name of the header key to use for a given checksum algorithm
/// </summary>
/// <param name="checksumAlgorithm">Checksum algorithm</param>
/// <returns>Name of the HTTP header key for the given algorithm</returns>
internal static string GetChecksumHeaderKey(CoreChecksumAlgorithm checksumAlgorithm)
{
return $"x-amz-checksum-{checksumAlgorithm.ToString().ToLower()}";
}
/// <summary>
/// Attempts to select and then calculate the checksum for a request
/// </summary>
/// <param name="request">Request to calculate the checksum for</param>
/// <param name="checksumAlgorithm">Checksum algorithm to use, specified on the request using a service-specific enum</param>
/// <param name="fallbackToMD5">If checksumAlgorithm is <see cref="CoreChecksumAlgorithm.NONE"/>,
/// this flag controls whether or not to fallback to using a MD5 to generate a checksum.
/// </param>
public static void SetRequestChecksum(IRequest request, string checksumAlgorithm, bool fallbackToMD5 = true)
{
var coreChecksumAlgoritm = ChecksumUtils.ConvertToCoreChecksumAlgorithm(checksumAlgorithm);
if (coreChecksumAlgoritm == CoreChecksumAlgorithm.NONE)
{
if (fallbackToMD5)
SetRequestChecksumMD5(request);
return;
}
var checksumHeaderKey = GetChecksumHeaderKey(coreChecksumAlgoritm);
// If the user provided a precalculated header for this checksum, don't recalculate it
if (request.Headers.TryGetValue(checksumHeaderKey, out var checksumHeaderValue))
{
if (!string.IsNullOrEmpty(checksumHeaderValue))
{
return;
}
}
if (request.UseChunkEncoding || (request.DisablePayloadSigning ?? false))
{
// Add the checksum key to the trailing headers, but not the value
// because we won't know it until the wrapper stream is fully read,
// and we only want to read the wrapper stream once.
//
// The header key is required upfront for calculating the total length of
// the wrapper stream, which we need to send as the Content-Length header
// before the wrapper stream is transmitted.
request.TrailingHeaders.Add(checksumHeaderKey, string.Empty);
request.SelectedChecksum = coreChecksumAlgoritm;
}
else // calculate and set the checksum in the request headers
{
request.Headers[checksumHeaderKey] = CalculateChecksumForRequest(CryptoUtilFactory.GetChecksumInstance(coreChecksumAlgoritm), request);
}
}
/// <summary>
/// Attempts to select and then calculate a MD5 checksum for a request
/// </summary>
/// <param name="request">Request to calculate the checksum for</param>
public static void SetRequestChecksumMD5(IRequest request)
{
// If the user provided a precalculated MD5 header, don't recalculate it
if (request.Headers.TryGetValue(HeaderKeys.ContentMD5Header, out var md5HeaderValue))
{
if (!string.IsNullOrEmpty(md5HeaderValue))
{
return;
}
}
request.Headers[HeaderKeys.ContentMD5Header] = request.ContentStream != null ?
AWSSDKUtils.GenerateMD5ChecksumForStream(request.ContentStream) :
AWSSDKUtils.GenerateChecksumForBytes(request.Content, true);
}
/// <summary>
/// Calculates the given checksum for a marshalled request
/// </summary>
/// <param name="algorithm">Checksum algorithm to calculate</param>
/// <param name="request">Request whose content to calculate the checksum for</param>
/// <returns>Calculated checksum for the given request</returns>
private static string CalculateChecksumForRequest(HashAlgorithm algorithm, IRequest request)
{
if (request.ContentStream != null)
{
var seekableStream = WrapperStream.SearchWrappedStream(request.ContentStream, s => s.CanSeek);
if (seekableStream != null)
{
var position = seekableStream.Position;
var checksumBytes = algorithm.ComputeHash(seekableStream);
seekableStream.Seek(position, SeekOrigin.Begin);
return Convert.ToBase64String(checksumBytes);
}
else
{
throw new ArgumentException("Request must have a seekable content stream to calculate checksum");
}
}
else if (request.Content != null)
{
var checksumBytes = algorithm.ComputeHash(request.Content);
return Convert.ToBase64String(checksumBytes);
}
else // request doesn't have content
{
return string.Empty;
}
}
/// <summary>
/// Selects which checksum to use to validate the integrity of a response
/// </summary>
/// <param name="operationSupportedChecksums">List of checksums supported by the service operation</param>
/// <param name="responseData">Response from the service, which potentially contains x-amz-checksum-* headers</param>
/// <returns>Single checksum algorithm to use for validating the response, or NONE if checksum validation should be skipped</returns>
public static CoreChecksumAlgorithm SelectChecksumForResponseValidation(ICollection<CoreChecksumAlgorithm> operationSupportedChecksums, IWebResponseData responseData)
{
if (operationSupportedChecksums == null || operationSupportedChecksums.Count == 0 || responseData == null)
{
return CoreChecksumAlgorithm.NONE;
}
// Checksums to use for validation in order of speed (via CRT profiling)
CoreChecksumAlgorithm[] checksumsInPriorityOrder =
{
CoreChecksumAlgorithm.CRC32C,
CoreChecksumAlgorithm.CRC32,
CoreChecksumAlgorithm.SHA1,
CoreChecksumAlgorithm.SHA256
};
foreach (var algorithm in checksumsInPriorityOrder)
{
if (operationSupportedChecksums.Contains(algorithm))
{
var headerKey = GetChecksumHeaderKey(algorithm);
if (responseData.IsHeaderPresent(headerKey) && !IsChecksumValueMultipartGet(responseData.GetHeaderValue(headerKey)))
{
return algorithm;
}
}
}
return CoreChecksumAlgorithm.NONE;
}
/// <summary>
/// Determines if a checksum value is for a whole S3 multipart object, which must skip validation.
/// These checksums end with `-#`, where # is an integer between 1 and 10000
/// </summary>
/// <param name="checksumValue">Base 64 checksum value</param>
/// <returns>True if the checksum is for an S3 multipart object, false otherwise</returns>
private static bool IsChecksumValueMultipartGet(string checksumValue)
{
if (string.IsNullOrEmpty(checksumValue))
{
return false;
}
var lastDashIndex = checksumValue.LastIndexOf('-');
if (lastDashIndex == -1)
{
return false;
}
int partNumber;
var isInteger = int.TryParse(checksumValue.Substring(lastDashIndex + 1), out partNumber);
if (!isInteger)
{
return false;
}
if (partNumber >= 1 && partNumber <= 10000)
{
return true;
}
return false;
}
/// <summary>
/// Translates a string representation of a flexible checksum algorithm to the
/// corresponding <see cref="CoreChecksumAlgorithm" /> enum value.
/// </summary>
/// <param name="selectedServiceChecksum">Checksum algorithm as a string</param>
/// <returns>Enum value reprsenting the checksum algorithm</returns>
/// <exception cref="AmazonClientException">Thrown if a matching enum value could not be found</exception>
private static CoreChecksumAlgorithm ConvertToCoreChecksumAlgorithm(string selectedServiceChecksum)
{
if (string.IsNullOrEmpty(selectedServiceChecksum))
{
return CoreChecksumAlgorithm.NONE;
}
CoreChecksumAlgorithm selectedCoreChecksumAlgorithm;
#if BCL35
try
{
selectedCoreChecksumAlgorithm = (CoreChecksumAlgorithm)Enum.Parse(typeof(CoreChecksumAlgorithm), selectedServiceChecksum, true);
}
catch (Exception ex)
{
// Service checksum options should always be a subset of the core, but in case not
throw new AmazonClientException($"Attempted to sign a request with an unknown checksum algorithm {selectedServiceChecksum}", ex);
}
#else
if (!Enum.TryParse(selectedServiceChecksum, true, out selectedCoreChecksumAlgorithm))
{
// Service checksum options should always be a subset of the core, but in case not
throw new AmazonClientException($"Attempted to sign a request with an unknown checksum algorithm {selectedServiceChecksum}");
}
#endif
return selectedCoreChecksumAlgorithm;
}
}
}
| 251 |
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.Globalization;
using System.IO;
using System.Text;
using Amazon.Util;
using Amazon.Util.Internal;
using Amazon.Runtime.Internal.Auth;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Linq;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Stream wrapper that double-buffers from a wrapped stream and
/// returns the buffered content as a series of signed 'chunks'
/// for the AWS4 ('Signature V4') protocol or the asymmetric Sigv4 (Sigv4a) protocol.
/// </summary>
public class ChunkedUploadWrapperStream : WrapperStream
{
public static readonly int DefaultChunkSize = 81920;
private const string STREAM_NEWLINE = "\r\n";
private const int NEWLINE_LENGTH = 2;
private const int HEADER_ROW_PADDING_LENGTH = 3; // additional length for each row of a trailing header, 1 for ':' between the key and value, plus 2 for CRLF
private const string CHUNK_STRING_TO_SIGN_PREFIX = "AWS4-HMAC-SHA256-PAYLOAD";
private const string CHUNK_SIGNATURE_HEADER = ";chunk-signature=";
public const int V4_SIGNATURE_LENGTH = 64;
public const int V4A_SIGNATURE_LENGTH = 144;
private const string TRAILING_HEADER_SIGNATURE_KEY = "x-amz-trailer-signature";
private const string TRAILING_HEADER_STRING_TO_SIGN_PREFIX = "AWS4-HMAC-SHA256-TRAILER";
private byte[] _inputBuffer;
private readonly byte[] _outputBuffer;
private int _outputBufferPos = -1;
private int _outputBufferDataLen = -1;
private readonly int _wrappedStreamBufferSize;
private bool _wrappedStreamConsumed;
private CoreChecksumAlgorithm _trailingChecksum;
private HashAlgorithm _hashAlgorithm;
private IDictionary<string, string> _trailingHeaders;
private string _trailingHeaderChunk;
private int _trailingHeaderPos = 0;
private bool _trailingHeadersConsumed = true;
// if this is set, we've exhausted the input stream and are now sending
// back to the client the final termination chunk, after which all Read
// operations will return 0 bytes.
private bool _outputBufferIsTerminatingChunk;
// The reading strategy used by FillInputBuffer against the wrapped stream.
// We prefer to read direct into our _inputBuffer but this isn't compatible
// with wrapped encryption streams, where we need to read into an interim
// buffer and then copy the encrypted content to _inputBuffer
private enum ReadStrategy
{
ReadDirect,
ReadAndCopy
}
private readonly ReadStrategy _readStrategy = ReadStrategy.ReadDirect;
/// <summary>
/// Initializes a chunked upload stream
/// </summary>
/// <param name="stream">stream to wrap</param>
/// <param name="wrappedStreamBufferSize">Size of buffer used for reading from stream</param>
/// <param name="headerSigningResult">SigV4 or SigV4a signing result for the request's headers</param>
internal ChunkedUploadWrapperStream(Stream stream, int wrappedStreamBufferSize, AWSSigningResultBase headerSigningResult) : base(stream)
{
if (!(headerSigningResult is AWS4aSigningResult || headerSigningResult is AWS4SigningResult))
{
throw new AmazonClientException($"{nameof(ChunkedUploadWrapperStream)} was initialized without a SigV4 or SigV4a signing result.");
}
else if (headerSigningResult is AWS4aSigningResult)
{
Sigv4aSigner = new AWS4aSignerCRTWrapper();
}
HeaderSigningResult = headerSigningResult;
PreviousChunkSignature = headerSigningResult?.Signature;
_wrappedStreamBufferSize = wrappedStreamBufferSize;
_inputBuffer = new byte[DefaultChunkSize];
_outputBuffer = new byte[CalculateChunkHeaderLength(DefaultChunkSize, HeaderSigningResult is AWS4aSigningResult ? V4A_SIGNATURE_LENGTH : V4_SIGNATURE_LENGTH)]; // header+data
// if the wrapped stream implements encryption, switch to a read-and-copy
// strategy for filling the chunk buffer
var encryptionStream = SearchWrappedStream(s =>
{
var encryptUploadPartStream = s as EncryptUploadPartStream;
if (encryptUploadPartStream != null)
return true;
var encryptStream = s as EncryptStream;
return encryptStream != null;
});
if (encryptionStream != null)
_readStrategy = ReadStrategy.ReadAndCopy;
}
/// <summary>
/// Initializes a chunked upload stream with one or more trailing headers,
/// which may include a trailing checksum header
/// </summary>
/// <param name="stream">Stream to wrap</param>
/// <param name="wrappedStreamBufferSize">Size of buffer used for reading from stream</param>
/// <param name="headerSigningResult">SigV4 or SigV4a signing result for the request's headers</param>
/// <param name="trailingChecksum">Algorithm to use to calculate the stream's checksum</param>
/// <param name="trailingHeaders">Trailing headers to append after the wrapped stream</param>
public ChunkedUploadWrapperStream(Stream stream,
int wrappedStreamBufferSize,
AWSSigningResultBase headerSigningResult,
CoreChecksumAlgorithm trailingChecksum,
IDictionary<string, string> trailingHeaders)
: this(stream, wrappedStreamBufferSize, headerSigningResult)
{
if (trailingChecksum != CoreChecksumAlgorithm.NONE)
{
_trailingChecksum = trailingChecksum;
_hashAlgorithm = CryptoUtilFactory.GetChecksumInstance(trailingChecksum);
}
_trailingHeadersConsumed = false;
_trailingHeaders = trailingHeaders;
}
/// <summary>
/// Reads some or all of the processed chunk to the consumer, constructing
/// and streaming a new chunk if more input data is available.
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <returns></returns>
public override int Read(byte[] buffer, int offset, int count)
{
int bytesRead = 0;
// If we have more no output and it was the special termination chunk,
// write the trailing headers if they're set, then we're done
//
// Otherwise fill the input buffer with enough data
// for the next chunk (or with whatever is left) and construct
// the chunk in the output buffer ready for streaming
if (_outputBufferPos == -1)
{
if (_wrappedStreamConsumed && _outputBufferIsTerminatingChunk)
{
if (_trailingHeadersConsumed)
{
return 0;
}
else
{
return WriteTrailingHeaders(buffer, offset, count);
}
}
bytesRead = FillInputBuffer();
}
return AdjustBufferAfterReading(buffer, offset, count, bytesRead);
}
private int AdjustBufferAfterReading(byte[] buffer, int offset, int count, int bytesRead)
{
if (_outputBufferPos == -1)
{
ConstructOutputBufferChunk(bytesRead);
_outputBufferIsTerminatingChunk = (_wrappedStreamConsumed && bytesRead == 0);
}
var outputRemaining = _outputBufferDataLen - _outputBufferPos;
if (outputRemaining < count)
count = outputRemaining;
Buffer.BlockCopy(_outputBuffer, _outputBufferPos, buffer, offset, count);
_outputBufferPos += count;
if (_outputBufferPos >= _outputBufferDataLen)
_outputBufferPos = -1;
return count;
}
#if AWS_ASYNC_API
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
int bytesRead = 0;
// If we have more no output and it was the special termination chunk,
// write the trailing headers if they're set, then we're done
//
// Otherwise fill the input buffer with enough data
// for the next chunk (or with whatever is left) and construct
// the chunk in the output buffer ready for streaming
if (_outputBufferPos == -1)
{
if (_wrappedStreamConsumed && _outputBufferIsTerminatingChunk)
{
if (_trailingHeadersConsumed)
{
return 0;
}
else
{
return WriteTrailingHeaders(buffer, offset, count);
}
}
bytesRead = await FillInputBufferAsync(cancellationToken).ConfigureAwait(false);
}
return AdjustBufferAfterReading(buffer, offset, count, bytesRead);
}
/// <summary>
/// Attempt to read sufficient data for a whole chunk from the wrapped stream,
/// returning the number of bytes successfully read to be processed into a chunk
/// </summary>
private async Task<int> FillInputBufferAsync(CancellationToken cancellationToken)
{
if (_wrappedStreamConsumed)
return 0;
var inputBufferPos = 0;
if (_readStrategy == ReadStrategy.ReadDirect)
{
while (inputBufferPos < _inputBuffer.Length && !_wrappedStreamConsumed)
{
// chunk buffer size may not align exactly with underlying buffer size
var chunkBufferRemaining = _inputBuffer.Length - inputBufferPos;
if (chunkBufferRemaining > _wrappedStreamBufferSize)
chunkBufferRemaining = _wrappedStreamBufferSize;
var bytesRead = await BaseStream.ReadAsync(_inputBuffer, inputBufferPos, chunkBufferRemaining, cancellationToken).ConfigureAwait(false);
if (bytesRead == 0)
_wrappedStreamConsumed = true;
else
inputBufferPos += bytesRead;
}
}
else
{
var readBuffer = new byte[_wrappedStreamBufferSize];
while (inputBufferPos < _inputBuffer.Length && !_wrappedStreamConsumed)
{
var bytesRead = await BaseStream.ReadAsync(readBuffer, 0, _wrappedStreamBufferSize, cancellationToken).ConfigureAwait(false);
if (bytesRead == 0)
_wrappedStreamConsumed = true;
else
{
Buffer.BlockCopy(readBuffer, 0, _inputBuffer, inputBufferPos, bytesRead);
inputBufferPos += bytesRead;
}
}
}
return inputBufferPos;
}
#endif
/// <summary>
/// Results of the header-signing portion of the request when using SigV4 signing
/// </summary>
private AWSSigningResultBase HeaderSigningResult { get; set; }
/// <summary>
/// SigV4a signer
/// </summary>
private AWS4aSignerCRTWrapper Sigv4aSigner { get; set; }
/// <summary>
/// Computed signature of the chunk prior to the one in-flight in hex,
/// for either SigV4 or SigV4a
/// </summary>
private string PreviousChunkSignature { get; set; }
/// <summary>
/// Computes the derived signature for a chunk of data of given length in the input buffer,
/// placing a formatted chunk with headers, signature and data into the output buffer
/// ready for streaming back to the consumer.
/// </summary>
/// <param name="dataLen"></param>
private void ConstructOutputBufferChunk(int dataLen)
{
// if the input wasn't sufficient to fill the buffer, size it
// down to make the subseqent hashing/computations easier since
// they don't take any length arguments
if (dataLen > 0 && dataLen < _inputBuffer.Length)
{
var temp = new byte[dataLen];
Buffer.BlockCopy(_inputBuffer, 0, temp, 0, dataLen);
_inputBuffer = temp;
}
var isFinalDataChunk = dataLen == 0;
var chunkHeader = new StringBuilder();
// variable-length size of the embedded chunk data in hex
chunkHeader.Append(dataLen.ToString("X", CultureInfo.InvariantCulture));
string chunkSignature = "";
if (HeaderSigningResult is AWS4aSigningResult v4aHeaderSigningResult)
{
if (isFinalDataChunk) // _inputBuffer still contains previous chunk, but this is the final 0 content chunk so sign null
{
chunkSignature = Sigv4aSigner.SignChunk(null, PreviousChunkSignature, v4aHeaderSigningResult);
}
else
{
chunkSignature = Sigv4aSigner.SignChunk(new MemoryStream(_inputBuffer), PreviousChunkSignature, v4aHeaderSigningResult);
}
}
else if (HeaderSigningResult is AWS4SigningResult v4HeaderSingingResult) // SigV4
{
var chunkStringToSign = BuildChunkedStringToSign(CHUNK_STRING_TO_SIGN_PREFIX, v4HeaderSingingResult.ISO8601DateTime,
v4HeaderSingingResult.Scope, PreviousChunkSignature, dataLen, _inputBuffer);
chunkSignature = AWSSDKUtils.ToHex(AWS4Signer.SignBlob(v4HeaderSingingResult.GetSigningKey(), chunkStringToSign), true);
}
// For Sigv4a the chunk signature must be padded when being appended to the chunk metadata,
// but not when being used as the input for the next chunk
PreviousChunkSignature = chunkSignature;
if (HeaderSigningResult is AWS4aSigningResult)
{
chunkHeader.Append(CHUNK_SIGNATURE_HEADER + chunkSignature.PadRight(V4A_SIGNATURE_LENGTH, '*'));
}
else // SigV4
{
chunkHeader.Append(CHUNK_SIGNATURE_HEADER + chunkSignature);
}
// If we're sending a trailing checksum, update the rolling checksum with this chunk's raw data
if (_hashAlgorithm != null)
{
_hashAlgorithm.TransformBlock(_inputBuffer, 0, dataLen, _inputBuffer, 0);
}
chunkHeader.Append(STREAM_NEWLINE);
try
{
var header = Encoding.UTF8.GetBytes(chunkHeader.ToString());
var trailer = ArrayEx.Empty<byte>();
// Append a trailing CRLF unless this is the final data chunk and there are trailing headers
if (!(isFinalDataChunk && _trailingHeaders?.Count > 0))
{
trailer = Encoding.UTF8.GetBytes(STREAM_NEWLINE);
}
var writePos = 0;
Buffer.BlockCopy(header, 0, _outputBuffer, writePos, header.Length);
writePos += header.Length;
if (dataLen > 0)
{
Buffer.BlockCopy(_inputBuffer, 0, _outputBuffer, writePos, dataLen);
writePos += dataLen;
}
Buffer.BlockCopy(trailer, 0, _outputBuffer, writePos, trailer.Length);
_outputBufferPos = 0;
_outputBufferDataLen = header.Length + dataLen + trailer.Length;
}
catch (Exception e)
{
throw new AmazonClientException("Unable to sign the chunked data. " + e.Message, e);
}
}
/// <summary>
/// Constructs the signed trailing headers, optionally including
/// the selected checksum for this stream's data. For example:
/// trailing-header-A:value CRLF
/// trailing-header-B:value CRLF
/// x-amz-trailer-signature:signature_value CRLF
/// CRLF
/// </summary>
/// <returns>Stream chunk containing the trailing headers and their signature</returns>
private string ConstructSignedTrailersChunk()
{
// If the trailing headers included a trailing checksum, set the hash value
if (_hashAlgorithm != null)
{
_hashAlgorithm.TransformFinalBlock(ArrayEx.Empty<byte>(), 0, 0);
_trailingHeaders[ChecksumUtils.GetChecksumHeaderKey(_trailingChecksum)] = Convert.ToBase64String(_hashAlgorithm.Hash);
}
string chunkSignature;
if (HeaderSigningResult is AWS4SigningResult)
{
var sortedTrailingHeaders = AWS4Signer.SortAndPruneHeaders(_trailingHeaders);
var canonicalizedTrailingHeaders = AWS4Signer.CanonicalizeHeaders(sortedTrailingHeaders);
var chunkStringToSign =
TRAILING_HEADER_STRING_TO_SIGN_PREFIX + "\n" +
HeaderSigningResult.ISO8601DateTime + "\n" +
HeaderSigningResult.Scope + "\n" +
PreviousChunkSignature + "\n" +
AWSSDKUtils.ToHex(AWS4Signer.ComputeHash(canonicalizedTrailingHeaders), true);
chunkSignature = AWSSDKUtils.ToHex(AWS4Signer.SignBlob(((AWS4SigningResult)HeaderSigningResult).GetSigningKey(), chunkStringToSign), true);
}
else // SigV4a
{
chunkSignature = Sigv4aSigner.SignTrailingHeaderChunk(_trailingHeaders, PreviousChunkSignature, (AWS4aSigningResult)HeaderSigningResult).PadRight(V4A_SIGNATURE_LENGTH, '*');
}
var chunk = new StringBuilder();
// The order here must match the order of keys sent already in the X-Amz-Trailer header.
foreach (var kvp in _trailingHeaders.OrderBy(kvp => kvp.Key))
{
chunk.Append($"{kvp.Key}:{kvp.Value}{STREAM_NEWLINE}");
}
chunk.Append($"{TRAILING_HEADER_SIGNATURE_KEY}:{chunkSignature}{STREAM_NEWLINE}");
chunk.Append(STREAM_NEWLINE);
return chunk.ToString();
}
/// <summary>
/// Copies the signed trailing headers to the output buffer
/// </summary>
/// <param name="buffer">The buffer to write the data into</param>
/// <param name="offset">The byte offset in buffer at which to begin copying data</param>
/// <param name="count">The maximum number of bytes to copy</param>
/// <returns>Number of bytes copied</returns>
private int WriteTrailingHeaders(byte[] buffer, int offset, int count)
{
if (string.IsNullOrEmpty(_trailingHeaderChunk))
{
_trailingHeaderChunk = ConstructSignedTrailersChunk();
}
var lengthRemaining = _trailingHeaderChunk.Length - _trailingHeaderPos;
if (lengthRemaining == 0)
{
_trailingHeadersConsumed = true;
return 0;
}
if (lengthRemaining <= count)
{
Buffer.BlockCopy(Encoding.Default.GetBytes(_trailingHeaderChunk), _trailingHeaderPos, buffer, offset, lengthRemaining);
_trailingHeadersConsumed = true;
return lengthRemaining;
}
else // the trailing headers don't entirely fit in the buffer for the current read, so use the remaining count
{
Buffer.BlockCopy(Encoding.Default.GetBytes(_trailingHeaderChunk), _trailingHeaderPos, buffer, offset, count);
_trailingHeaderPos += count;
return count;
}
}
/// <summary>
/// Length override to return the true length of the payload plus the metainfo
/// supplied with each chunk
/// </summary>
public override long Length
{
get
{
if (BaseStream == null)
{
return 0;
}
return ComputeChunkedContentLength(BaseStream.Length, HeaderSigningResult is AWS4aSigningResult ? V4A_SIGNATURE_LENGTH : V4_SIGNATURE_LENGTH, _trailingHeaders, _trailingChecksum);
}
}
public override bool CanSeek
{
get
{
return false;
}
}
/// <summary>
/// Computes the total size of the data payload, including the chunk metadata.
/// Called externally so as to be able to set the correct Content-Length header
/// value.
/// </summary>
/// <param name="originalLength">Length of the wrapped stream</param>
/// <param name="signatureLength">Length of the signature for each chunk, in bytes</param>
/// <returns>Total size of the wrapped payload, in bytes</returns>
public static long ComputeChunkedContentLength(long originalLength, int signatureLength)
{
return ComputeChunkedContentLength(originalLength, signatureLength, null, CoreChecksumAlgorithm.NONE);
}
/// <summary>
/// Computes the total size of the data payload, including the chunk metadata
/// and optional trailing headers. Called externally so as to be able to set
/// the correct Content-Length header value.
/// </summary>
/// <param name="originalLength">Length of the wrapped stream</param>
/// <param name="signatureLength">Length of the signature for each chunk, in bytes</param>
/// <param name="trailingHeaders">Optional trailing headers</param>
/// <param name="trailingChecksum">Optional checksum algorithm for a trailing header</param>
/// <returns>Total size of the wrapped payload, in bytes</returns>
public static long ComputeChunkedContentLength(long originalLength, int signatureLength, IDictionary<string, string> trailingHeaders, CoreChecksumAlgorithm trailingChecksum)
{
if (originalLength < 0)
{
throw new ArgumentOutOfRangeException("originalLength", "Expected 0 or greater value for originalLength.");
}
int trailingHeaderLength = 0;
long chunkedContentLength;
// Calculate the size of the chunked content, before trailing headers/checksum
if (originalLength == 0)
{
chunkedContentLength = CalculateChunkHeaderLength(0, signatureLength);
}
else
{
var maxSizeChunks = originalLength / DefaultChunkSize;
var remainingBytes = originalLength % DefaultChunkSize;
chunkedContentLength = maxSizeChunks * CalculateChunkHeaderLength(DefaultChunkSize, signatureLength)
+ (remainingBytes > 0 ? CalculateChunkHeaderLength(remainingBytes, signatureLength) : 0)
+ CalculateChunkHeaderLength(0, signatureLength);
}
if (trailingHeaders?.Count > 0)
{
foreach (var key in trailingHeaders.Keys)
{
// If the trailing checksum key is already in dictionary, use the
// expected length since the checksum value may not be set yet.
if (trailingChecksum != CoreChecksumAlgorithm.NONE && ChecksumUtils.GetChecksumHeaderKey(trailingChecksum) == key)
{
trailingHeaderLength += key.Length +
CryptoUtilFactory.GetChecksumBase64Length(trailingChecksum) + HEADER_ROW_PADDING_LENGTH;
}
else
{
trailingHeaderLength += key.Length + trailingHeaders[key].Length + HEADER_ROW_PADDING_LENGTH;
}
}
trailingHeaderLength += TRAILING_HEADER_SIGNATURE_KEY.Length + signatureLength + HEADER_ROW_PADDING_LENGTH;
}
return chunkedContentLength + trailingHeaderLength;
}
/// <summary>
/// Builds the string to sign for a single V4/V4a chunk
/// </summary>
/// <param name="prefix">Algorithm being used</param>
/// <param name="dateTime">ISO8601DateTime that we're signing the request for</param>
/// <param name="scope">Signing scope (date/region/service/aws4_request)</param>
/// <param name="previousSignature">Previous chunk's unpadded signature</param>
/// <param name="dataLength">Length of the content for this chunk</param>
/// <param name="inputBuffer">Content of this chunk</param>
/// <returns>The string to sign for this chunk</returns>
public static string BuildChunkedStringToSign(string prefix, string dateTime, string scope, string previousSignature, int dataLength, byte[] inputBuffer)
{
return prefix + "\n" +
dateTime + "\n" +
scope + "\n" +
previousSignature + "\n" +
AWSSDKUtils.ToHex(AWS4Signer.ComputeHash(""), true) + "\n" +
(dataLength > 0
? AWSSDKUtils.ToHex(AWS4Signer.ComputeHash(inputBuffer), true)
: AWS4Signer.EmptyBodySha256);
}
/// <summary>
/// Computes the size of the header data for each chunk.
/// </summary>
/// <param name="chunkDataSize">Payload size of each chunk, in bytes</param>
/// <param name="signatureLength">Length of the signature for each chunk, in bytes</param>
/// <returns></returns>
private static long CalculateChunkHeaderLength(long chunkDataSize, int signatureLength)
{
return chunkDataSize.ToString("X", CultureInfo.InvariantCulture).Length
+ CHUNK_SIGNATURE_HEADER.Length
+ signatureLength
+ NEWLINE_LENGTH
+ chunkDataSize
+ NEWLINE_LENGTH;
}
/// <summary>
/// Attempt to read sufficient data for a whole chunk from the wrapped stream,
/// returning the number of bytes successfully read to be processed into a chunk
/// </summary>
private int FillInputBuffer()
{
if (_wrappedStreamConsumed)
return 0;
var inputBufferPos = 0;
if (_readStrategy == ReadStrategy.ReadDirect)
{
while (inputBufferPos < _inputBuffer.Length && !_wrappedStreamConsumed)
{
// chunk buffer size may not align exactly with underlying buffer size
var chunkBufferRemaining = _inputBuffer.Length - inputBufferPos;
if (chunkBufferRemaining > _wrappedStreamBufferSize)
chunkBufferRemaining = _wrappedStreamBufferSize;
var bytesRead = BaseStream.Read(_inputBuffer, inputBufferPos, chunkBufferRemaining);
if (bytesRead == 0)
_wrappedStreamConsumed = true;
else
inputBufferPos += bytesRead;
}
}
else
{
var readBuffer = new byte[_wrappedStreamBufferSize];
while (inputBufferPos < _inputBuffer.Length && !_wrappedStreamConsumed)
{
var bytesRead = BaseStream.Read(readBuffer, 0, _wrappedStreamBufferSize);
if (bytesRead == 0)
_wrappedStreamConsumed = true;
else
{
Buffer.BlockCopy(readBuffer, 0, _inputBuffer, inputBufferPos, bytesRead);
inputBufferPos += bytesRead;
}
}
}
return inputBufferPos;
}
internal override bool HasLength
{
get
{
return HeaderSigningResult != null;
}
}
}
}
| 670 |
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.Collections.Generic;
namespace Amazon.Runtime.Internal.Util
{
/*
* The following types were added to the SDK to solve two issues:
* 1. The SDK always initializes collection types, so it was impossible
* to determine if a given collection came back from the service as empty
* or did not come back from the service at all.
* 2. The SDK does not send empty collections to the service, so it was
* impossible to send an empty collection as a value to a service.
* (Specifically, it was impossible to store an empty list or empty map
* in a DynamoDB attribute, something that the service began to support
* in late 2014.)
*
* Resolution:
* We have added these collection types and the new Is[Name]Set property
* which can be read (get) to see if the [Name] collection was present,
* and can be written (set) to specify that the [Name] collection should
* or should not be sent to the server. The logic for the new property
* is as follows:
*
* Get
* [Name] is not null AND
* [Name] is AlwaysSendList/AlwaysSendDictionary OR
* [Name].Count > 0
* => True
* Otherwise
* => False
*
* Set
* True =>
* Set [Name] to new AlwaysSendList/AlwaysSendDictionary
* False =>
* Set [Name] to new List/Dictionary
*/
/// <summary>
/// A list object that will always be sent to AWS services,
/// even if it is empty.
/// The AWS .NET SDK does not send empty collections to services, unless
/// the collection is of this type.
/// </summary>
/// <typeparam name="T"></typeparam>
internal class AlwaysSendList<T> : List<T>
{
public AlwaysSendList()
: base() { }
public AlwaysSendList(IEnumerable<T> collection)
: base(collection ?? new List<T>()) { }
}
/// <summary>
/// A dictionary object that will always be sent to AWS services,
/// even if it is empty.
/// The AWS .NET SDK does not send empty collections to services, unless
/// the collection is of this type.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
internal class AlwaysSendDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public AlwaysSendDictionary()
: base() { }
public AlwaysSendDictionary(IEqualityComparer<TKey> comparer)
: base(comparer) { }
public AlwaysSendDictionary(IDictionary<TKey, TValue> dictionary)
: base(dictionary ?? new Dictionary<TKey,TValue>()) { }
}
}
| 95 |
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 AWSSDK.Runtime.Internal.Util;
using System;
using System.Security.Cryptography;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Implementation of CRC32, using the SDK-wide
/// instance of AWS Common Runtime's checksums
/// </summary>
public class CrtCrc32 : HashAlgorithm
{
private uint _rollingResult;
public override void Initialize()
{
_rollingResult = 0;
}
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
byte[] buffer = new byte[cbSize];
Buffer.BlockCopy(array, ibStart, buffer, 0, cbSize);
_rollingResult = ChecksumCRTWrapper.Crc32(buffer, _rollingResult);
}
protected override byte[] HashFinal()
{
var result = BitConverter.GetBytes(_rollingResult);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(result);
}
return result;
}
}
}
| 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 AWSSDK.Runtime.Internal.Util;
using System;
using System.Security.Cryptography;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Implementation of CRC32C, using the SDK-wide
/// instance of AWS Common Runtime's checksums
/// </summary>
public class CrtCrc32c : HashAlgorithm
{
private uint _rollingResult;
public override void Initialize()
{
_rollingResult = 0;
}
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
byte[] buffer = new byte[cbSize];
Buffer.BlockCopy(array, ibStart, buffer, 0, cbSize);
_rollingResult = ChecksumCRTWrapper.Crc32C(buffer, _rollingResult);
}
protected override byte[] HashFinal()
{
var result = BitConverter.GetBytes(_rollingResult);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(result);
}
return result;
}
}
}
| 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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Amazon.Runtime;
namespace Amazon.Runtime.Internal.Util
{
public abstract class DecryptionWrapper : IDecryptionWrapper
{
private SymmetricAlgorithm algorithm;
private ICryptoTransform decryptor;
private const int encryptionKeySize = 256;
protected DecryptionWrapper()
{
algorithm = CreateAlgorithm();
}
#region IDecryptionWrapper Members
protected abstract SymmetricAlgorithm CreateAlgorithm();
public ICryptoTransform Transformer
{
get { return this.decryptor; }
}
public void SetDecryptionData(byte[] key, byte[] IV)
{
algorithm.KeySize = encryptionKeySize;
algorithm.Padding = PaddingMode.PKCS7;
algorithm.Mode = CipherMode.CBC;
algorithm.Key = key;
algorithm.IV = IV;
}
public void CreateDecryptor()
{
decryptor = algorithm.CreateDecryptor();
}
#endregion
}
public class DecryptionWrapperAES : DecryptionWrapper
{
public DecryptionWrapperAES()
: base()
{ }
protected override SymmetricAlgorithm CreateAlgorithm()
{
return Aes.Create();
}
}
}
| 79 |
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;
using System.IO;
using Amazon.Runtime;
using System.Security.Cryptography;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// A wrapper stream that decrypts the base stream as it
/// is being read.
/// </summary>
public abstract class DecryptStream : WrapperStream
{
#region Properties
protected CryptoStream CryptoStream { get; set; }
protected IDecryptionWrapper Algorithm { get; set; }
#endregion
#region Constructors
/// <summary>
/// Initializes an DecryptStream with an decryption algorithm and a base stream.
/// </summary>
/// <param name="baseStream">Stream to perform encryption on..</param>
protected DecryptStream(Stream baseStream)
: base(baseStream)
{
ValidateBaseStream();
}
#endregion
#region Stream overrides
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position
/// within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the
/// number of bytes requested if that many bytes are not currently available,
/// or zero (0) if the end of the stream has been reached.
/// </returns>
public override int Read(byte[] buffer, int offset, int count)
{
int result = this.CryptoStream.Read(buffer, offset, count);
return result;
}
#if AWS_ASYNC_API
/// <summary>
/// Asynchronously reads a sequence of bytes from the current stream and advances
/// the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests. The default value is
/// System.Threading.CancellationToken.None.
/// </param>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the
/// number of bytes requested if that many bytes are not currently available,
/// or zero (0) if the end of the stream has been reached.
/// </returns>
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
int result = await this.CryptoStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
return result;
}
#endif
#if BCL
public override void Close()
{
base.Close();
}
#endif
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// DecryptStream does not support seeking, this will always be false.
/// </summary>
public override bool CanSeek
{
get
{
// Restrict random access
return false;
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// DecryptStream does not support seeking, attempting to set Position
/// will throw NotSupportedException.
/// </summary>
public override long Position
{
get
{
throw new NotSupportedException("DecryptStream does not support seeking");
}
set
{
throw new NotSupportedException("DecryptStream does not support seeking");
}
}
/// <summary>
/// Sets the position within the current stream.
/// DecryptStream does not support seeking, attempting to call Seek
/// will throw NotSupportedException.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">
/// A value of type System.IO.SeekOrigin indicating the reference point used
/// to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("DecryptStream does not support seeking");
}
#endregion
#region Private methods
/// <summary>
/// Validates the underlying stream.
/// </summary>
private void ValidateBaseStream()
{
if (!BaseStream.CanRead && !BaseStream.CanWrite)
throw new InvalidDataException("DecryptStream does not support base streams that are not capable of reading or writing");
}
#endregion
}
/// <summary>
/// A wrapper stream that decrypts the base stream as it
/// is being read.
/// </summary>
public class DecryptStream<T> : DecryptStream
where T : class, IDecryptionWrapper, new()
{
#region Constructors
/// <summary>
/// Initializes an DecryptStream with an decryption algorithm and a base stream.
/// </summary>
/// <param name="baseStream">Stream to perform encryption on..</param>
/// <param name="envelopeKey">Symmetric key to perform decryption</param>
/// <param name="IV">Initialization vector to perform decryption</param>
public DecryptStream(Stream baseStream, byte[] envelopeKey, byte[] IV)
: base(baseStream)
{
Algorithm = new T();
Algorithm.SetDecryptionData(envelopeKey, IV);
Algorithm.CreateDecryptor();
CryptoStream = new CryptoStream(this.BaseStream, Algorithm.Transformer, CryptoStreamMode.Read);
}
#endregion
}
/// <summary>
/// A wrapper stream that decrypts the base stream using AES algorithm as it
/// is being read.
/// </summary>
public class AESDecryptionStream : DecryptStream<DecryptionWrapperAES>
{
#region Constructors
/// <summary>
/// Initializes an AESDecryptionStream with a base stream.
/// </summary>
/// <param name="baseStream">Stream to perform decryption on..</param>
/// <param name="key">Symmetric key to perform decryption</param>
/// <param name="IV">Initialization vector to perform decryption</param>
public AESDecryptionStream(Stream baseStream, byte[] key, byte[] IV)
: base(baseStream, key, IV) { }
#endregion
}
} | 239 |
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.Threading;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Class to perform actions on a background thread.
/// Uses a single background thread and performs actions
/// on it in the order the data was sent through the instance.
/// </summary>
internal class BackgroundDispatcher<T> : IDisposable
{
#region Properties
private bool isDisposed = false;
private Action<T> action;
private Queue<T> queue;
private Thread backgroundThread;
private AutoResetEvent resetEvent;
private bool shouldStop;
public bool IsRunning { get; private set; }
#endregion
#region Constructor/destructor
public BackgroundDispatcher(Action<T> action)
{
if (action == null)
throw new ArgumentNullException("action");
queue = new Queue<T>();
resetEvent = new AutoResetEvent(false);
shouldStop = false;
this.action = action;
backgroundThread = new Thread(Run);
backgroundThread.IsBackground = true;
backgroundThread.Start();
}
~BackgroundDispatcher()
{
Stop();
this.Dispose(false);
}
#endregion
#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.isDisposed)
{
if (disposing && resetEvent != null)
{
#if NETSTANDARD
resetEvent.Dispose();
#else
resetEvent.Close();
#endif
resetEvent = null;
}
this.isDisposed = true;
}
}
/// <summary>
/// Disposes of all managed and unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Public Methods
const int MAX_QUEUE_SIZE = 100;
public void Dispatch(T data)
{
if (queue.Count < MAX_QUEUE_SIZE)
{
lock (queue)
{
if (queue.Count < MAX_QUEUE_SIZE)
queue.Enqueue(data);
}
}
resetEvent.Set();
}
public void Stop()
{
shouldStop = true;
resetEvent.Set();
}
#endregion
#region Private methods
private void Run()
{
IsRunning = true;
while (!shouldStop)
{
HandleInvoked();
resetEvent.WaitOne();
}
HandleInvoked();
IsRunning = false;
}
private void HandleInvoked()
{
while (true)
{
bool dataPresent = false;
T data = default(T);
lock (queue)
{
if (queue.Count > 0)
{
data = queue.Dequeue();
dataPresent = true;
}
}
if (!dataPresent)
break;
try
{
action(data);
}
catch { }
}
}
#endregion
}
/// <summary>
/// Class to invoke actions on a background thread.
/// Uses a single background thread and invokes actions
/// on it in the order they were invoked through the instance.
/// </summary>
internal class BackgroundInvoker : BackgroundDispatcher<Action>
{
public BackgroundInvoker()
: base(action => action())
{
}
}
}
| 185 |
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.IO;
using System.Security.Cryptography;
namespace Amazon.Runtime.Internal.Util
{
public abstract class EncryptionWrapper : IEncryptionWrapper
{
private SymmetricAlgorithm algorithm;
private ICryptoTransform encryptor;
private const int encryptionKeySize = 256;
protected EncryptionWrapper()
{
algorithm = CreateAlgorithm();
}
protected abstract SymmetricAlgorithm CreateAlgorithm();
#region IEncryptionWrapper Members
public int AppendBlock(byte[] buffer, int offset, int count, byte[] target, int targetOffset)
{
int bytesRead = encryptor.TransformBlock(buffer, offset, count, target, targetOffset);
return bytesRead;
}
public byte[] AppendLastBlock(byte[] buffer, int offset, int count)
{
byte[] finalTransform = encryptor.TransformFinalBlock(buffer, offset, count);
return finalTransform;
}
public void CreateEncryptor()
{
encryptor = algorithm.CreateEncryptor();
}
public void SetEncryptionData(byte[] key, byte[] IV)
{
algorithm.KeySize = encryptionKeySize;
algorithm.Padding = PaddingMode.PKCS7;
algorithm.Mode = CipherMode.CBC;
algorithm.Key = key;
algorithm.IV = IV;
}
public void Reset()
{
CreateEncryptor();
}
#endregion
}
public class EncryptionWrapperAES : EncryptionWrapper
{
public EncryptionWrapperAES()
: base() { }
protected override SymmetricAlgorithm CreateAlgorithm()
{
return Aes.Create();
}
}
}
| 88 |
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;
using System.IO;
using Amazon.Runtime;
using System.Collections;
using System.Diagnostics;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// A wrapper stream that encrypts the base stream as it
/// is being read.
/// </summary>
public abstract class EncryptStream : WrapperStream
{
#region Properties
protected IEncryptionWrapper Algorithm { get; set; }
private const int internalEncryptionBlockSize = 16;
private byte[] internalBuffer;
private bool performedLastBlockTransform;
#endregion
#region Constructors
/// <summary>
/// Initializes an EncryptStream with an encryption algorithm and a base stream.
/// </summary>
/// <param name="baseStream">Stream to perform encryption on..</param>
protected EncryptStream(Stream baseStream)
: base(baseStream)
{
performedLastBlockTransform = false;
internalBuffer = new byte[internalEncryptionBlockSize];
ValidateBaseStream();
}
#endregion
#region Stream overrides
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position
/// within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the
/// number of bytes requested if that many bytes are not currently available,
/// or zero (0) if the end of the stream has been reached.
/// </returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (performedLastBlockTransform)
return 0;
long previousPosition = this.Position;
int maxBytesRead = count - (count % internalEncryptionBlockSize);
int readBytes = base.Read(buffer, offset, maxBytesRead);
return Append(buffer, offset, previousPosition, readBytes);
}
#if AWS_ASYNC_API
/// <summary>
/// Asynchronously reads a sequence of bytes from the current stream, advances
/// the position within the stream by the number of bytes read, and monitors
/// cancellation requests.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests. The default value is
/// System.Threading.CancellationToken.None.
/// </param>
/// <returns>
/// A task that represents the asynchronous read operation. The value of the TResult
/// parameter contains the total number of bytes read into the buffer. This can be
/// less than the number of bytes requested if that many bytes are not currently
/// available, or zero (0) if the end of the stream has been reached.
/// </returns>
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (performedLastBlockTransform)
return 0;
long previousPosition = this.Position;
int maxBytesRead = count - (count % internalEncryptionBlockSize);
int readBytes = await base.ReadAsync(buffer, offset, maxBytesRead, cancellationToken).ConfigureAwait(false);
return Append(buffer, offset, previousPosition, readBytes);
}
#endif
private int Append(byte[] buffer, int offset, long previousPosition, int readBytes)
{
if (readBytes == 0)
{
byte[] finalBytes = Algorithm.AppendLastBlock(buffer, offset, 0);
finalBytes.CopyTo(buffer, offset);
performedLastBlockTransform = true;
return finalBytes.Length;
}
long currentPosition = previousPosition;
while (this.Position - currentPosition >= internalEncryptionBlockSize)
{
currentPosition += Algorithm.AppendBlock(buffer, offset, internalEncryptionBlockSize, internalBuffer, 0);
Buffer.BlockCopy(internalBuffer, 0, buffer, offset, internalEncryptionBlockSize);
offset = offset + internalEncryptionBlockSize;
}
if ((this.Length - this.Position) < internalEncryptionBlockSize)
{
byte[] finalBytes = Algorithm.AppendLastBlock(buffer, offset, (int)(this.Position - currentPosition));
finalBytes.CopyTo(buffer, offset);
currentPosition += finalBytes.Length;
performedLastBlockTransform = true;
}
return (int)(currentPosition - previousPosition);
}
#if BCL
public override void Close()
{
base.Close();
}
#endif
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
public override bool CanSeek
{
get
{
return true;
}
}
/// <summary>
/// Returns encrypted content length.
/// </summary>
public override long Length
{
get
{
if (base.Length % internalEncryptionBlockSize == 0)
{
return (base.Length + internalEncryptionBlockSize);
}
else
{
return (base.Length + internalEncryptionBlockSize - (base.Length % internalEncryptionBlockSize));
}
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// </summary>
public override long Position
{
get
{
return BaseStream.Position;
}
set
{
Seek(offset: value, origin: SeekOrigin.Begin);
}
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">
/// A value of type System.IO.SeekOrigin indicating the reference point used
/// to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
long position = BaseStream.Seek(offset, origin);
this.performedLastBlockTransform = false;
this.Algorithm.Reset();
return position;
}
#endregion
#region Private methods
/// <summary>
/// Validates the underlying stream.
/// </summary>
private void ValidateBaseStream()
{
if (!BaseStream.CanRead && !BaseStream.CanWrite)
throw new InvalidDataException("EncryptStream does not support base streams that are not capable of reading or writing");
}
#endregion
}
/// <summary>
/// A wrapper stream that encrypts the base stream as it
/// is being read.
/// </summary>
public class EncryptStream<T> : EncryptStream
where T : class, IEncryptionWrapper, new()
{
#region Constructors
/// <summary>
/// Initializes an EncryptStream with an encryption algorithm and a base stream.
/// </summary>
/// <param name="baseStream">Stream to perform encryption on..</param>
/// <param name="key">Symmetric key to perform encryption</param>
/// <param name="IV">Initialization vector to perform encryption</param>
public EncryptStream(Stream baseStream, byte[] key, byte[] IV)
: base(baseStream)
{
Algorithm = new T();
Algorithm.SetEncryptionData(key, IV);
Algorithm.CreateEncryptor();
}
#endregion
}
/// <summary>
/// A wrapper stream that encrypts the base stream using AES algorithm as it
/// is being read.
/// </summary>
public class AESEncryptionPutObjectStream : EncryptStream<EncryptionWrapperAES>
{
#region Constructors
/// <summary>
/// Initializes an AESEncryptionStream with a base stream.
/// </summary>
/// <param name="baseStream">Stream to perform encryption on..</param>
/// <param name="key">Symmetric key to perform encryption</param>
/// <param name="IV">Initialization vector to perform encryption</param>
public AESEncryptionPutObjectStream(Stream baseStream, byte[] key, byte[] IV)
: base(baseStream, key, IV) { }
#endregion
}
} | 302 |
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;
using System.IO;
using Amazon.Runtime;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// A wrapper stream that encrypts the base stream as it
/// is being read.
/// </summary>
public abstract class EncryptUploadPartStream : WrapperStream
{
#region Properties
protected IEncryptionWrapper Algorithm { get; set; }
private byte[] internalBuffer;
public byte[] InitializationVector { get; protected set; }
internal const int InternalEncryptionBlockSize = 16;
#endregion
#region Constructors
/// <summary>
/// Initializes an EncryptStream for Multipart uploads with an encryption algorithm and a base stream.
/// </summary>
/// <param name="baseStream">Stream to perform encryption on..</param>
protected EncryptUploadPartStream(Stream baseStream)
: base(baseStream)
{
internalBuffer = new byte[InternalEncryptionBlockSize];
InitializationVector = new byte[InternalEncryptionBlockSize];
ValidateBaseStream();
}
#endregion
#region Stream overrides
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position
/// within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the
/// number of bytes requested if that many bytes are not currently available,
/// or zero (0) if the end of the stream has been reached.
/// </returns>
public override int Read(byte[] buffer, int offset, int count)
{
int readBytes = base.Read(buffer, offset, count);
return Append(buffer, offset, readBytes);
}
#if AWS_ASYNC_API
/// <summary>
/// Asynchronously reads a sequence of bytes from the current stream, advances
/// the position within the stream by the number of bytes read, and monitors
/// cancellation requests.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests. The default value is
/// System.Threading.CancellationToken.None.
/// </param>
/// <returns>
/// A task that represents the asynchronous read operation. The value of the TResult
/// parameter contains the total number of bytes read into the buffer. This can be
/// less than the number of bytes requested if that many bytes are not currently
/// available, or zero (0) if the end of the stream has been reached.
/// </returns>
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
int readBytes = await base.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
return Append(buffer, offset, readBytes);
}
#endif
private int Append(byte[] buffer, int offset, int readBytes)
{
if (readBytes == 0)
return 0;
int numBytesRead = 0;
while (numBytesRead < readBytes)
{
numBytesRead += Algorithm.AppendBlock(buffer, offset, InternalEncryptionBlockSize, internalBuffer, 0);
Buffer.BlockCopy(internalBuffer, 0, buffer, offset, InternalEncryptionBlockSize);
offset = offset + InternalEncryptionBlockSize;
}
Buffer.BlockCopy(buffer, numBytesRead - InternalEncryptionBlockSize, InitializationVector, 0, InternalEncryptionBlockSize);
return numBytesRead;
}
#if BCL
public override void Close()
{
base.Close();
}
#endif
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
public override bool CanSeek
{
get
{
return true;
}
}
/// <summary>
/// Returns encrypted content length.
/// </summary>
public override long Length
{
get
{
if (base.Length % InternalEncryptionBlockSize == 0)
{
return (base.Length);
}
else
{
return (base.Length + InternalEncryptionBlockSize - (base.Length % InternalEncryptionBlockSize));
}
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// </summary>
public override long Position
{
get
{
return BaseStream.Position;
}
set
{
Seek(offset: value, origin: SeekOrigin.Begin);
}
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">
/// A value of type System.IO.SeekOrigin indicating the reference point used
/// to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
long position = BaseStream.Seek(offset, origin);
this.Algorithm.Reset();
return position;
}
#endregion
#region Private methods
/// <summary>
/// Validates the underlying stream.
/// </summary>
private void ValidateBaseStream()
{
if (!BaseStream.CanRead && !BaseStream.CanWrite)
throw new InvalidDataException("EncryptStreamForUploadPart does not support base streams that are not capable of reading or writing");
}
#endregion
}
/// <summary>
/// A wrapper stream that encrypts the base stream as it
/// is being read.
/// </summary>
public class EncryptUploadPartStream<T> : EncryptUploadPartStream
where T : class, IEncryptionWrapper, new()
{
#region Constructors
/// <summary>
/// Initializes an EncryptStream with an encryption algorithm and a base stream.
/// </summary>
/// <param name="baseStream">Stream to perform encryption on..</param>
/// <param name="key">Symmetric key to perform encryption</param>
/// <param name="IV">Initialization vector to perform encryption</param>
public EncryptUploadPartStream(Stream baseStream, byte[] key, byte[] IV)
: base(baseStream)
{
Algorithm = new T();
Algorithm.SetEncryptionData(key, IV);
Algorithm.CreateEncryptor();
}
#endregion
}
/// <summary>
/// A wrapper stream that encrypts the base stream as it
/// is being read.
/// </summary>
public class AESEncryptionUploadPartStream : EncryptUploadPartStream<EncryptionWrapperAES>
{
#region Constructors
/// <summary>
/// Initializes an AESEncryptionStream with a base stream.
/// </summary>
/// <param name="baseStream">Stream to perform encryption on..</param>
/// <param name="key">Symmetric key to perform encryption</param>
/// <param name="IV">Initialization vector to perform encryption</param>
public AESEncryptionUploadPartStream(Stream baseStream, byte[] key, byte[] IV)
: base(baseStream, key, IV) { }
#endregion
}
} | 274 |
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 System.Linq;
using System.Text;
using System.Threading;
#if AWS_ASYNC_API
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal.Util
{
internal class EventStream : WrapperStream
{
internal delegate void ReadProgress(int bytesRead);
internal event ReadProgress OnRead;
bool disableClose;
//Stream wrappedStream;
internal EventStream(Stream stream, bool disableClose)
: base(stream)
{
//this.wrappedStream = stream;
this.disableClose = disableClose;
}
protected override void Dispose(bool disposing)
{
}
public override bool CanRead
{
get { return BaseStream.CanRead; }
}
public override bool CanSeek
{
get { return BaseStream.CanSeek; }
}
public override bool CanTimeout
{
get { return BaseStream.CanTimeout; }
}
public override bool CanWrite
{
get { return BaseStream.CanWrite; }
}
public override long Length
{
get { return BaseStream.Length; }
}
public override long Position
{
get { return BaseStream.Position; }
set { BaseStream.Position = value; }
}
public override int ReadTimeout
{
get { return BaseStream.ReadTimeout; }
set { BaseStream.ReadTimeout = value; }
}
public override int WriteTimeout
{
get { return BaseStream.WriteTimeout; }
set { BaseStream.WriteTimeout = value; }
}
public override void Flush()
{
BaseStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
int bytesRead = BaseStream.Read(buffer, offset, count);
if (this.OnRead != null)
{
this.OnRead(bytesRead);
}
return bytesRead;
}
public override long Seek(long offset, SeekOrigin origin)
{
return BaseStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
BaseStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override void WriteByte(byte value)
{
throw new NotImplementedException();
}
#if AWS_ASYNC_API
public override Task FlushAsync(CancellationToken cancellationToken)
{
return BaseStream.FlushAsync(cancellationToken);
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
int bytesRead = await BaseStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
if (this.OnRead != null)
{
this.OnRead(bytesRead);
}
return bytesRead;
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
#endif
#if !NETSTANDARD
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
var result = new AsyncResult()
{
AsyncState = state,
CompletedSynchronously = true,
IsCompleted = true,
AsyncWaitHandle = new ManualResetEvent(true)
};
try
{
int bytesRead = this.Read(buffer, offset, count);
result.Return = bytesRead;
}
catch (Exception e)
{
result.Return = e;
}
if (callback != null)
callback(result);
return result;
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
throw new NotImplementedException();
}
public override void Close()
{
if (!disableClose)
{
BaseStream.Close();
}
}
public override int EndRead(IAsyncResult asyncResult)
{
var result = asyncResult as AsyncResult;
if (result == null)
throw new ArgumentException("Parameter asyncResult was not of type Amazon.Runtime.Internal.Util.AsyncResult", "asyncResult");
if (result.Return is Exception)
throw (Exception)result.Return;
return Convert.ToInt32(result.Return, CultureInfo.InvariantCulture);
}
public override void EndWrite(IAsyncResult asyncResult)
{
throw new NotImplementedException();
}
class AsyncResult : IAsyncResult
{
public object AsyncState { get; internal set; }
public WaitHandle AsyncWaitHandle { get; internal set; }
public bool CompletedSynchronously { get; internal set; }
public bool IsCompleted { get; internal set; }
internal object Return { get; set; }
}
#endif
}
}
| 220 |
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.Net;
namespace AWSSDK.Runtime.Internal.Util
{
internal static class ExceptionUtils
{
internal static HttpStatusCode? DetermineHttpStatusCode(Exception e)
{
var response = (e as WebException)?.Response as HttpWebResponse;
if (response != null)
{
return response.StatusCode;
}
#if !BCL35
var requestException = e as System.Net.Http.HttpRequestException;
if (requestException?.Data?.Contains("StatusCode") == true)
{
return (HttpStatusCode)requestException.Data["StatusCode"];
}
#endif
if (e?.InnerException != null)
{
return DetermineHttpStatusCode(e.InnerException);
}
return null;
}
internal static bool IsInnerException<T>(Exception exception)
where T : Exception
{
T innerException;
return IsInnerException<T>(exception, out innerException);
}
internal static bool IsInnerException<T>(Exception exception, out T inner)
where T : Exception
{
inner = null;
Queue<Exception> queue = new Queue<Exception>();
//Modified BFS for the specific exception type
var currentException = exception;
do
{
//When queue.Count == 0 this is the initial parent queue item
//which will not be checked for the exception of type T.
if(queue.Count > 0)
{
currentException = queue.Dequeue();
inner = currentException as T;
if (inner != null)
{
return true;
}
}
#if !BCL35
var aggregateException = currentException as AggregateException;
if (aggregateException != null)
{
foreach (var e in aggregateException.InnerExceptions)
{
queue.Enqueue(e);
}
continue;
}
#endif
if (currentException.InnerException != null)
{
queue.Enqueue(currentException.InnerException);
}
}
while (queue.Count > 0);
return false;
}
}
}
| 99 |
aws-sdk-net | aws | C# | using Amazon.Util;
/*
* 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;
using System.Text;
using System.Threading;
namespace Amazon.Runtime.Internal.Util
{
public static partial class Extensions
{
private static readonly long TicksPerSecond = TimeSpan.FromSeconds(1).Ticks;
private static readonly double TickFrequency = TicksPerSecond / (double)Stopwatch.Frequency;
public static long GetElapsedDateTimeTicks(this Stopwatch self)
{
double stopwatchTicks = self.ElapsedTicks;
var ticks = (long)(stopwatchTicks * TickFrequency);
return ticks;
}
/// <summary>
/// Returns true if the Content is set or there are
/// query parameters.
/// </summary>
/// <param name="request">This request</param>
/// <returns>True if data is present; false otherwise.</returns>
public static bool HasRequestData(this IRequest request)
{
if (request == null)
return false;
if (request.ContentStream != null || request.Content != null)
return true;
return request.Parameters.Count > 0;
}
#if BCL35
public static bool Wait(this WaitHandle semaphore)
{
return semaphore.WaitOne();
}
public static void Dispose(this WaitHandle semaphore)
{
semaphore.Close();
}
#endif
}
}
| 64 |
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.Internal.Util
{
/// <summary>
/// Utilities for dealing with Guids
/// </summary>
public static class GuidUtils
{
public static bool TryParseNullableGuid(string value, out Guid? result)
{
Guid guid;
if (TryParseGuid(value, out guid))
{
result = guid;
return true;
}
else
{
result = null;
return false;
}
}
public static bool TryParseGuid(string value, out Guid result)
{
try
{
result = new Guid(value);
return true;
}
catch (Exception)
{
result = Guid.Empty;
return false;
}
}
}
}
| 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.Collections.Generic;
using System.Linq;
namespace Amazon.Runtime.Internal.Util
{
public static class Hashing
{
/// <summary>
/// Hashes a set of objects.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int Hash(params object[] value)
{
var hashes = value
.Select(v => v == null ? 0 : v.GetHashCode())
.ToArray();
var result = CombineHashes(hashes);
return result;
}
/// <summary>
/// Combines a set of hashses.
/// </summary>
/// <param name="hashes"></param>
/// <returns></returns>
public static int CombineHashes(params int[] hashes)
{
int result = 0;
foreach (int hash in hashes)
{
result = CombineHashesInternal(result, hash);
}
return result;
}
/// <summary>
/// Combines two hashes.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
private static int CombineHashesInternal(int a, int b)
{
return unchecked(((a << 5) + a) ^ b);
}
}
}
| 64 |
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.Util;
using System;
using System.Security.Cryptography;
namespace Amazon.Runtime.Internal.Util
{
public partial class HashingWrapper : IHashingWrapper
{
public HashingWrapper(string algorithmName)
{
if (string.IsNullOrEmpty(algorithmName))
throw new ArgumentNullException("algorithmName");
Init(algorithmName);
}
public HashingWrapper(HashAlgorithm algorithm)
{
_algorithm = algorithm;
}
#region IHashingWrapper Members
public void AppendBlock(byte[] buffer)
{
AppendBlock(buffer, 0, buffer.Length);
}
public byte[] AppendLastBlock(byte[] buffer)
{
return AppendLastBlock(buffer, 0, buffer.Length);
}
#endregion
#region Dispose Pattern Implementation
/// <summary>
/// Disposes of all managed and unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
public class HashingWrapperCRC32C : HashingWrapper
{
public HashingWrapperCRC32C()
: base(CryptoUtilFactory.GetChecksumInstance(CoreChecksumAlgorithm.CRC32C))
{ }
}
public class HashingWrapperCRC32 : HashingWrapper
{
public HashingWrapperCRC32()
: base(CryptoUtilFactory.GetChecksumInstance(CoreChecksumAlgorithm.CRC32))
{ }
}
public class HashingWrapperSHA256 : HashingWrapper
{
public HashingWrapperSHA256()
: base(CryptoUtilFactory.GetChecksumInstance(CoreChecksumAlgorithm.SHA256))
{ }
}
public class HashingWrapperSHA1 : HashingWrapper
{
public HashingWrapperSHA1()
: base(CryptoUtilFactory.GetChecksumInstance(CoreChecksumAlgorithm.SHA1))
{ }
}
}
| 97 |
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 Amazon.Util.Internal;
using System;
using System.IO;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// A wrapper stream that calculates a hash of the base stream as it
/// is being read.
/// The calculated hash is only available after the stream is closed or
/// CalculateHash is called. After calling CalculateHash, any further reads
/// on the streams will not change the CalculatedHash.
/// If an ExpectedHash is specified and is not equal to the calculated hash,
/// Close or CalculateHash methods will throw an AmazonClientException.
/// If CalculatedHash is calculated for only the portion of the stream that
/// is read.
/// </summary>
/// <exception cref="Amazon.Runtime.AmazonClientException">
/// Exception thrown during Close() or CalculateHash(), if ExpectedHash is set and
/// is different from CalculateHash that the stream calculates, provided that
/// CalculatedHash is not a zero-length byte array.
/// </exception>
public abstract class HashStream : WrapperStream
{
#region Properties
/// <summary>
/// Algorithm to use to calculate hash.
/// </summary>
protected IHashingWrapper Algorithm { get; set; }
/// <summary>
/// True if hashing is finished and no more hashing should be done;
/// otherwise false.
/// </summary>
protected bool FinishedHashing { get { return CalculatedHash != null; } }
/// <summary>
/// Current position in the stream.
/// </summary>
protected long CurrentPosition { get; private set; }
/// <summary>
/// Calculated hash for the stream.
/// This value is set only after the stream is closed.
/// </summary>
public byte[] CalculatedHash { get; protected set; }
/// <summary>
/// Expected hash value. Compared against CalculatedHash upon Close().
/// If the hashes are different, an AmazonClientException is thrown.
/// </summary>
public byte[] ExpectedHash { get; private set; }
/// <summary>
/// Expected length of stream.
/// </summary>
public long ExpectedLength { get; protected set; }
#endregion
#region Constructors
///// <summary>
///// Initializes an HashStream with a hash algorithm and a base stream.
///// </summary>
///// <param name="baseStream">Stream to calculate hash for.</param>
//protected HashStream(Stream baseStream)
// : this(baseStream, null) { }
/// <summary>
/// Initializes an HashStream with a hash algorithm and a base stream.
/// </summary>
/// <param name="baseStream">Stream to calculate hash for.</param>
/// <param name="expectedHash">
/// Expected hash. Will be compared against calculated hash on stream close.
/// Pass in null to disable check.
/// </param>
/// <param name="expectedLength">
/// Expected length of the stream. If the reading stops before reaching this
/// position, CalculatedHash will be set to empty array.
/// </param>
protected HashStream(Stream baseStream, byte[] expectedHash, long expectedLength)
: base(baseStream)
{
ExpectedHash = expectedHash;
ExpectedLength = expectedLength;
ValidateBaseStream();
Reset();
}
#endregion
#region Stream overrides
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position
/// within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the
/// number of bytes requested if that many bytes are not currently available,
/// or zero (0) if the end of the stream has been reached.
/// </returns>
public override int Read(byte[] buffer, int offset, int count)
{
int result = base.Read(buffer, offset, count);
CurrentPosition += result;
if (!FinishedHashing)
{
Algorithm.AppendBlock(buffer, offset, result);
}
// Calculate the hash if this was the final read
if (result == 0)
{
CalculateHash();
}
return result;
}
#if AWS_ASYNC_API
/// <summary>
/// Asynchronously reads a sequence of bytes from the current stream, advances
/// the position within the stream by the number of bytes read, and monitors
/// cancellation requests.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests. The default value is
/// System.Threading.CancellationToken.None.
/// </param>
/// <returns>
/// A task that represents the asynchronous read operation. The value of the TResult
/// parameter contains the total number of bytes read into the buffer. This can be
/// less than the number of bytes requested if that many bytes are not currently
/// available, or zero (0) if the end of the stream has been reached.
/// </returns>
public async override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
int result = await base.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
CurrentPosition += result;
if (!FinishedHashing)
{
Algorithm.AppendBlock(buffer, offset, result);
}
// Calculate the hash if this was the final read
if (result == 0)
{
CalculateHash();
}
return result;
}
#endif
#if !NETSTANDARD
/// <summary>
/// Closes the underlying stream and finishes calculating the hash.
/// If an ExpectedHash is specified and is not equal to the calculated hash,
/// this method will throw an AmazonClientException.
/// </summary>
/// <exception cref="Amazon.Runtime.AmazonClientException">
/// If ExpectedHash is set and is different from CalculateHash that the stream calculates.
/// </exception>
public override void Close()
{
CalculateHash();
base.Close();
}
#endif
protected override void Dispose(bool disposing)
{
try
{
CalculateHash();
if (disposing && Algorithm != null)
{
Algorithm.Dispose();
Algorithm = null;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// HashStream does not support seeking, this will always be false.
/// </summary>
public override bool CanSeek
{
get
{
// Restrict random access, as this will break hashing.
return false;
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// HashStream does not support seeking, attempting to set Position
/// will throw NotSupportedException.
/// </summary>
public override long Position
{
get
{
throw new NotSupportedException("HashStream does not support seeking");
}
set
{
// Restrict random access, as this will break hashing.
throw new NotSupportedException("HashStream does not support seeking");
}
}
/// <summary>
/// Sets the position within the current stream.
/// HashStream does not support seeking, attempting to call Seek
/// will throw NotSupportedException.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">
/// A value of type System.IO.SeekOrigin indicating the reference point used
/// to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
// Restrict random access, as this will break hashing.
throw new NotSupportedException("HashStream does not support seeking");
}
/// <summary>
/// Gets the overridden length used to construct the HashStream
/// </summary>
public override long Length
{
get
{
return this.ExpectedLength;
}
}
#endregion
#region Public methods
/// <summary>
/// Calculates the hash for the stream so far and disables any further
/// hashing.
/// </summary>
public virtual void CalculateHash()
{
if (!FinishedHashing)
{
if (ExpectedLength < 0 || CurrentPosition == ExpectedLength)
{
CalculatedHash = Algorithm.AppendLastBlock(ArrayEx.Empty<byte>());
}
else
CalculatedHash = ArrayEx.Empty<byte>();
if (CalculatedHash.Length > 0 && ExpectedHash != null && ExpectedHash.Length > 0)
{
if (!CompareHashes(ExpectedHash, CalculatedHash))
throw new AmazonClientException("Expected hash not equal to calculated hash");
}
}
}
/// <summary>
/// Resets the hash stream to starting state.
/// Use this if the underlying stream has been modified and needs
/// to be rehashed without reconstructing the hierarchy.
/// </summary>
public void Reset()
{
CurrentPosition = 0;
CalculatedHash = null;
if (Algorithm != null)
Algorithm.Clear();
var baseHashStream = BaseStream as HashStream;
if (baseHashStream != null)
{
baseHashStream.Reset();
}
}
#endregion
#region Private methods
/// <summary>
/// Validates the underlying stream.
/// </summary>
private void ValidateBaseStream()
{
// Fast-fail on unusable streams
if (!BaseStream.CanRead && !BaseStream.CanWrite)
throw new InvalidDataException("HashStream does not support base streams that are not capable of reading or writing");
}
/// <summary>
/// Compares two hashes (arrays of bytes).
/// </summary>
/// <param name="expected">Expected hash.</param>
/// <param name="actual">Actual hash.</param>
/// <returns>
/// True if the hashes are identical; otherwise false.
/// </returns>
protected static bool CompareHashes(byte[] expected, byte[] actual)
{
if (ReferenceEquals(expected, actual))
return true;
if (expected == null || actual == null)
return (expected == actual);
if (expected.Length != actual.Length)
return false;
for (int i = 0; i < expected.Length; i++)
{
if (expected[i] != actual[i])
return false;
}
return true;
}
#endregion
}
/// <summary>
/// A wrapper stream that calculates a hash of the base stream as it
/// is being read or written.
/// The calculated hash is only available after the stream is closed or
/// CalculateHash is called. After calling CalculateHash, any further reads
/// on the streams will not change the CalculatedHash.
/// If an ExpectedHash is specified and is not equal to the calculated hash,
/// Close or CalculateHash methods will throw an AmazonClientException.
/// If base stream's position is not 0 or HashOnReads is true and the entire stream is
/// not read, the CalculatedHash will be set to an empty byte array and
/// comparison to ExpectedHash will not be made.
/// </summary>
/// <exception cref="Amazon.Runtime.AmazonClientException">
/// Exception thrown during Close() or CalculateHash(), if ExpectedHash is set and
/// is different from CalculateHash that the stream calculates, provided that
/// CalculatedHash is not a zero-length byte array.
/// </exception>
public class HashStream<T> : HashStream
where T : IHashingWrapper, new()
{
#region Constructors
/// <summary>
/// Initializes an HashStream with a hash algorithm and a base stream.
/// </summary>
/// <param name="baseStream">Stream to calculate hash for.</param>
/// <param name="expectedHash">
/// Expected hash. Will be compared against calculated hash on stream close.
/// Pass in null to disable check.
/// </param>
/// <param name="expectedLength">
/// Expected length of the stream. If the reading stops before reaching this
/// position, CalculatedHash will be set to empty array.
/// </param>
public HashStream(Stream baseStream, byte[] expectedHash, long expectedLength)
: base(baseStream, expectedHash, expectedLength)
{
Algorithm = new T();
}
#endregion
}
/// <summary>
/// A wrapper stream that calculates an MD5 hash of the base stream as it
/// is being read or written.
/// The calculated hash is only available after the stream is closed or
/// CalculateHash is called. After calling CalculateHash, any further reads
/// on the streams will not change the CalculatedHash.
/// If an ExpectedHash is specified and is not equal to the calculated hash,
/// Close or CalculateHash methods will throw an AmazonClientException.
/// If base stream's position is not 0 or HashOnReads is true and the entire stream is
/// not read, the CalculatedHash will be set to an empty byte array and
/// comparison to ExpectedHash will not be made.
/// </summary>
/// <exception cref="Amazon.Runtime.AmazonClientException">
/// Exception thrown during Close() or CalculateHash(), if ExpectedHash is set and
/// is different from CalculateHash that the stream calculates, provided that
/// CalculatedHash is not a zero-length byte array.
/// </exception>
public class MD5Stream : HashStream<HashingWrapperMD5>
{
private Logger _logger;
#region Constructors
/// <summary>
/// Initializes an MD5Stream with a base stream.
/// </summary>
/// <param name="baseStream">Stream to calculate hash for.</param>
/// <param name="expectedHash">
/// Expected hash. Will be compared against calculated hash on stream close.
/// Pass in null to disable check.
/// </param>
/// <param name="expectedLength">
/// Expected length of the stream. If the reading stops before reaching this
/// position, CalculatedHash will be set to empty array.
/// </param>
public MD5Stream(Stream baseStream, byte[] expectedHash, long expectedLength)
: base(baseStream, expectedHash, expectedLength)
{
_logger = Logger.GetLogger(this.GetType());
}
#endregion
}
}
| 478 |
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.Text;
using System.IO;
using Amazon.Util;
using System.Text.RegularExpressions;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Utilities for validating label values for host prefix templates
/// </summary>
public static class HostPrefixUtils
{
private static Regex labelValidationRegex = new Regex(@"^[A-Za-z0-9\-]+$", RegexOptions.Compiled | RegexOptions.Singleline);
/// <summary>
/// Validates a label value
/// </summary>
public static bool IsValidLabelValue(String value)
{
// Make sure value is not null or empty
if (string.IsNullOrEmpty(value))
return false;
// Check if the value is between 1 and 63 characters
if (value.Length < 1 || value.Length > 63)
return false;
// Check that the value only contains:
// uppercase letters, lowercase letters, numbers,
// dashes (-)
if (!labelValidationRegex.IsMatch(value))
return false;
return true;
}
}
}
| 57 |
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.IO;
using System.Security.Cryptography;
namespace Amazon.Runtime.Internal.Util
{
public interface IDecryptionWrapper
{
ICryptoTransform Transformer { get;}
void SetDecryptionData(byte[] key, byte[] IV);
void CreateDecryptor();
}
}
| 33 |
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.IO;
using System.Security.Cryptography;
namespace Amazon.Runtime.Internal.Util
{
public interface IEncryptionWrapper
{
void Reset();
int AppendBlock(byte[] buffer, int offset, int count, byte[] target, int targetOffset);
byte[] AppendLastBlock(byte[] buffer, int offset, int count);
void SetEncryptionData(byte[] key, byte[] IV);
void CreateEncryptor();
}
}
| 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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.IO;
namespace Amazon.Runtime.Internal.Util
{
public interface IHashingWrapper : IDisposable
{
void Clear();
byte[] ComputeHash(byte[] buffer);
byte[] ComputeHash(Stream stream);
void AppendBlock(byte[] buffer);
void AppendBlock(byte[] buffer, int offset, int count);
byte[] AppendLastBlock(byte[] buffer);
byte[] AppendLastBlock(byte[] buffer, int offset, int count);
}
}
| 36 |
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.Internal.Util
{
public interface ILogger
{
void InfoFormat(string messageFormat, params object[] args);
void Debug(Exception exception, string messageFormat, params object[] args);
void DebugFormat(string messageFormat, params object[] args);
void Error(Exception exception, string messageFormat, params object[] args);
void Flush();
}
}
| 29 |
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 System.Text.RegularExpressions;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Provides read/write access to a file in the INI format.
///
/// This class is not threadsafe.
/// </summary>
public class IniFile
{
private const string sectionNamePrefix = "[";
private const string sectionNameSuffix = "]";
private const string keyValueSeparator = "=";
private const string semiColonComment = ";";
private const string hashComment = "#";
private OptimisticLockedTextFile textFile;
private Logger logger;
/// <summary>
/// Construct a new IniFile.
/// </summary>
/// <param name="filePath">path of the IniFile</param>
public IniFile(string filePath)
{
logger = Logger.GetLogger(GetType());
textFile = new OptimisticLockedTextFile(filePath);
Validate();
}
/// <summary>
/// the path of the file
/// </summary>
public String FilePath
{
get
{
return textFile.FilePath;
}
}
/// <summary>
/// helper to access the lines of the file
/// </summary>
private List<string> Lines
{
get
{
return textFile.Lines;
}
}
/// <summary>
/// Persist the changes to this INI file to disk.
/// </summary>
public void Persist()
{
Validate();
textFile.Persist();
}
/// <summary>
/// Rename the section fromSectionName to toSectionName
/// </summary>
/// <param name="oldSectionName"></param>
/// <param name="newSectionName"></param>
public void RenameSection(string oldSectionName, string newSectionName)
{
RenameSection(oldSectionName, newSectionName, false);
}
/// <summary>
/// Rename the section fromSectionName to toSectionName
/// </summary>
/// <param name="oldSectionName"></param>
/// <param name="newSectionName"></param>
/// <param name="force">if true and destination section already exists overwrite it</param>
public void RenameSection(string oldSectionName, string newSectionName, bool force)
{
int sectionLineNumber = 0;
if (TrySeekSection(oldSectionName, ref sectionLineNumber))
{
int lineNumber = 0;
if (TrySeekSection(newSectionName, ref lineNumber))
{
// if oldSectionName == newSectionName it's a no op
if (!string.Equals(oldSectionName, newSectionName, StringComparison.Ordinal))
{
if (force)
{
DeleteSection(newSectionName);
// recursive call with force == false now that the destination section is gone
RenameSection(oldSectionName, newSectionName, false);
}
else
throw new ArgumentException("Cannot rename section. The destination section " + newSectionName +
" already exists." + GetLineMessage(lineNumber));
}
}
else
Lines[sectionLineNumber] = sectionNamePrefix + newSectionName + sectionNameSuffix;
}
else
throw new ArgumentException("Cannot rename section. The source section " + oldSectionName + " does not exist.");
}
/// <summary>
/// Copy the section fromSectionName to toSectionName
/// </summary>
/// <param name="fromSectionName"></param>
/// <param name="toSectionName"></param>
/// <param name="replaceProperties">Any properties in the original section that are also in this dictionary will
/// be replaced by the value from this dictionary.</param>
public void CopySection(string fromSectionName, string toSectionName, Dictionary<string, string> replaceProperties)
{
CopySection(fromSectionName, toSectionName, replaceProperties, false);
}
/// <summary>
/// Copy the section fromSectionName to toSectionName
/// </summary>
/// <param name="fromSectionName"></param>
/// <param name="toSectionName"></param>
/// <param name="replaceProperties">Any properties in the original section that are also in this dictionary will
/// be replaced by the value from this dictionary.</param>
/// <param name="force">if true and destination section already exists overwrite it</param>
public void CopySection(string fromSectionName, string toSectionName, Dictionary<string, string> replaceProperties, bool force)
{
int currentLineNumber = 0;
if (TrySeekSection(fromSectionName, ref currentLineNumber))
{
int lineNumber = 0;
if (TrySeekSection(toSectionName, ref lineNumber))
{
// if fromSectionName == toSectionName it's a no op
if (!string.Equals(fromSectionName, toSectionName, StringComparison.Ordinal))
{
if (force)
{
DeleteSection(toSectionName);
// recursive call with force == false now that the destination section is gone
CopySection(fromSectionName, toSectionName, replaceProperties, false);
}
else
throw new ArgumentException("Cannot copy section. The destination section " + toSectionName +
" already exists." + GetLineMessage(lineNumber));
}
}
else
{
// keep the first line number
var firstLineNumber = currentLineNumber;
// find the last line number (exclusive)
// could be end of file or beginning of next section
string dummySectionName;
currentLineNumber++;
while (currentLineNumber < Lines.Count
&& !TryParseSection(Lines[currentLineNumber], out dummySectionName))
{
currentLineNumber++;
}
// add the new section header to the end of the file
Lines.Add(sectionNamePrefix + toSectionName + sectionNameSuffix);
// copy the contents of the section to the end of the file
for (int line = firstLineNumber + 1; line < currentLineNumber; line++)
{
// If the key is in replaceProperties use the value from there
// otherwise just copy the line.
string propertyName;
string unused;
if (TryParseProperty(Lines[line], out propertyName, out unused) &&
replaceProperties.ContainsKey(propertyName))
Lines.Add(GetPropertyLine(propertyName, replaceProperties[propertyName]));
else
Lines.Add(Lines[line]);
}
}
}
else
throw new ArgumentException("Cannot copy section. The source section " + fromSectionName + " does not exist.");
}
/// <summary>
/// Update the section with the properties given.
/// If the section doesn't exist, it will be appended to the file.
///
/// Notes:
/// 1. Any properties that do exist in the section will be updated.
/// 2. A null value for a property denotes that it should be deleted from the section
/// 3. If any properties don't exist they will be appended to the end of the section
/// in the same order they appear in the SortedDictionary.
/// </summary>
/// <param name="sectionName">name of the section to operate on</param>
/// <param name="properties">properties to add/update/delete</param>
public virtual void EditSection(string sectionName, SortedDictionary<string, string> properties)
{
EnsureSectionExists(sectionName);
// build dictionary from list
// ensure the keys will be looked up case-insensitive
var propertiesLookup = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var pair in properties)
{
propertiesLookup.Add(pair.Key, pair.Value);
}
var lineNumber = 0;
if (TrySeekSection(sectionName, ref lineNumber))
{
lineNumber++;
string propertyName;
string propertyValue;
while (SeekProperty(ref lineNumber, out propertyName, out propertyValue))
{
var propertyDeleted = false;
if (propertiesLookup.ContainsKey(propertyName))
{
if (!string.Equals(propertiesLookup[propertyName], propertyValue))
{
if (propertiesLookup[propertyName] == null)
{
// delete the line
Lines.RemoveAt(lineNumber);
propertyDeleted = true;
}
else
{
// update the line
Lines[lineNumber] = GetPropertyLine(propertyName, propertiesLookup[propertyName]);
}
}
propertiesLookup.Remove(propertyName);
}
if (!propertyDeleted)
{
lineNumber++;
}
}
foreach (var pair in properties)
{
if (propertiesLookup.ContainsKey(pair.Key) && propertiesLookup[pair.Key] != null)
{
Lines.Insert(lineNumber++, pair.Key + keyValueSeparator + pair.Value);
}
}
}
}
/// <summary>
/// Check if the section exists. If not, append it to the end of the file.
/// </summary>
/// <param name="sectionName">section to ensure exists</param>
public void EnsureSectionExists(string sectionName)
{
var lineNumber = 0;
if (!TrySeekSection(sectionName, ref lineNumber))
{
Lines.Add(sectionNamePrefix + sectionName + sectionNameSuffix);
}
}
/// <summary>
/// If the section exists, delete it from the INI file.
/// </summary>
/// <param name="sectionName">section to delete</param>
public void DeleteSection(string sectionName)
{
var lineNumber = 0;
if (TrySeekSection(sectionName, ref lineNumber))
{
Lines.RemoveAt(lineNumber);
while (lineNumber < Lines.Count &&
!IsSection(Lines[lineNumber]))
{
Lines.RemoveAt(lineNumber);
}
}
}
public virtual HashSet<string> ListSectionNames()
{
var sectionNames = new HashSet<string>();
int lineNumber = 0;
string sectionName = null;
while (SeekSection(ref lineNumber, out sectionName))
{
sectionNames.Add(sectionName);
lineNumber++;
}
return sectionNames;
}
/// <summary>
/// Determine if a section exists in the INI file.
/// </summary>
/// <param name="sectionName">name of section to look for</param>
/// <returns>true if the section exists, false otherwise</returns>
public bool SectionExists(string sectionName)
{
var lineNumber = 0;
return TrySeekSection(sectionName, ref lineNumber);
}
/// <summary>
/// Determine if a section exists in the INI file.
/// </summary>
/// <param name="sectionNameRegex">Regex to match name of section to look for</param>
/// <param name="sectionName">name of section if regex matches</param>
/// <returns>true if the section exists, false otherwise</returns>
public bool SectionExists(Regex sectionNameRegex, out string sectionName)
{
var lineNumber = 0;
return TrySeekSection(sectionNameRegex, ref lineNumber, out sectionName);
}
/// <summary>
/// Return the properties for the section if it exists.
/// </summary>
/// <param name="sectionName">name of section to get</param>
/// <param name="properties">properties contained in the section</param>
/// <returns>True if the section was found, false otherwise</returns>
public virtual bool TryGetSection(string sectionName, out Dictionary<string, string> properties)
{
var lineNumber = 0;
properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (TrySeekSection(sectionName, ref lineNumber))
{
lineNumber++;
string propertyName;
string propertyValue;
while (SeekProperty(ref lineNumber, out propertyName, out propertyValue))
{
if (IsDuplicateProperty(properties, propertyName, sectionName, lineNumber))
{
properties.Clear();
return false;
}
properties.Add(propertyName, propertyValue);
lineNumber++;
}
return true;
}
return false;
}
/// <summary>
/// Return the properties for the section if it exists.
/// </summary>
/// <param name="sectionNameRegex">Regex to match name of section to get</param>
/// <param name="properties">properties contained in the section</param>
/// <returns>True if the section was found, false otherwise</returns>
public bool TryGetSection(Regex sectionNameRegex, out Dictionary<string, string> properties)
{
string dummy = null;
return TryGetSection(sectionNameRegex, out dummy, out properties);
}
/// <summary>
/// Return the properties for the section if it exists.
/// </summary>
/// <param name="sectionNameRegex">Regex to match name of section to get</param>
/// <param name="sectionName">name of section if regex matches</param>
/// <param name="properties">properties contained in the section</param>
/// <returns>True if the section was found, false otherwise</returns>
public bool TryGetSection(Regex sectionNameRegex, out string sectionName,
out Dictionary<string, string> properties)
{
var lineNumber = 0;
properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (TrySeekSection(sectionNameRegex, ref lineNumber, out sectionName))
{
lineNumber++;
string propertyName;
string propertyValue;
while (SeekProperty(ref lineNumber, out propertyName, out propertyValue))
{
if (IsDuplicateProperty(properties, propertyName, sectionName, lineNumber))
{
sectionName = null;
properties.Clear();
return false;
}
properties.Add(propertyName, propertyValue);
lineNumber++;
}
return true;
}
return false;
}
override public string ToString()
{
return textFile.ToString();
}
private bool IsDuplicateProperty(Dictionary<string, string> properties, string propertyName, string sectionName, int lineNumber)
{
var result = properties.ContainsKey(propertyName);
if (result)
logger.InfoFormat("Skipping section {0} because of duplicate property {1}. {2}", sectionName, propertyName, GetLineMessage(lineNumber));
return result;
}
private void Validate()
{
for (int i = 0; i < Lines.Count; i++)
{
var line = Lines[i];
if (!IsProperty(line) && !IsSection(line) && !IsCommentOrBlank(line))
{
throw new InvalidDataException(GetErrorMessage(i));
}
}
}
private bool TrySeekSection(Regex sectionNameRegex, ref int lineNumber, out string sectionName)
{
string currentSectionName = null;
while (SeekSection(ref lineNumber, out currentSectionName) &&
!sectionNameRegex.IsMatch(currentSectionName))
{
lineNumber++;
}
sectionName = currentSectionName;
return currentSectionName != null && sectionNameRegex.IsMatch(currentSectionName);
}
private bool TrySeekSection(String sectionName, ref int lineNumber)
{
string currentSectionName = null;
while (SeekSection(ref lineNumber, out currentSectionName) &&
!string.Equals(sectionName, currentSectionName, StringComparison.Ordinal))
{
lineNumber++;
}
return string.Equals(sectionName, currentSectionName, StringComparison.Ordinal);
}
private bool SeekSection(ref int lineNumber, out string sectionName)
{
while (lineNumber < Lines.Count)
{
if (TryParseSection(Lines[lineNumber], out sectionName))
{
return true;
}
lineNumber++;
}
sectionName = null;
return false;
}
private bool SeekProperty(ref int lineNumber, out string propertyName, out string propertyValue)
{
while (lineNumber < Lines.Count)
{
if (TryParseProperty(Lines[lineNumber], out propertyName, out propertyValue))
{
return true;
}
else if (IsSection(Lines[lineNumber]))
{
return false;
}
else if (IsCommentOrBlank(Lines[lineNumber]))
{
lineNumber++;
}
else
{
throw new InvalidDataException(GetErrorMessage(lineNumber));
}
}
propertyName = null;
propertyValue = null;
return false;
}
private string GetErrorMessage(int lineNumber)
{
return string.Format(CultureInfo.InvariantCulture,
"Line {0}:<{1}> in file {2} does not contain a section, property or comment.",
lineNumber + 1,
Lines[lineNumber],
FilePath);
}
private static bool IsCommentOrBlank(string line)
{
if (line == null)
{
return true;
}
else
{
line = line.Trim();
return string.IsNullOrEmpty(line)
|| line.StartsWith(semiColonComment, StringComparison.Ordinal)
|| line.StartsWith(hashComment, StringComparison.Ordinal);
}
}
private static bool IsSection(string line)
{
string dummy;
return TryParseSection(line, out dummy);
}
private static bool TryParseSection(string line, out string sectionName)
{
if (line != null)
{
line = line.Trim();
if (line.StartsWith(sectionNamePrefix, StringComparison.Ordinal)
&& line.EndsWith(sectionNameSuffix, StringComparison.Ordinal))
{
sectionName = line.Substring(1, line.Length - 2).Trim();
return true;
}
}
sectionName = null;
return false;
}
private static bool IsProperty(string line)
{
string dummyName;
string dummyValue;
return TryParseProperty(line, out dummyName, out dummyValue);
}
private static bool TryParseProperty(string line, out string propertyName, out string propertyValue)
{
if (line != null && !IsCommentOrBlank(line))
{
line = line.Trim();
var separatorIndex = line.IndexOf(keyValueSeparator, StringComparison.Ordinal);
if (separatorIndex >= 0)
{
propertyName = line.Substring(0, separatorIndex).Trim();
var valueStartIndex = separatorIndex + keyValueSeparator.Length;
propertyValue = line.Substring(valueStartIndex, line.Length - valueStartIndex).Trim();
return true;
}
}
propertyName = null;
propertyValue = null;
return false;
}
private static string GetPropertyLine(string propertyName, string propertyValue)
{
return string.Concat(propertyName, keyValueSeparator, propertyValue);
}
private string GetLineMessage(int lineNumber)
{
return string.Concat("(", this.FilePath, ":line ", lineNumber + 1, ")");
}
}
} | 587 |
aws-sdk-net | aws | C# | using Amazon.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
namespace Amazon.Runtime.Internal.Util
{
internal class InternalConsoleLogger : InternalLogger
{
//mapped to android logcat
enum LogLevel
{
Verbose = 2,
Debug = 3,
Info = 4,
Warn = 5,
Error = 6,
Assert = 7
}
public static long _sequanceId;
public InternalConsoleLogger(Type declaringType)
: base(declaringType)
{}
#region Overrides
public override void Flush()
{
}
/// <summary>
/// Simple wrapper around the log4net Error method.
/// </summary>
/// <param name="exception"></param>
/// <param name="messageFormat"></param>
/// <param name="args"></param>
public override void Error(Exception exception, string messageFormat, params object[] args)
{
this.Log(LogLevel.Error, string.Format(CultureInfo.CurrentCulture, messageFormat, args), exception);
}
/// <summary>
/// Write debug message to Console
/// </summary>
/// <param name="exception"></param>
/// <param name="messageFormat"></param>
/// <param name="args"></param>
public override void Debug(Exception exception, string messageFormat, params object[] args)
{
this.Log(LogLevel.Debug, string.Format(CultureInfo.CurrentCulture, messageFormat, args), exception);
}
/// <summary>
/// Write debug message to Console
/// </summary>
/// <param name="message"></param>
/// <param name="arguments"></param>
public override void DebugFormat(string message, params object[] arguments)
{
this.Log(LogLevel.Debug, string.Format(CultureInfo.CurrentCulture, message, arguments), (Exception)null);
}
/// <summary>
/// Simple wrapper around the log4net InfoFormat method.
/// </summary>
/// <param name="message"></param>
/// <param name="arguments"></param>
public override void InfoFormat(string message, params object[] arguments)
{
this.Log(LogLevel.Info, string.Format(CultureInfo.CurrentCulture, message, arguments), (Exception)null);
}
#endregion
private void Log(LogLevel logLevel, string message, Exception ex)
{
string formatted = null;
long sequence = Interlocked.Increment(ref _sequanceId);
#pragma warning disable CS0612 // Type or member is obsolete
string dt = AWSSDKUtils.CorrectedUtcNow.ToLocalTime().ToString(AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture);
#pragma warning restore CS0612 // Type or member is obsolete
string asString = logLevel.ToString().ToUpper(CultureInfo.InvariantCulture);
if (ex != null)
formatted = string.Format(CultureInfo.CurrentCulture, "{0}|{1}|{2}|{3} --> {4}", sequence, dt, asString, message, ex.ToString());
else
formatted = string.Format(CultureInfo.CurrentCulture, "{0}|{1}|{2}|{3}", sequence, dt, asString, message);
Console.WriteLine(@"{0} {1}", DeclaringType.Name, formatted);
}
}
}
| 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 System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.ComponentModel;
using Amazon.Runtime;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// This is a dynamic wrapper around log4net so we can avoid log4net being required
/// to be distributed with the SDK.
/// </summary>
public class Logger : ILogger
{
private static IDictionary<Type, Logger> cachedLoggers = new Dictionary<Type, Logger>();
private List<InternalLogger> loggers;
private static Logger emptyLogger = new Logger();
private Logger()
{
loggers = new List<InternalLogger>();
}
private Logger(Type type)
{
loggers = new List<InternalLogger>();
InternalLog4netLogger log4netLogger = new InternalLog4netLogger(type);
loggers.Add(log4netLogger);
loggers.Add(new InternalConsoleLogger(type));
InternalSystemDiagnosticsLogger sdLogger = new InternalSystemDiagnosticsLogger(type);
loggers.Add(sdLogger);
ConfigureLoggers();
AWSConfigs.PropertyChanged += ConfigsChanged;
}
private void ConfigsChanged(object sender, PropertyChangedEventArgs e)
{
if (e != null && string.Equals(e.PropertyName, AWSConfigs.LoggingDestinationProperty, StringComparison.Ordinal))
{
ConfigureLoggers();
}
}
private void ConfigureLoggers()
{
LoggingOptions logging = AWSConfigs.LoggingConfig.LogTo;
foreach (InternalLogger il in loggers)
{
if (il is InternalLog4netLogger)
il.IsEnabled = (logging & LoggingOptions.Log4Net) == LoggingOptions.Log4Net;
if (il is InternalConsoleLogger)
il.IsEnabled = (logging & LoggingOptions.Console) == LoggingOptions.Console;
if (il is InternalSystemDiagnosticsLogger)
il.IsEnabled = (logging & LoggingOptions.SystemDiagnostics) == LoggingOptions.SystemDiagnostics;
}
}
#region Static accessor
public static Logger GetLogger(Type type)
{
if (type == null) throw new ArgumentNullException("type");
Logger l;
lock (cachedLoggers)
{
if (!cachedLoggers.TryGetValue(type, out l))
{
l = new Logger(type);
cachedLoggers[type] = l;
}
}
return l;
}
public static void ClearLoggerCache()
{
lock (cachedLoggers)
{
cachedLoggers = new Dictionary<Type, Logger>();
}
}
public static Logger EmptyLogger { get { return emptyLogger; } }
#endregion
#region Logging methods
public void Flush()
{
foreach (InternalLogger logger in loggers)
{
logger.Flush();
}
}
public void Error(Exception exception, string messageFormat, params object[] args)
{
foreach (InternalLogger logger in loggers)
{
if (logger.IsEnabled && logger.IsErrorEnabled)
logger.Error(exception, messageFormat, args);
}
}
public void Debug(Exception exception, string messageFormat, params object[] args)
{
foreach (InternalLogger logger in loggers)
{
if (logger.IsEnabled && logger.IsDebugEnabled)
logger.Debug(exception, messageFormat, args);
}
}
public void DebugFormat(string messageFormat, params object[] args)
{
foreach (InternalLogger logger in loggers)
{
if (logger.IsEnabled && logger.IsDebugEnabled)
logger.DebugFormat(messageFormat, args);
}
}
public void InfoFormat(string messageFormat, params object[] args)
{
foreach (InternalLogger logger in loggers)
{
if (logger.IsEnabled && logger.IsInfoEnabled)
logger.InfoFormat(messageFormat, args);
}
}
#endregion
}
/// <summary>
/// Abstract logger class, base for any custom/specific loggers.
/// </summary>
internal abstract class InternalLogger
{
public Type DeclaringType { get; private set; }
public bool IsEnabled { get; set; }
public InternalLogger(Type declaringType)
{
DeclaringType = declaringType;
IsEnabled = true;
}
#region Logging methods
/// <summary>
/// Flushes the logger contents.
/// </summary>
public abstract void Flush();
/// <summary>
/// Simple wrapper around the log4net IsErrorEnabled property.
/// </summary>
public virtual bool IsErrorEnabled { get { return true; } }
/// <summary>
/// Simple wrapper around the log4net IsDebugEnabled property.
/// </summary>
public virtual bool IsDebugEnabled { get { return true; } }
/// <summary>
/// Simple wrapper around the log4net IsInfoEnabled property.
/// </summary>
public virtual bool IsInfoEnabled { get { return true; } }
/// <summary>
/// Simple wrapper around the log4net Error method.
/// </summary>
/// <param name="exception"></param>
/// <param name="messageFormat"></param>
/// <param name="args"></param>
public abstract void Error(Exception exception, string messageFormat, params object[] args);
/// <summary>
/// Simple wrapper around the log4net Debug method.
/// </summary>
/// <param name="exception"></param>
/// <param name="messageFormat"></param>
/// <param name="args"></param>
public abstract void Debug(Exception exception, string messageFormat, params object[] args);
/// <summary>
/// Simple wrapper around the log4net DebugFormat method.
/// </summary>
/// <param name="message"></param>
/// <param name="arguments"></param>
public abstract void DebugFormat(string message, params object[] arguments);
/// <summary>
/// Simple wrapper around the log4net InfoFormat method.
/// </summary>
/// <param name="message"></param>
/// <param name="arguments"></param>
public abstract void InfoFormat(string message, params object[] arguments);
#endregion
}
}
| 225 |
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.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.ComponentModel;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Logger wrapper for System.Diagnostics.TraceSource logger.
/// </summary>
internal class InternalSystemDiagnosticsLogger : InternalLogger
{
volatile int eventId = 0;
TraceSource trace;
public InternalSystemDiagnosticsLogger(Type declaringType)
: base(declaringType)
{
this.trace = TraceSourceUtil.GetTraceSource(declaringType);
}
#region Overrides
public override void Flush()
{
if (trace != null)
this.trace.Flush();
}
public override void Error(Exception exception, string messageFormat, params object[] args)
{
trace.TraceData(TraceEventType.Error, eventId++, new LogMessage(CultureInfo.InvariantCulture, messageFormat, args), exception);
}
public override void Debug(Exception exception, string messageFormat, params object[] args)
{
trace.TraceData(TraceEventType.Verbose, eventId++, new LogMessage(CultureInfo.InvariantCulture, messageFormat, args), exception);
}
public override void DebugFormat(string messageFormat, params object[] args)
{
trace.TraceData(TraceEventType.Verbose, eventId++, new LogMessage(CultureInfo.InvariantCulture, messageFormat, args));
}
public override void InfoFormat(string message, params object[] arguments)
{
trace.TraceData(TraceEventType.Information, eventId++, new LogMessage(CultureInfo.InvariantCulture, message, arguments));
}
public override bool IsDebugEnabled { get { return (trace != null); } }
public override bool IsErrorEnabled { get { return (trace != null); } }
public override bool IsInfoEnabled { get { return (trace != null); } }
#endregion
}
/// <summary>
/// Creates TraceRoute for a given Type or the closest "parent" that has a listener configured.
/// Example: if type is Amazon.DynamoDB.AmazonDynamoDBClient, listeners can be configured for:
/// -Amazon.DynamoDB.AmazonDynamoDBClient
/// -Amazon.DynamoDB
/// -Amazon
/// The first matching TraceSource with listeners will be used.
/// If no listeners are configured for type or one of its "parents", will return null.
/// </summary>
internal static class TraceSourceUtil
{
#region Public methods
/// <summary>
/// Gets a TraceSource for given Type with SourceLevels.All.
/// If there are no listeners configured for targetType or one of its "parents", returns null.
/// </summary>
/// <param name="targetType"></param>
/// <returns></returns>
public static TraceSource GetTraceSource(Type targetType)
{
return GetTraceSource(targetType, SourceLevels.All);
}
/// <summary>
/// Gets a TraceSource for given Type and SourceLevels.
/// If there are no listeners configured for targetType or one of its "parents", returns null.
/// </summary>
/// <param name="targetType"></param>
/// <param name="sourceLevels"></param>
/// <returns></returns>
public static TraceSource GetTraceSource(Type targetType, SourceLevels sourceLevels)
{
TraceSource traceSource = GetTraceSourceWithListeners(targetType.FullName, sourceLevels);
return traceSource;
}
#endregion
#region Private methods
// Gets the name of the closest "parent" TraceRoute that has listeners, or null otherwise.
private static TraceSource GetTraceSourceWithListeners(string name, SourceLevels sourceLevels)
{
string[] parts = name.Split(new char[] { '.' }, StringSplitOptions.None);
List<string> namesToTest = new List<string>();
StringBuilder sb = new StringBuilder();
foreach (var part in parts)
{
if (sb.Length > 0)
sb.Append(".");
sb.Append(part);
string partialName = sb.ToString();
namesToTest.Add(partialName);
}
namesToTest.Reverse();
foreach (var testName in namesToTest)
{
TraceSource ts = new TraceSource(testName, sourceLevels);
ts.Listeners.AddRange(AWSConfigs.TraceListeners(testName));
// no listeners? skip
if (ts.Listeners == null || ts.Listeners.Count == 0)
{
ts.Close();
continue;
}
// more than one listener? use this TraceSource
if (ts.Listeners.Count > 1)
return ts;
TraceListener listener = ts.Listeners[0];
// single listener isn't DefaultTraceListener? use this TraceRoute
if (!(listener is DefaultTraceListener))
return ts;
// single listener is DefaultTraceListener but isn't named Default? use this TraceRoute
if (!string.Equals(listener.Name, "Default", StringComparison.Ordinal))
return ts;
// not the TraceSource we're looking for, close it
ts.Close();
}
// nothing found? no listeners are configured for any of the names, even the original,
// so return null to signify failure
return null;
}
#endregion
}
} | 170 |
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.Globalization;
using System.Reflection;
using System.Text;
using System.ComponentModel;
using Amazon.Util.Internal;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Logger wrapper for reflected log4net logging methods.
/// </summary>
internal class InternalLog4netLogger : InternalLogger
{
enum LoadState { Uninitialized, Failed, Loading, Success };
#region Reflected Types and methods
static LoadState loadState = LoadState.Uninitialized;
static readonly object LOCK = new object();
static Type logMangerType;
static ITypeInfo logMangerTypeInfo;
static MethodInfo getLoggerWithTypeMethod;
static Type logType;
static ITypeInfo logTypeInfo;
static MethodInfo logMethod;
static Type levelType;
static ITypeInfo levelTypeInfo;
static object debugLevelPropertyValue;
static object infoLevelPropertyValue;
static object errorLevelPropertyValue;
static MethodInfo isEnabledForMethod;
static Type systemStringFormatType;
static Type loggerType;
#endregion
private object internalLogger;
private bool? isErrorEnabled;
private bool? isDebugEnabled;
private bool? isInfoEnabled;
/// <summary>
/// This should be a one time call to use reflection to find all the types and methods
/// needed for the logging API.
/// </summary>
private static void loadStatics()
{
lock (InternalLog4netLogger.LOCK)
{
if (loadState != LoadState.Uninitialized)
return;
loadState = LoadState.Loading;
try
{
loggerType = Type.GetType("Amazon.Runtime.Internal.Util.Logger");
// The LogManager and its methods
logMangerType = Type.GetType("log4net.Core.LoggerManager, log4net");
logMangerTypeInfo = TypeFactory.GetTypeInfo(logMangerType);
if (logMangerType == null)
{
loadState = LoadState.Failed;
return;
}
getLoggerWithTypeMethod = logMangerTypeInfo.GetMethod("GetLogger", new ITypeInfo[] { TypeFactory.GetTypeInfo(typeof(Assembly)), TypeFactory.GetTypeInfo(typeof(Type)) });
// The ILog and its methdods
logType = Type.GetType("log4net.Core.ILogger, log4net");
logTypeInfo = TypeFactory.GetTypeInfo(logType);
levelType = Type.GetType("log4net.Core.Level, log4net");
levelTypeInfo = TypeFactory.GetTypeInfo(levelType);
debugLevelPropertyValue = levelTypeInfo.GetField("Debug").GetValue(null);
infoLevelPropertyValue = levelTypeInfo.GetField("Info").GetValue(null);
errorLevelPropertyValue = levelTypeInfo.GetField("Error").GetValue(null);
systemStringFormatType = Type.GetType("log4net.Util.SystemStringFormat, log4net");
logMethod = logTypeInfo.GetMethod("Log", new ITypeInfo[] { TypeFactory.GetTypeInfo(typeof(Type)), levelTypeInfo, TypeFactory.GetTypeInfo(typeof(object)), TypeFactory.GetTypeInfo(typeof(Exception)) });
isEnabledForMethod = logTypeInfo.GetMethod("IsEnabledFor", new ITypeInfo[] { levelTypeInfo });
if (getLoggerWithTypeMethod == null ||
isEnabledForMethod == null ||
logType == null ||
levelType == null ||
logMethod == null)
{
loadState = LoadState.Failed;
return;
}
var log4netSectionPresent = AWSConfigs.XmlSectionExists("log4net");
// If log4net section exists and log4net logging is enabled, we attempt to activate
// log4net by calling XmlConfigurator.Configure()
if (log4netSectionPresent &&
(AWSConfigs.LoggingConfig.LogTo & LoggingOptions.Log4Net) == LoggingOptions.Log4Net)
{
ITypeInfo xmlConfiguratorType = TypeFactory.GetTypeInfo(Type.GetType("log4net.Config.XmlConfigurator, log4net"));
if (xmlConfiguratorType != null)
{
MethodInfo configureMethod = xmlConfiguratorType.GetMethod("Configure", new ITypeInfo[0]);
if (configureMethod != null)
{
configureMethod.Invoke(null, null);
}
}
}
loadState = LoadState.Success;
}
catch
{
// Mark as failed so no attempted will be made on the logging methods.
loadState = LoadState.Failed;
}
}
}
public InternalLog4netLogger(Type declaringType)
: base(declaringType)
{
if (loadState == LoadState.Uninitialized)
{
loadStatics();
}
if (logMangerType == null)
return;
this.internalLogger = getLoggerWithTypeMethod.Invoke(null, new object[] { TypeFactory.GetTypeInfo(declaringType).Assembly, declaringType }); //Assembly.GetCallingAssembly()
}
#region Overrides
public override void Flush()
{
}
/// <summary>
/// Simple wrapper around the log4net IsErrorEnabled property.
/// </summary>
public override bool IsErrorEnabled
{
get
{
if (!isErrorEnabled.HasValue)
{
if (loadState != LoadState.Success || this.internalLogger == null || loggerType == null || systemStringFormatType == null || errorLevelPropertyValue == null)
isErrorEnabled = false;
else
isErrorEnabled = Convert.ToBoolean(isEnabledForMethod.Invoke(this.internalLogger, new object[] { errorLevelPropertyValue }), CultureInfo.InvariantCulture);
}
return isErrorEnabled.Value;
}
}
/// <summary>
/// Simple wrapper around the log4net Error method.
/// </summary>
/// <param name="exception"></param>
/// <param name="messageFormat"></param>
/// <param name="args"></param>
public override void Error(Exception exception, string messageFormat, params object[] args)
{
logMethod.Invoke(
this.internalLogger,
new object[]
{
loggerType, errorLevelPropertyValue,
new LogMessage(CultureInfo.InvariantCulture, messageFormat, args),
exception
});
}
/// <summary>
/// Simple wrapper around the log4net IsDebugEnabled property.
/// </summary>
public override bool IsDebugEnabled
{
get
{
if (!isDebugEnabled.HasValue)
{
if (loadState != LoadState.Success || this.internalLogger == null || loggerType == null || systemStringFormatType == null || debugLevelPropertyValue == null)
isDebugEnabled = false;
else
isDebugEnabled = Convert.ToBoolean(isEnabledForMethod.Invoke(this.internalLogger, new object[] { debugLevelPropertyValue }), CultureInfo.InvariantCulture);
}
return isDebugEnabled.Value;
}
}
/// <summary>
/// Simple wrapper around the log4net Debug method.
/// </summary>
/// <param name="exception"></param>
/// <param name="messageFormat"></param>
/// <param name="args"></param>
public override void Debug(Exception exception, string messageFormat, params object[] args)
{
logMethod.Invoke(
this.internalLogger,
new object[]
{
loggerType, debugLevelPropertyValue,
new LogMessage(CultureInfo.InvariantCulture, messageFormat, args),
exception
});
}
/// <summary>
/// Simple wrapper around the log4net DebugFormat method.
/// </summary>
/// <param name="message"></param>
/// <param name="arguments"></param>
public override void DebugFormat(string message, params object[] arguments)
{
logMethod.Invoke(
this.internalLogger,
new object[]
{
loggerType, debugLevelPropertyValue,
new LogMessage(CultureInfo.InvariantCulture, message, arguments),
null
});
}
/// <summary>
/// Simple wrapper around the log4net IsInfoEnabled property.
/// </summary>
public override bool IsInfoEnabled
{
get
{
if (!isInfoEnabled.HasValue)
{
if (loadState != LoadState.Success || this.internalLogger == null || loggerType == null || systemStringFormatType == null || infoLevelPropertyValue == null)
isInfoEnabled = false;
else
isInfoEnabled = Convert.ToBoolean(isEnabledForMethod.Invoke(this.internalLogger, new object[] { infoLevelPropertyValue }), CultureInfo.InvariantCulture);
}
return isInfoEnabled.Value;
}
}
/// <summary>
/// Simple wrapper around the log4net InfoFormat method.
/// </summary>
/// <param name="message"></param>
/// <param name="arguments"></param>
public override void InfoFormat(string message, params object[] arguments)
{
logMethod.Invoke(
this.internalLogger,
new object[]
{
loggerType, infoLevelPropertyValue,
new LogMessage(CultureInfo.InvariantCulture, message, arguments),
null
});
}
#endregion
}
}
| 295 |
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.Globalization;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// A single logged message
/// </summary>
public class LogMessage : ILogMessage
{
/// <summary>
/// Log message arguments.
/// </summary>
public object[] Args { get; private set; }
/// <summary>
/// Culture-specific formatting provider.
/// </summary>
public IFormatProvider Provider { get; private set; }
/// <summary>
/// Log message format.
/// </summary>
public string Format { get; private set; }
public LogMessage(string message) : this(CultureInfo.InvariantCulture, message) { }
public LogMessage(string format, params object[] args) : this(CultureInfo.InvariantCulture, format, args) { }
public LogMessage(IFormatProvider provider, string format, params object[] args)
{
Args = args;
Format = format;
Provider = provider;
}
public override string ToString()
{
return string.Format(Provider, Format, Args);
}
}
}
| 56 |
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;
using System;
using System.Collections.Generic;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// a size-limited cache of key value pairs
///
/// Once the maximum size has been reached, the least recently
/// used pairs will be evicted to make room for any new items.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
public class LruCache<TKey, TValue>
where TKey : class
where TValue : class
{
private readonly object cacheLock = new object();
private Dictionary<TKey, LruListItem<TKey, TValue>> cache;
private LruList<TKey, TValue> lruList;
/// <summary>
/// the maximum number of entries this LruCache will hold
/// before items begin getting evicted
/// </summary>
public int MaxEntries { get; private set; }
/// <summary>
/// the number of items in the cache
/// </summary>
public int Count
{
get
{
lock (cacheLock)
{
return cache.Count;
}
}
}
/// <summary>
/// Construct a new LruCache.
/// </summary>
/// <param name="maxEntries">maximum number of entries before items are evicted</param>
public LruCache(int maxEntries)
{
if (maxEntries < 1)
{
throw new ArgumentException("maxEntries must be greater than zero.");
}
MaxEntries = maxEntries;
cache = new Dictionary<TKey, LruListItem<TKey, TValue>>();
lruList = new LruList<TKey, TValue>();
}
/// <summary>
/// Returns the least recently used item if it exists.
/// </summary>
/// <returns>The item that is least recently used or the default value of the LruListItem class if the LRU cache is empty.</returns>
public LruListItem<TKey, TValue> FindOldestItem()
{
lock (cacheLock)
{
var item = default(LruListItem<TKey, TValue>);
if (lruList.Tail != null)
item = lruList.Tail;
return item;
}
}
/// <summary>
/// Method to evict expired LRUListItems.
/// </summary>
/// <param name="validityInSeconds">Number of seconds the LRUListItems are valid for.</param>
public void EvictExpiredLRUListItems(int validityInSeconds)
{
lock (cacheLock)
{
while (Count != 0)
{
var item = FindOldestItem();
#pragma warning disable CS0618 // Type or member is obsolete
var timeSpan = AWSSDKUtils.CorrectedUtcNow - item.LastTouchedTimestamp;
#pragma warning restore CS0618 // Type or member is obsolete
if (timeSpan.TotalSeconds > validityInSeconds)
Evict(item.Key);
else
break;
}
}
}
/// <summary>
/// Add the key/value pair to the cache, or update
/// the value if the key already exists.
///
/// If the cache is full, evicts the least recently used item.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void AddOrUpdate(TKey key, TValue value)
{
lock (cacheLock)
{
LruListItem<TKey, TValue> existingLruListItem;
if (cache.TryGetValue(key, out existingLruListItem))
{
// update
existingLruListItem.Value = value;
lruList.Touch(existingLruListItem);
}
else
{
// add
var newLruListItem = new LruListItem<TKey, TValue>(key, value);
while (cache.Count >= MaxEntries)
{
cache.Remove(lruList.EvictOldest());
}
lruList.Add(newLruListItem);
cache.Add(key, newLruListItem);
}
}
}
/// <summary>
/// Evicts a specific key out of the cache if it exists
/// </summary>
/// <param name="key">the key to evict from the cache</param>
public void Evict(TKey key)
{
lock (cacheLock)
{
LruListItem<TKey, TValue> existingLruListItem;
if (cache.TryGetValue(key, out existingLruListItem))
{
lruList.Remove(existingLruListItem);
cache.Remove(key);
}
}
}
/// <summary>
/// Try to get the value associated with the key.
/// </summary>
/// <param name="key">the key to look up</param>
/// <param name="value">the value, if the key exists</param>
/// <returns>true if there is a value associated with the key, or false if no value is associated with the key</returns>
public bool TryGetValue(TKey key, out TValue value)
{
LruListItem<TKey, TValue> existingListItem;
lock (cacheLock)
{
if (cache.TryGetValue(key, out existingListItem))
{
lruList.Touch(existingListItem);
value = existingListItem.Value;
return true;
}
else
{
value = null;
return false;
}
}
}
/// <summary>
/// Try to get the value associated with the key, if it doesn't exist, use the provided factory method to
/// create a new value and tries adding it to the cache.
/// </summary>
/// <param name="key">the key to look up</param>
/// <param name="factory">the factory method used in case the key is not present in the cache</param>
/// <returns>the looked up value or the value created by the factory</returns>
public TValue GetOrAdd(TKey key, Func<TKey, TValue> factory)
{
TValue value;
if (TryGetValue(key, out value))
{
return value;
}
value = factory(key);
AddOrUpdate(key, value);
return value;
}
/// <summary>
/// Clear the LruCache of all entries.
/// </summary>
public void Clear()
{
lock (cacheLock)
{
cache.Clear();
lruList.Clear();
}
}
}
/// <summary>
/// Helper class to support LruCache.
/// Does not implement the error checking and synchronization that
/// would be necessary for it to stand alone.
/// </summary>
public class LruList<TKey, TValue>
{
public LruListItem<TKey, TValue> Head { get; private set; }
public LruListItem<TKey, TValue> Tail { get; private set; }
public void Add(LruListItem<TKey, TValue> item)
{
if (Head == null)
{
Head = item;
Tail = item;
item.Previous = null;
item.Next = null;
}
else
{
Head.Previous = item;
item.Next = Head;
item.Previous = null;
Head = item;
}
#pragma warning disable CS0618 // Type or member is obsolete
item.LastTouchedTimestamp = AWSSDKUtils.CorrectedUtcNow;
#pragma warning restore CS0618 // Type or member is obsolete
}
public void Remove(LruListItem<TKey, TValue> item)
{
if (Head == item || Tail == item)
{
if (Head == item)
{
Head = item.Next;
if (Head != null)
{
Head.Previous = null;
}
}
if (Tail == item)
{
Tail = item.Previous;
if (Tail != null)
{
Tail.Next = null;
}
}
}
else
{
item.Previous.Next = item.Next;
item.Next.Previous = item.Previous;
}
item.Previous = null;
item.Next = null;
}
public void Touch(LruListItem<TKey, TValue> item)
{
Remove(item);
Add(item);
}
public TKey EvictOldest()
{
TKey key = default(TKey);
if (Tail != null)
{
key = Tail.Key;
Remove(Tail);
}
return key;
}
internal void Clear()
{
Head = null;
Tail = null;
}
}
/// <summary>
/// Item to be stored in the LruList
/// linked list structure.
/// </summary>
public class LruListItem<TKey, TValue>
{
public TValue Value { get; set; }
public TKey Key { get; private set; }
internal DateTime LastTouchedTimestamp { get; set; }
public LruListItem<TKey, TValue> Next { get; set; }
public LruListItem<TKey, TValue> Previous { get; set; }
public LruListItem(TKey key, TValue value)
{
Key = key;
Value = value;
}
}
}
| 323 |
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.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Amazon.Util;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Runtime.Internal.Util
{
public class RequestMetrics : IRequestMetrics
{
#region Private members
private object metricsLock = new object();
private Stopwatch stopWatch;
private Dictionary<Metric, Timing> inFlightTimings;
private List<MetricError> errors = new List<MetricError>();
private long CurrentTime { get { return stopWatch.GetElapsedDateTimeTicks(); } }
private void LogError_Locked(Metric metric, string messageFormat, params object[] args)
{
errors.Add(new MetricError(metric, messageFormat, args));
}
private static void Log(StringBuilder builder, Metric metric, object metricValue)
{
LogHelper(builder, metric, metricValue);
}
private static void Log(StringBuilder builder, Metric metric, List<object> metricValues)
{
if (metricValues == null || metricValues.Count == 0)
LogHelper(builder, metric);
else
LogHelper(builder, metric, metricValues.ToArray());
}
private static void LogHelper(StringBuilder builder, Metric metric, params object[] metricValues)
{
builder.AppendFormat(CultureInfo.InvariantCulture, "{0} = ", metric);
if (metricValues == null)
{
builder.Append(ObjectToString(metricValues));
}
else
{
for (int i = 0; i < metricValues.Length; i++)
{
object metricValue = metricValues[i];
string metricValueString = ObjectToString(metricValue);
if (i > 0)
builder.Append(", ");
builder.Append(metricValueString);
}
}
builder.Append("; ");
}
private static string ObjectToString(object data)
{
if (data == null)
return "NULL";
return data.ToString();
}
#endregion
#region Properties
/// <summary>
/// Collection of properties being tracked
/// </summary>
public Dictionary<Metric, List<object>> Properties { get; set; }
/// <summary>
/// Timings for metrics being tracked
/// </summary>
public Dictionary<Metric, List<IMetricsTiming>> Timings { get; set; }
/// <summary>
/// Counters being tracked
/// </summary>
public Dictionary<Metric, long> Counters { get; set; }
/// <summary>
/// Whether metrics are enabled for the request
/// </summary>
public bool IsEnabled { get; internal set; }
#endregion
#region Constructor
/// <summary>
/// Constructs an empty, disabled metrics object
/// </summary>
public RequestMetrics()
{
stopWatch = Stopwatch.StartNew();
Properties = new Dictionary<Metric, List<object>>();
Timings = new Dictionary<Metric, List<IMetricsTiming>>();
Counters = new Dictionary<Metric, long>();
inFlightTimings = new Dictionary<Metric, Timing>();
IsEnabled = false;
}
#endregion
#region Internal methods
/// <summary>
/// Starts timing an event. Logs an exception if an event
/// of the same type was started but not stopped.
/// </summary>
/// <param name="metric"></param>
/// <returns></returns>
public TimingEvent StartEvent(Metric metric)
{
lock (metricsLock)
{
if (inFlightTimings.ContainsKey(metric))
LogError_Locked(metric, "Starting multiple events for the same metric");
inFlightTimings[metric] = new Timing(CurrentTime);
}
return new TimingEvent(this, metric);
}
/// <summary>
/// Stops timing an event. Logs an exception if the event wasn't started.
/// </summary>
/// <param name="metric"></param>
/// <returns></returns>
public Timing StopEvent(Metric metric)
{
Timing timing;
lock (metricsLock)
{
if (!inFlightTimings.TryGetValue(metric, out timing))
{
LogError_Locked(metric, "Trying to stop event that has not been started");
return new Timing();
}
inFlightTimings.Remove(metric);
timing.Stop(CurrentTime);
if (IsEnabled)
{
List<IMetricsTiming> list;
if (!Timings.TryGetValue(metric, out list))
{
list = new List<IMetricsTiming>();
Timings[metric] = list;
}
list.Add(timing);
}
}
return timing;
}
/// <summary>
/// Adds a property for a metric. If there are multiple, the
/// object is added as a new item in a list.
/// </summary>
/// <param name="metric"></param>
/// <param name="property"></param>
public void AddProperty(Metric metric, object property)
{
if (!IsEnabled) return;
List<object> list;
lock (metricsLock)
{
if (!Properties.TryGetValue(metric, out list))
{
list = new List<object>();
Properties[metric] = list;
}
list.Add(property);
}
}
/// <summary>
/// Sets a counter for a specific metric.
/// </summary>
/// <param name="metric"></param>
/// <param name="value"></param>
public void SetCounter(Metric metric, long value)
{
if (!IsEnabled) return;
lock (metricsLock)
{
Counters[metric] = value;
}
}
/// <summary>
/// Increments a specific metric counter.
/// If counter doesn't exist yet, it is set to 1.
/// </summary>
/// <param name="metric"></param>
public void IncrementCounter(Metric metric)
{
if (!IsEnabled) return;
lock (metricsLock)
{
long value;
if (!Counters.TryGetValue(metric, out value))
{
value = 1;
}
else
{
value++;
}
Counters[metric] = value;
}
}
/// <summary>
/// Returns errors associated with the metric, including
/// if there are still any timing events in-flight.
/// </summary>
/// <returns></returns>
public string GetErrors()
{
using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
{
lock (metricsLock)
{
if (inFlightTimings.Count > 0)
{
string inFlightTimingsValue = string.Join(", ", inFlightTimings.Keys.Select(k => k.ToString()).ToArray());
writer.Write("Timings are still in flight: {0}.", inFlightTimingsValue);
}
if (errors.Count > 0)
{
writer.Write("Logged {0} metrics errors: ", errors.Count);
foreach (MetricError error in errors)
{
// skip empty errors
if (error.Exception == null && string.IsNullOrEmpty(error.Message))
continue;
writer.Write("{0} - {1} - ",
error.Time.ToUniversalTime().ToString(AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture),
error.Metric);
if (!string.IsNullOrEmpty(error.Message))
{
writer.Write(error.Message);
writer.Write(";");
}
if (error.Exception != null)
{
writer.Write(error.Exception);
writer.Write("; ");
}
}
}
}
return writer.ToString();
}
}
#endregion
#region Overrides
/// <summary>
/// Returns a string representation of the current metrics.
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (!IsEnabled)
return "Metrics logging disabled";
StringBuilder builder = new StringBuilder();
// Check for a custom formatter
if (AWSConfigs.LoggingConfig.LogMetricsCustomFormatter != null)
{
try
{
lock (metricsLock)
{
builder.Append(AWSConfigs.LoggingConfig.LogMetricsCustomFormatter.FormatMetrics(this));
}
return builder.ToString();
}
catch (Exception e)
{
builder.Append("[Custom metrics formatter failed: ")
.Append(e.Message).Append("] ");
}
}
// If no custom formatter, or formatter fails, check to see if JSON is configured
if (AWSConfigs.LoggingConfig.LogMetricsFormat == LogMetricsFormatOption.JSON)
{
lock (metricsLock)
{
builder.Append(this.ToJSON());
}
return builder.ToString();
}
// Standard format.
lock (metricsLock)
{
foreach (var kvp in Properties)
{
Metric metric = kvp.Key;
List<object> values = kvp.Value;
Log(builder, metric, values);
}
foreach (var kvp in Timings)
{
Metric metric = kvp.Key;
List<IMetricsTiming> list = kvp.Value;
foreach (var timing in list)
{
if (timing.IsFinished)
Log(builder, metric, timing.ElapsedTime);
}
}
foreach (var kvp in Counters)
{
Metric metric = kvp.Key;
long value = kvp.Value;
Log(builder, metric, value);
}
}
builder.Replace("\r", "\\r").Replace("\n", "\\n");
return builder.ToString();
}
/// <summary>
/// Return a JSON represenation of the current metrics
/// </summary>
/// <returns></returns>
public string ToJSON()
{
if (!this.IsEnabled)
return "{ }";
var sb = new StringBuilder();
var jw = new JsonWriter(sb);
jw.WriteObjectStart();
jw.WritePropertyName("properties");
jw.WriteObjectStart();
foreach (var kvp in this.Properties)
{
jw.WritePropertyName(kvp.Key.ToString());
var properties = kvp.Value;
if (properties.Count > 1)
jw.WriteArrayStart();
foreach (var obj in properties)
{
if (obj == null)
jw.Write(null);
else
jw.Write(obj.ToString());
}
if (properties.Count > 1)
jw.WriteArrayEnd();
}
jw.WriteObjectEnd();
jw.WritePropertyName("timings");
jw.WriteObjectStart();
foreach (var kvp in this.Timings)
{
jw.WritePropertyName(kvp.Key.ToString());
var timings = kvp.Value;
if (timings.Count > 1)
jw.WriteArrayStart();
foreach (var timing in kvp.Value)
{
if (timing.IsFinished)
jw.Write(timing.ElapsedTime.TotalMilliseconds);
}
if (timings.Count > 1)
jw.WriteArrayEnd();
}
jw.WriteObjectEnd();
jw.WritePropertyName("counters");
jw.WriteObjectStart();
foreach (var kvp in this.Counters)
{
jw.WritePropertyName(kvp.Key.ToString());
jw.Write(kvp.Value);
}
jw.WriteObjectEnd();
jw.WriteObjectEnd();
return sb.ToString();
}
#endregion
}
/// <summary>
/// Timing information for a metric
/// </summary>
public class Timing : IMetricsTiming
{
private long startTime;
private long endTime;
/// <summary>
/// Empty, stopped timing object
/// </summary>
public Timing()
{
startTime = endTime = 0;
IsFinished = true;
}
/// <summary>
/// Timing object in a started state
/// </summary>
/// <param name="currentTime"></param>
public Timing(long currentTime)
{
startTime = currentTime;
IsFinished = false;
}
/// <summary>
/// Stops timing
/// </summary>
/// <param name="currentTime"></param>
public void Stop(long currentTime)
{
endTime = currentTime;
IsFinished = true;
}
/// <summary>
/// Whether the timing has been stopped
/// </summary>
public bool IsFinished { get; private set; }
/// <summary>
/// Elapsed ticks from start to stop.
/// If timing hasn't been stopped yet, returns 0.
/// </summary>
public long ElapsedTicks { get { return !IsFinished ? 0 : endTime - startTime; } }
/// <summary>
/// Elapsed time from start to stop.
/// If timing hasn't been stopped yet, returns TimeSpan.Zero
/// </summary>
public TimeSpan ElapsedTime { get { return TimeSpan.FromTicks(ElapsedTicks); } }
}
/// <summary>
/// Timing event, stops timing of a metric when disposed
/// </summary>
public class TimingEvent : IDisposable
{
private Metric metric;
private RequestMetrics metrics;
private bool disposed;
internal TimingEvent(RequestMetrics metrics, Metric metric)
{
this.metrics = metrics;
this.metric = metric;
}
#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)
{
metrics.StopEvent(metric);
}
this.disposed = true;
}
}
/// <summary>
/// Disposes of all managed and unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// The destructor for the client class.
/// </summary>
~TimingEvent()
{
this.Dispose(false);
}
#endregion
}
// Error encountered in metrics logging
public class MetricError
{
public Metric Metric { get; private set; }
public string Message { get; private set; }
public Exception Exception { get; private set; }
public DateTime Time { get; private set; }
public MetricError(Metric metric, string messageFormat, params object[] args) : this(metric, null, messageFormat, args) { }
public MetricError(Metric metric, Exception exception, string messageFormat, params object[] args)
{
#pragma warning disable CS0612 // Type or member is obsolete
Time = AWSSDKUtils.CorrectedUtcNow;
#pragma warning restore CS0612 // Type or member is obsolete
try
{
Message = string.Format(CultureInfo.InvariantCulture, messageFormat, args);
}
catch
{
Message = string.Format(CultureInfo.InvariantCulture, "Error message: {0}", messageFormat);
}
Exception = exception;
Metric = metric;
}
}
}
| 553 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// A wrapper stream which supresses disposal of the underlying stream.
/// </summary>
public class NonDisposingWrapperStream : WrapperStream
{
/// <summary>
/// Constructor for NonDisposingWrapperStream.
/// </summary>
/// <param name="baseStream">The base stream to wrap.</param>
public NonDisposingWrapperStream(Stream baseStream) : base (baseStream)
{
}
#if !NETSTANDARD
/// <summary>
/// The Close implementation for this wrapper stream
/// does not close the underlying stream.
/// </summary>
public override void Close()
{
// Suppress disposing the stream by not calling Close() on the base stream.
}
#endif
/// <summary>
/// The Dispose implementation for this wrapper stream
/// does not close the underlying stream.
/// </summary>
protected override void Dispose(bool disposing)
{
// Suppress disposing the stream by not calling Dispose() on the base stream.
}
}
}
| 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.IO;
namespace Amazon.Runtime.Internal.Util
{
internal class NullStream : Stream
{
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => 0;
public override long Position
{
get { return 0; }
set { }
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count) => 0;
public override long Seek(long offset, SeekOrigin origin) => 0;
public override void SetLength(long value)
{
}
public override void Write(byte[] buffer, int offset, int count)
{
}
}
} | 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.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Provides line-based read/write access to a file.
/// The file can be read into memory, changed, then written back to disk.
/// When the file is persisted back to disk, an optimistic concurrency
/// check is performed to make sure the file hasn't changed since it was
/// originally read.
///
/// This class is not threadsafe.
/// </summary>
public class OptimisticLockedTextFile
{
/// <summary>
/// a full copy of the original file
/// This is used for optimistic concurrency.
/// Note that this assumes a small file and does not scale large files.
/// </summary>
private string OriginalContents { get; set; }
/// <summary>
/// path of the file
/// </summary>
public string FilePath { get; private set; }
/// <summary>
/// Read/write access to the lines that make up the file.
/// Any changes to this List are persisted back to disk when Persist() is called.
///
/// NOTE:
/// The lines have the original line endings on them to preserve the
/// original text as much as possible.
/// </summary>
public List<string> Lines { get; private set; }
/// <summary>
/// Construct a new OptimisticLockedTextFile.
/// </summary>
/// <param name="filePath">path of the file</param>
public OptimisticLockedTextFile(string filePath)
{
FilePath = filePath;
Read();
}
/// <summary>
/// Persist changes to disk after an optimistic concurrency check is completed.
/// </summary>
public void Persist()
{
var newContents = ToString();
var path = Path.GetDirectoryName(FilePath);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
// open the file with exclusive access
using (var fileStream = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
// get a current copy of the file
string currentContents = null;
using (var streamReader = new StreamReader(fileStream))
{
currentContents = streamReader.ReadToEnd();
// optimistic concurrency check - make sure the file hasn't changed since it was read
if (string.Equals(currentContents, OriginalContents, StringComparison.Ordinal))
{
// write the new contents
fileStream.Seek(0, SeekOrigin.Begin);
using (var streamWriter = new StreamWriter(fileStream))
{
streamWriter.Write(newContents);
streamWriter.Flush();
// set the length in case the new contents are shorter than the old contents
fileStream.Flush();
fileStream.SetLength(fileStream.Position);
OriginalContents = newContents;
}
}
else
{
throw new IOException(string.Format(CultureInfo.InvariantCulture,
"Cannot write to file {0}. The file has been modified since it was last read.",
FilePath));
}
}
}
}
public override string ToString()
{
// Make sure all lines have endings, with the exception of the last line.
var contents = new StringBuilder();
for (int i = 0; i < Lines.Count; i++)
{
var line = Lines[i];
if (i < Lines.Count - 1 && !HasEnding(line))
{
contents.AppendLine(line);
}
else
{
contents.Append(line);
}
}
return contents.ToString();
}
private void Read()
{
// Store a copy of the file for checking concurrency
OriginalContents = "";
if (File.Exists(FilePath))
{
try
{
OriginalContents = File.ReadAllText(FilePath);
}
catch (FileNotFoundException)
{
// This is OK. The Persist() method will create it if necessary.
}
catch (DirectoryNotFoundException)
{
// This is OK. The Persist() method will create it if necessary.
}
}
// Parse the lines ourselves since we need to preserve the line endings.
// Parsing ourselves also avoids a race condition:
// Doing ReadAllText then ReadAllLines would leave a small gap in time where the file could be changed.
Lines = ReadLinesWithEndings(OriginalContents);
}
private static bool HasEnding(string line)
{
var lastChar = line[line.Length - 1];
return lastChar == '\n' || lastChar == '\r';
}
private static List<string> ReadLinesWithEndings(string str)
{
var lines = new List<string>();
var length = str.Length;
var i = 0;
var currentLineStart = 0;
while (i < length)
{
if (str[i] == '\r')
{
i++;
if (i < length && str[i] == '\n')
{
i++;
}
lines.Add(str.Substring(currentLineStart, i - currentLineStart));
currentLineStart = i;
}
else if (str[i] == '\n')
{
i++;
lines.Add(str.Substring(currentLineStart, i - currentLineStart));
currentLineStart = i;
}
else
{
i++;
}
}
if (currentLineStart < i)
{
lines.Add(str.Substring(currentLineStart, i - currentLineStart));
}
return lines;
}
}
} | 202 |
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;
using System.Collections.Generic;
using System.IO;
using System.Text;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// This class is used to wrap a stream for a particular segment of a stream. It
/// makes that segment look like you are reading from beginning to end of the stream.
/// </summary>
public class PartialWrapperStream : WrapperStream
{
private long initialPosition;
private long partSize;
public PartialWrapperStream(Stream stream, long partSize)
: base(stream)
{
if (!stream.CanSeek)
throw new InvalidOperationException("Base stream of PartialWrapperStream must be seekable");
this.initialPosition = stream.Position;
long remainingData = stream.Length - stream.Position;
if (partSize == 0 || remainingData < partSize)
{
this.partSize = remainingData;
}
else
{
this.partSize = partSize;
var encryptionStream = BaseStream as AESEncryptionUploadPartStream;
if (encryptionStream != null && (partSize % 16) != 0)
{
this.partSize = partSize - (partSize % EncryptUploadPartStream.InternalEncryptionBlockSize);
}
}
}
private long RemainingPartSize
{
get
{
long remaining = this.partSize - this.Position;
return remaining;
}
}
#region Stream overrides
public override long Length
{
get
{
long length = base.Length - this.initialPosition;
if (length > this.partSize)
{
length = this.partSize;
}
return length;
}
}
public override long Position
{
get
{
return base.Position - this.initialPosition;
}
set
{
base.Position = this.initialPosition + value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
int bytesToRead = count < this.RemainingPartSize ? count : (int)this.RemainingPartSize;
if (bytesToRead <= 0)
return 0;
return base.Read(buffer, offset, bytesToRead);
}
public override long Seek(long offset, SeekOrigin origin)
{
long position = 0;
switch (origin)
{
case SeekOrigin.Begin:
position = this.initialPosition + offset;
break;
case SeekOrigin.Current:
position = base.Position + offset;
break;
case SeekOrigin.End:
position = base.Position + this.partSize + offset;
break;
}
if (position < this.initialPosition)
{
position = this.initialPosition;
}
else if (position > this.initialPosition + this.partSize)
{
position = this.initialPosition + this.partSize;
}
base.Position = position;
return this.Position;
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void WriteByte(byte value)
{
throw new NotSupportedException();
}
#if AWS_ASYNC_API
/// <summary>
/// Asynchronously reads a sequence of bytes from the current stream, advances
/// the position within the stream by the number of bytes read, and monitors
/// cancellation requests.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests. The default value is
/// System.Threading.CancellationToken.None.
/// </param>
/// <returns>
/// A task that represents the asynchronous read operation. The value of the TResult
/// parameter contains the total number of bytes read into the buffer. This can be
/// less than the number of bytes requested if that many bytes are not currently
/// available, or zero (0) if the end of the stream has been reached.
/// </returns>
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
int bytesToRead = count < this.RemainingPartSize ? count : (int)this.RemainingPartSize;
if (bytesToRead <= 0)
return 0;
return await base.ReadAsync(buffer, offset, bytesToRead, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously writes a sequence of bytes to the current stream and advances the
/// current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">
/// An array of bytes. This method copies count bytes from buffer to the current stream.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin copying bytes to the
/// current stream.
/// </param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests. The default value is
/// System.Threading.CancellationToken.None.
/// </param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
#endif
#if !NETSTANDARD
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
throw new NotSupportedException();
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
throw new NotSupportedException();
}
public override int EndRead(IAsyncResult asyncResult)
{
throw new NotImplementedException();
}
public override void EndWrite(IAsyncResult asyncResult)
{
throw new NotImplementedException();
}
#endif
#endregion
}
}
| 240 |
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.Text;
using System.Text.RegularExpressions;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Subclass of IniFile that allows INI sections to be read with the profile keyword in front of the section name.
/// </summary>
public class ProfileIniFile : IniFile
{
private const string ProfileMarker = "profile";
private const string SsoSessionMarker = "sso-session";
public bool ProfileMarkerRequired { get; set; }
public override HashSet<string> ListSectionNames()
{
var profileNames = new HashSet<string>();
foreach (var profileName in base.ListSectionNames())
{
if (ProfileMarkerRequired)
{
if (!(profileName.StartsWith(ProfileMarker, StringComparison.Ordinal)))
continue;
}
var actualProfileName = Regex.Replace(profileName, ProfileMarker + "[ \t]+", "");
profileNames.Add(actualProfileName);
}
return profileNames;
}
public ProfileIniFile(string filePath,bool profileMarkerRequired) : base(filePath)
{
ProfileMarkerRequired = profileMarkerRequired;
}
public override bool TryGetSection(string sectionName, out Dictionary<string, string> properties)
{
return this.TryGetSection(sectionName, isSsoSession: false, out properties);
}
public bool TryGetSection(string sectionName, bool isSsoSession, out Dictionary<string, string> properties)
{
bool hasCredentialsProperties = false;
properties = null;
if (!ProfileMarkerRequired && !isSsoSession)
hasCredentialsProperties = base.TryGetSection(sectionName, out properties);
if (!hasCredentialsProperties)
{
var marker = isSsoSession ? SsoSessionMarker : ProfileMarker;
var credentialSectionNameRegex = new Regex("^" + marker + "[ \\t]+" + Regex.Escape(sectionName) + "$", RegexOptions.Singleline);
hasCredentialsProperties = this.TryGetSection(credentialSectionNameRegex, out properties);
}
return hasCredentialsProperties;
}
public override void EditSection(string sectionName, SortedDictionary<string, string> properties)
{
this.EditSection(sectionName, isSsoSession: false, properties);
}
public void EditSection(string sectionName, bool isSsoSession, SortedDictionary<string, string> properties)
{
if (!ProfileMarkerRequired && !isSsoSession)
{
base.EditSection(sectionName, properties);
return;
}
var marker = isSsoSession ? SsoSessionMarker : ProfileMarker;
var credentialSectionNameRegex = new Regex("^" + marker + "[ \\t]+" + Regex.Escape(sectionName) + "$", RegexOptions.Singleline);
if(SectionExists(credentialSectionNameRegex, out var fullSectionName))
{
base.EditSection(fullSectionName, properties);
}
}
}
}
| 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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
* API Version: 2006-03-01
*
*/
using System;
using System.IO;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Wrapper stream that only supports reading
/// </summary>
public class ReadOnlyWrapperStream : WrapperStream
{
public ReadOnlyWrapperStream(Stream baseStream)
: base(baseStream)
{
if (!baseStream.CanRead)
throw new InvalidOperationException("Base stream must be readable");
}
#region Overrides
#if !NETSTANDARD
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException();
}
public override void EndWrite(IAsyncResult asyncResult)
{
throw new NotSupportedException();
}
#endif
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override long Length
{
get
{
throw new NotSupportedException();
}
}
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
public override void Flush()
{
throw new NotSupportedException();
}
#if AWS_ASYNC_API
/// <summary>
/// Asynchronously clears all buffers for this stream and causes any buffered data
/// to be written to the underlying device.
/// </summary>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests. The default value is
/// System.Threading.CancellationToken.None.
/// </param>
/// <returns>
/// A task that represents the asynchronous flush operation.
/// </returns>
public override Task FlushAsync(CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
/// <summary>
/// Asynchronously writes a sequence of bytes to the current stream and advances the
/// current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">
/// An array of bytes. This method copies count bytes from buffer to the current stream.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin copying bytes to the
/// current stream.
/// </param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests. The default value is
/// System.Threading.CancellationToken.None.
/// </param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
#endif
#endregion
}
/// <summary>
/// Partial wrapper stream that only supports reading
/// </summary>
public class PartialReadOnlyWrapperStream : ReadOnlyWrapperStream
{
private long _currentPosition;
private long _size;
public PartialReadOnlyWrapperStream(Stream baseStream, long size)
: base(baseStream)
{
_currentPosition = 0;
_size = size;
}
private long RemainingSize
{
get
{
long remaining = this._size - this._currentPosition;
return remaining;
}
}
#region Overrides
public override int Read(byte[] buffer, int offset, int count)
{
int bytesToRead = count < this.RemainingSize ? count : (int)this.RemainingSize;
if (bytesToRead <= 0)
return 0;
int result = base.Read(buffer, offset, bytesToRead);
_currentPosition += result;
return result;
}
#if AWS_ASYNC_API
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
int bytesToRead = count < this.RemainingSize ? count : (int)this.RemainingSize;
if (bytesToRead <= 0)
return 0;
int result = await base.ReadAsync(buffer, offset, bytesToRead, cancellationToken).ConfigureAwait(false);
_currentPosition += result;
return result;
}
#endif
public override long Length
{
get
{
return _size;
}
}
public override long Position
{
get
{
return _currentPosition;
}
}
#endregion
}
}
| 217 |
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.Text;
using System.Text.RegularExpressions;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Uri wrapper that can parse out information (bucket, key, region, style) from an
/// S3 URI.
/// </summary>
public class S3Uri
{
private const string S3EndpointPattern = @"^(.+\.)?s3[.-]([a-z0-9-]+)\.";
//s3-control has a similar pattern to s3-region host names, so we explicitly exclude it
private const string S3ControlExlusionPattern = @"^(.+\.)?s3-control\.";
private static readonly Regex S3EndpointRegex = new Regex(S3EndpointPattern, RegexOptions.Compiled);
private static readonly Regex S3ControlExlusionRegex = new Regex(S3ControlExlusionPattern, RegexOptions.Compiled);
/// <summary>
/// True if the URI contains the bucket in the path, false if it contains the bucket in the authority.
/// </summary>
public bool IsPathStyle { get; private set; }
/// <summary>
/// The bucket name parsed from the URI (or null if no bucket specified).
/// </summary>
public string Bucket { get; private set; }
/// <summary>
/// The key parsed from the URI (or null if no key specified).
/// </summary>
public string Key { get; private set; }
/// <summary>
/// The region parsed from the URI (or null if no region specified).
/// </summary>
public RegionEndpoint Region { get; set; }
/// <summary>
/// Constructs a parser for the S3 URI specified as a string.
/// </summary>
/// <param name="uri">The S3 URI to be parsed.</param>
public S3Uri(string uri)
: this(new Uri(uri))
{
}
/// <summary>
/// Constructs a parser for the S3 URI specified as a Uri instance.
/// </summary>
/// <param name="uri">The S3 URI to be parsed.</param>
public S3Uri(Uri uri)
{
if (uri == null)
throw new ArgumentNullException("uri");
if (string.IsNullOrEmpty(uri.Host))
throw new ArgumentException("Invalid URI - no hostname present");
var match = S3EndpointRegex.Match(uri.Host);
if (!match.Success && !S3ControlExlusionRegex.Match(uri.Host).Success)
throw new ArgumentException("Invalid S3 URI - hostname does not appear to be a valid S3 endpoint");
// for host style urls:
// group 0 is bucketname plus 's3' prefix and possible region code
// group 1 is bucket name
// group 2 will be region or 'amazonaws' if US Classic region
// for path style urls:
// group 0 will be s3 prefix plus possible region code
// group 1 will be empty
// group 2 will be region or 'amazonaws' if US Classic region
var bucketNameGroup = match.Groups[1];
if (string.IsNullOrEmpty(bucketNameGroup.Value))
{
// no bucket name in the authority, parse it from the path
this.IsPathStyle = true;
// grab the encoded path so we don't run afoul of '/'s in the bucket name
var path = uri.AbsolutePath;
if (path.Equals("/"))
{
this.Bucket = null;
this.Key = null;
}
else
{
var index = path.IndexOf('/', 1);
if (index == -1)
{
// https://s3.amazonaws.com/bucket
this.Bucket = Decode(path.Substring(1));
this.Key = null;
}
else if (index == (path.Length - 1))
{
// https://s3.amazonaws.com/bucket/
this.Bucket = Decode(path.Substring(1, index)).TrimEnd('/');
this.Key = null;
}
else
{
// https://s3.amazonaws.com/bucket/key
this.Bucket = Decode(path.Substring(1, index)).TrimEnd('/');
this.Key = Decode(path.Substring(index + 1));
}
}
}
else
{
// bucket name in the host, path is the object key
this.IsPathStyle = false;
// remove any trailing '.' from the prefix to get the bucket name
this.Bucket = bucketNameGroup.Value.TrimEnd('.');
this.Key = uri.AbsolutePath.Equals("/") ? null : uri.AbsolutePath.Substring(1);
}
if (match.Groups.Count > 2)
{
// US 'classic' urls will not have a region code in the endpoint
var regionGroupValue = match.Groups[2].Value;
if (regionGroupValue.Equals("amazonaws", StringComparison.Ordinal)
|| regionGroupValue.Equals("external-1", StringComparison.Ordinal))
this.Region = RegionEndpoint.USEast1;
else
this.Region = RegionEndpoint.GetBySystemName(regionGroupValue);
}
}
public static bool IsS3Uri(Uri uri)
{
return S3EndpointRegex.Match(uri.Host).Success && !S3ControlExlusionRegex.Match(uri.Host).Success;
}
/// <summary>
/// Percent-decodes the given string, with a fast path for strings that are not
/// percent-encoded.
/// </summary>
/// <param name="s">The string to decode</param>
/// <returns>The decoded string</returns>
static string Decode(string s)
{
if (s == null)
return null;
for (var i = 0; i < s.Length; ++i)
{
if (s[i] == '%')
return Decode(s, i);
}
return s;
}
/// <summary>
/// Percent-decodes the given string.
/// </summary>
/// <param name="s">The string to decode</param>
/// <param name="firstPercent">The index of the first '%' in the string</param>
/// <returns>The decoded string</returns>
static string Decode(string s, int firstPercent)
{
var sb = new StringBuilder(s.Substring(0, firstPercent));
AppendDecoded(sb, s, firstPercent);
for (var i = firstPercent + 3; i < s.Length; ++i)
{
if (s[i] == '%')
{
AppendDecoded(sb, s, i);
i += 2;
}
else
sb.Append(s[i]);
}
return sb.ToString();
}
/// <summary>
/// Decodes the percent-encoded character at the given index in the string
/// and appends the decoded value to the string under construction.
/// </summary>
/// <param name="builder">
/// The string under construction to which the decoded character will be
/// appended.
/// </param>
/// <param name="s">The string being decoded.</param>
/// <param name="index">The index of the '%' character in the string.</param>
static void AppendDecoded(StringBuilder builder, string s, int index)
{
if (index > s.Length - 3)
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"Invalid percent-encoded string '{0}'",
s));
var first = s[index + 1];
var second = s[index + 2];
var decoded = (char)(FromHex(first) << 4 | FromHex(second));
builder.Append(decoded);
}
/// <summary>
/// Converts a hex character (0-9A-Fa-f) into its corresponding quad value.
/// </summary>
/// <param name="c">The hex character</param>
/// <returns>The quad value</returns>
static int FromHex(char c)
{
if (c < '0')
{
throw new InvalidOperationException(
"Invalid percent-encoded string: bad character '" + c + "' in "
+ "escape sequence.");
}
if (c <= '9')
{
return (c - '0');
}
if (c < 'A')
{
throw new InvalidOperationException(
"Invalid percent-encoded string: bad character '" + c + "' in "
+ "escape sequence.");
}
if (c <= 'F')
{
return (c - 'A') + 10;
}
if (c < 'a')
{
throw new InvalidOperationException(
"Invalid percent-encoded string: bad character '" + c + "' in "
+ "escape sequence.");
}
if (c <= 'f')
{
return (c - 'a') + 10;
}
throw new InvalidOperationException(
"Invalid percent-encoded string: bad character '" + c + "' in "
+ "escape sequence.");
}
}
}
| 275 |
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.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Amazon.Util;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
using System.Threading;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Interface for a non-generic cache.
/// </summary>
public interface ICache
{
/// <summary>
/// Clears the entire cache.
/// </summary>
void Clear();
/// <summary>
/// Maximum time to keep an item around after its last use.
/// </summary>
TimeSpan MaximumItemLifespan { get; set; }
/// <summary>
/// How often should the cache be cleared of old items.
/// </summary>
TimeSpan CacheClearPeriod { get; set; }
/// <summary>
/// The number of items in the cache.
/// </summary>
int ItemCount { get; }
}
/// <summary>
/// Interface for a generic cache.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
public interface ICache<TKey, TValue> : ICache
{
/// <summary>
/// Retrieves a value out of the cache or from the source.
/// </summary>
/// <param name="key"></param>
/// <param name="creator"></param>
/// <returns></returns>
TValue GetValue(TKey key, Func<TKey, TValue> creator);
/// <summary>
/// Retrieves a value out of the cache or from the source.
/// If the item was in the cache, isStaleItem is set to true;
/// otherwise, if the item comes from the source, isStaleItem is false.
/// </summary>
/// <param name="key"></param>
/// <param name="creator"></param>
/// <param name="isStaleItem"></param>
/// <returns></returns>
TValue GetValue(TKey key, Func<TKey, TValue> creator, out bool isStaleItem);
/// <summary>
/// Clears a specific value from the cache if it's there.
/// </summary>
/// <param name="key"></param>
void Clear(TKey key);
/// <summary>
/// Returns the keys for all items in the cache.
/// </summary>
/// <returns></returns>
List<TKey> Keys { get; }
/// <summary>
/// Executes specified operation, catches exception, clears the cache for
/// the given key, retries the operation.
/// </summary>
/// <typeparam name="TOut"></typeparam>
/// <param name="key"></param>
/// <param name="operation"></param>
/// <param name="onError"></param>
/// <param name="shouldRetryForException"></param>
/// <returns></returns>
TOut UseCache<TOut>(TKey key, Func<TOut> operation, Action onError, Predicate<Exception> shouldRetryForException);
}
/// <summary>
/// SDK-wide cache.
/// Provides access to caches specific to a particular set of credentials
/// and target region.
/// </summary>
public static class SdkCache
{
private static object cacheLock = new object();
private static Cache<CacheKey, ICache> cache = new Cache<CacheKey, ICache>();
/// <summary>
/// Clear all caches
/// </summary>
public static void Clear()
{
cache.Clear();
}
/// <summary>
/// Clear all caches of a particular type
/// </summary>
/// <param name="cacheType"></param>
public static void Clear(object cacheType)
{
lock (cacheLock)
{
var keys = cache.Keys;
foreach (CacheKey key in keys)
{
if (AWSSDKUtils.AreEqual(key.CacheType, cacheType))
{
var value = cache.GetValue(key, null);
value.Clear();
}
}
}
}
/// <summary>
/// Retrieve a cache of a specific type for a client object.
/// The client object can be null in cases where a cache does
/// not correspond to a specific AWS account or target region.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="client"></param>
/// <param name="cacheIdentifier"></param>
/// <param name="keyComparer"></param>
/// <returns></returns>
public static ICache<TKey, TValue> GetCache<TKey, TValue>(
object client,
object cacheIdentifier,
IEqualityComparer<TKey> keyComparer)
{
return GetCache<TKey, TValue>(client as AmazonServiceClient, cacheIdentifier, keyComparer);
}
/// <summary>
/// Retrieve a cache of a specific type for a client object.
/// The client object can be null in cases where a cache does
/// not correspond to a specific AWS account or target region.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="client"></param>
/// <param name="cacheIdentifier"></param>
/// <param name="keyComparer"></param>
/// <returns></returns>
public static ICache<TKey, TValue> GetCache<TKey, TValue>(
AmazonServiceClient client,
object cacheIdentifier,
IEqualityComparer<TKey> keyComparer)
{
// If client is null, create an empty key to use.
// This supports mock frameworks (where the service is mocked up,
// but there is no client to get credentials/region from) and
// caches that do not depend on a client (such as a cache
// for client-side reflection data).
CacheKey key;
if (client == null)
key = CacheKey.Create(cacheIdentifier);
else
key = CacheKey.Create(client, cacheIdentifier);
ICache value = null;
lock (cacheLock)
{
value = cache.GetValue(key, k => new Cache<TKey, TValue>(keyComparer));
}
var typedValue = value as Cache<TKey, TValue>;
if (value != null && typedValue == null)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"Unable to cast cache of type {0} as cache of type {1}",
value.GetType().FullName,
typeof(Cache<TKey, TValue>).FullName));
}
return typedValue;
}
// Composite cache key consisting of credentials, region, service url, cache type
internal class CacheKey
{
public ImmutableCredentials ImmutableCredentials { get; private set; }
public RegionEndpoint RegionEndpoint { get; private set; }
public string ServiceUrl { get; private set; }
public object CacheType { get; private set; }
private CacheKey()
{
ImmutableCredentials = null;
RegionEndpoint = null;
ServiceUrl = null;
CacheType = null;
}
public static CacheKey Create(AmazonServiceClient client, object cacheType)
{
if (client == null) throw new ArgumentNullException("client");
var key = new CacheKey();
var credentials = client.Credentials;
key.ImmutableCredentials = credentials == null ?
null : credentials.GetCredentials();
key.RegionEndpoint = client.Config.RegionEndpoint;
key.ServiceUrl = client.Config.ServiceURL;
key.CacheType = cacheType;
return key;
}
public static CacheKey Create(object cacheType)
{
var key = new CacheKey();
key.CacheType = cacheType;
return key;
}
#region Public overrides
public override int GetHashCode()
{
return Hashing.Hash(
ImmutableCredentials,
RegionEndpoint,
ServiceUrl,
CacheType);
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
return true;
CacheKey ck = obj as CacheKey;
if (ck == null)
return false;
var allEqual = AWSSDKUtils.AreEqual(
new object[] { this.ImmutableCredentials, this.RegionEndpoint, this.ServiceUrl, this.CacheType },
new object[] { ck.ImmutableCredentials, ck.RegionEndpoint, ck.ServiceUrl, ck.CacheType });
return allEqual;
}
#endregion
}
}
// Implementation of generic ICache<TKey,TValue> interface
internal class Cache<TKey, TValue> : ICache<TKey, TValue>
{
#region Private members
private Dictionary<TKey, CacheItem<TValue>> Contents;
private readonly object CacheLock = new object();
#endregion
#region Constructor
public Cache(IEqualityComparer<TKey> keyComparer = null)
{
Contents = new Dictionary<TKey, CacheItem<TValue>>(keyComparer);
MaximumItemLifespan = DefaultMaximumItemLifespan;
CacheClearPeriod = DefaultCacheClearPeriod;
}
#endregion
#region Public members
public static TimeSpan DefaultMaximumItemLifespan = TimeSpan.FromHours(6);
public static TimeSpan DefaultCacheClearPeriod = TimeSpan.FromHours(1);
public DateTime LastCacheClean { get; private set; }
#endregion
#region ICache implementation
public TValue GetValue(TKey key, Func<TKey, TValue> creator)
{
bool isStaleItem;
return GetValueHelper(key, out isStaleItem, creator);
}
public TValue GetValue(TKey key, Func<TKey, TValue> creator, out bool isStaleItem)
{
return GetValueHelper(key, out isStaleItem, creator);
}
public void Clear(TKey key)
{
lock (CacheLock)
{
Contents.Remove(key);
}
}
public void Clear()
{
lock (CacheLock)
{
Contents.Clear();
LastCacheClean = GetCorrectedLocalTime();
}
}
public List<TKey> Keys
{
get
{
lock (CacheLock)
{
return Contents.Keys.ToList();
}
}
}
private TimeSpan maximumItemLifespan;
public TimeSpan MaximumItemLifespan
{
get { return maximumItemLifespan; }
set
{
if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException("value");
maximumItemLifespan = value;
}
}
private TimeSpan cacheClearPeriod;
public TimeSpan CacheClearPeriod
{
get { return cacheClearPeriod; }
set
{
if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException("value");
cacheClearPeriod = value;
}
}
public int ItemCount
{
get
{
lock (CacheLock)
{
return Contents.Count;
}
}
}
public TOut UseCache<TOut>(TKey key, Func<TOut> operation,
Action onError, Predicate<Exception> shouldRetryForException)
{
TOut output = default(TOut);
try
{
output = operation();
}
catch(Exception e)
{
// if predicate is specified, check whether to retry on exception
// otherwise, retry
var shouldRetry = shouldRetryForException == null || shouldRetryForException(e);
if (shouldRetry)
{
// clear existing value
Clear(key);
// allow calling code to cleanup
if (onError != null)
onError();
// retry operation
output = operation();
}
else
throw;
}
return output;
}
#endregion
#region Private methods and classes
private TValue GetValueHelper(TKey key, out bool isStaleItem, Func<TKey, TValue> creator = null)
{
isStaleItem = true;
CacheItem<TValue> item = null;
if (AWSConfigs.UseSdkCache)
{
lock (CacheLock)
{
if (!Contents.TryGetValue(key, out item) || !IsValidItem(item))
{
if (creator == null)
throw new InvalidOperationException("Unable to calculate value for key " + key);
var value = creator(key);
isStaleItem = false;
item = new CacheItem<TValue>(value);
Contents[key] = item;
RemoveOldItems_Locked();
}
}
}
else
{
if (creator == null)
throw new InvalidOperationException("Unable to calculate value for key " + key);
var value = creator(key);
item = new CacheItem<TValue>(value);
isStaleItem = false;
}
if (item == null)
throw new InvalidOperationException("Unable to find value for key " + key);
return item.Value;
}
private bool IsValidItem(CacheItem<TValue> item)
{
if (item == null)
return false;
var cutoff = GetCorrectedLocalTime() - this.MaximumItemLifespan;
if (item.LastUseTime < cutoff)
return false;
return true;
}
private void RemoveOldItems_Locked()
{
if (LastCacheClean + CacheClearPeriod > AWSConfigs.utcNowSource().ToLocalTime())
return;
// Remove all items that were not accessed since the cutoff.
// Using a cutoff is more optimal than item.Age, as we only need
// to do DateTime calculation once, not for each item.
var cutoff = GetCorrectedLocalTime() - MaximumItemLifespan;
var keysToRemove = new List<TKey>();
foreach (var kvp in Contents)
{
var key = kvp.Key;
var item = kvp.Value;
if (item == null || item.LastUseTime < cutoff)
keysToRemove.Add(key);
}
foreach (var key in keysToRemove)
Contents.Remove(key);
LastCacheClean = GetCorrectedLocalTime();
}
private class CacheItem<T>
{
private T _value;
public T Value
{
get
{
LastUseTime = GetCorrectedLocalTime();
return _value;
}
private set
{
_value = value;
}
}
public DateTime LastUseTime { get; private set; }
public CacheItem(T value)
{
Value = value;
LastUseTime = GetCorrectedLocalTime();
}
}
private static DateTime GetCorrectedLocalTime()
{
#pragma warning disable CS0612 // Type or member is obsolete
return AWSSDKUtils.CorrectedUtcNow.ToLocalTime();
#pragma warning restore CS0612 // Type or member is obsolete
}
#endregion
}
}
| 524 |
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.Text;
using System.IO;
using Amazon.Util;
using System.Linq;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Utilities for converting objects to strings. Used by the marshaller classes.
/// </summary>
public static class StringUtils
{
private static readonly Encoding UTF_8 = Encoding.UTF8;
public static string FromString(String value)
{
return value;
}
public static string FromStringWithSlashEncoding(String value)
{
return AWSSDKUtils.UrlEncodeSlash(FromString(value));
}
public static string FromString(ConstantClass value)
{
return value == null ? "" : value.Intern().Value;
}
public static string FromMemoryStream(MemoryStream value)
{
return Convert.ToBase64String(value.ToArray());
}
public static string FromInt(int value)
{
return value.ToString(CultureInfo.InvariantCulture);
}
public static string FromInt(int? value)
{
if (value != null)
return value.Value.ToString(CultureInfo.InvariantCulture);
return null;
}
public static string FromLong(long value)
{
return value.ToString(CultureInfo.InvariantCulture);
}
public static string FromFloat(float value)
{
return value.ToString(CultureInfo.InvariantCulture);
}
public static string FromBool(bool value)
{
return value ? "true" : "false";
}
[Obsolete("This method doesn't handle correctly non-UTC DateTimes. Use FromDateTimeToISO8601 instead.", false)]
public static string FromDateTime(DateTime value)
{
return value.ToString(AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts a DateTime to ISO8601 formatted string.
/// </summary>
public static string FromDateTimeToISO8601(DateTime value)
{
return value.ToUniversalTime().ToString(AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts a DateTime to RFC822 formatted string.
/// </summary>
public static string FromDateTimeToRFC822(DateTime value)
{
return value.ToUniversalTime().ToString(
AWSSDKUtils.RFC822DateFormat, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts a DateTime to Unix epoch time formatted string.
/// </summary>
public static string FromDateTimeToUnixTimestamp(DateTime value)
{
return AWSSDKUtils.ConvertToUnixEpochSecondsString(value);
}
public static string FromDouble(double value)
{
return value.ToString(CultureInfo.InvariantCulture);
}
public static string FromDecimal(decimal value)
{
return value.ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Combines a list of enums into a comma-separated string to be marshalled as a header
/// </summary>
/// <param name="values">List of enums</param>
/// <returns>Header value representing the list of enums</returns>
public static string FromList(IEnumerable<Enum> values)
{
return FromList(values?.Select(x => x.ToString()));
}
/// <summary>
/// Combines a list of enums into a comma-separated string to be marshalled as a header
/// </summary>
/// <param name="values">List of enums</param>
/// <returns>Header value representing the list of enums</returns>
public static string FromList(List<Enum> values)
{
return FromList(values?.Select(x => x.ToString()));
}
/// <summary>
/// Combines an enumerable of ConstantClass enums into a comma-separated string to be marshalled as a header
/// </summary>
/// <param name="values">List of enums</param>
/// <returns>Header value representing the list of enums</returns>
public static string FromList<T>(IEnumerable<T> values) where T : ConstantClass
{
return FromList(values?.Select(x => x.ToString()));
}
/// <summary>
/// Combines a list of ConstantClass enums into a comma-separated string to be marshalled as a header
/// </summary>
/// <param name="values">List of enums</param>
/// <returns>Header value representing the list of enums</returns>
public static string FromList<T>(List<T> values) where T : ConstantClass
{
return FromList(values?.Select(x => x.ToString()));
}
/// <summary>
/// Combines a list of strings into a comma-separated string to be marshalled as a header
/// </summary>
/// <param name="values">List of strings</param>
/// <returns>Header value representing the list of strings</returns>
public static string FromList(IEnumerable<string> values)
{
if (values == null || values.Count() == 0)
{
return "";
}
// Comma separate any non-null/non-empty entries with below formatting
return string.Join(",", values.Where(x => !string.IsNullOrEmpty(x)).Select(x => EscapeHeaderListEntry(x)).ToArray());
}
/// <summary>
/// Wraps an item to be sent in
/// </summary>
/// <param name="headerListEntry">Single item from the header's list</param>
/// <returns>Item wrapped in double quotes if appropriate</returns>
private static string EscapeHeaderListEntry(string headerListEntry)
{
// If it's already surounded by double quotes, no further formatting needed
if (headerListEntry.Length >= 2 && headerListEntry[0] == '\"' && headerListEntry[headerListEntry.Length - 1] == '\"')
{
return headerListEntry;
}
else if (headerListEntry.Contains(",") || headerListEntry.Contains("\""))
{
// The string must be double quoted if double quote(s) or comma(s) appear within the string
return $"\"{headerListEntry}\"";
}
return headerListEntry;
}
public static long Utf8ByteLength(string value)
{
if (value == null)
{
return 0;
}
return UTF_8.GetByteCount(value);
}
}
}
| 209 |
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;
using Amazon.Util.Internal;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Stream wrapper to append trailing headers, including an optional
/// rolling checksum for a request with an unsigned payload.
/// </summary>
public class TrailingHeadersWrapperStream : WrapperStream
{
private const string STREAM_NEWLINE = "\r\n";
private const string EMPTY_CHUNK = "0\r\n";
private const int NEWLINE_LENGTH = 2; // additional length for any new lines
private const int EMPTY_CHUNK_LENGTH = 3; // additional length for an empty chunk "0CRLF"
private const int HEADER_ROW_PADDING_LENGTH = 3; // additional length for each row of a trailing header, 1 for ':' between the key and value, plus 2 for CRLF
private Stream _baseStream;
private HashAlgorithm _hashAlgorithm;
private IDictionary<string, string> _trailingHeaders;
private CoreChecksumAlgorithm _checksumAlgorithm;
string _prefix;
string _suffix;
bool _haveFinishedPrefix;
bool _haveFinishedStream;
bool _haveFinishedSuffix;
int _prefixPosition;
int _suffixPosition;
/// <summary>
/// Initiates a stream wrapper to append trailing headers to an unsigned payload
/// </summary>
/// <param name="baseStream">Stream to wrap</param>
/// <param name="trailingHeaders">Trailing headers to append after the wrapped stream</param>
public TrailingHeadersWrapperStream(Stream baseStream, IDictionary<string, string> trailingHeaders) : base(baseStream)
{
if (trailingHeaders == null || trailingHeaders.Count == 0)
{
throw new AmazonClientException($"{nameof(TrailingHeadersWrapperStream)} was initialized without any trailing headers.");
}
_baseStream = baseStream;
_trailingHeaders = trailingHeaders;
_prefix = GenerateContentChunkLength();
}
/// <summary>
/// Initiates a stream wrapper to append trailing headers to an unsigned payload,
/// with a trailing checksum
/// </summary>
/// <param name="baseStream">Stream to wrap</param>
/// <param name="trailingHeaders">Header keys and values to append after the stream's conent</param>
/// <param name="checksumAlgorithm">Algorithm to use to calculate the stream's checksum</param>
public TrailingHeadersWrapperStream(
Stream baseStream,
IDictionary<string, string> trailingHeaders,
CoreChecksumAlgorithm checksumAlgorithm) : this(baseStream, trailingHeaders)
{
if (checksumAlgorithm != CoreChecksumAlgorithm.NONE)
{
_checksumAlgorithm = checksumAlgorithm;
_hashAlgorithm = CryptoUtilFactory.GetChecksumInstance(checksumAlgorithm);
}
}
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte
/// array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if
/// that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
#if AWS_ASYNC_API
return ReadInternal(buffer, offset, count, false, CancellationToken.None).GetAwaiter().GetResult();
#else
return ReadInternal(buffer, offset, count, false);
#endif
}
#if AWS_ASYNC_API
/// <summary>
/// Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte
/// array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if
/// that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return await ReadInternal(buffer, offset, count, true, cancellationToken).ConfigureAwait(false);
}
#endif
#if AWS_ASYNC_API
private async Task<int> ReadInternal(byte[] buffer, int offset, int count, bool useAsyncRead, CancellationToken cancellationToken)
#else
private int ReadInternal(byte[] buffer, int offset, int count, bool useAsyncRead)
#endif
{
var countRemainingForThisRead = count;
var countFromPrefix = 0;
var countFromStream = 0;
var countFromSuffix = 0;
if (countRemainingForThisRead > 0 && !_haveFinishedPrefix)
{
countFromPrefix = ReadFromPrefix(buffer, offset, countRemainingForThisRead);
offset += countFromPrefix;
countRemainingForThisRead -= countFromPrefix;
}
if (countRemainingForThisRead > 0 && !_haveFinishedStream)
{
// First read from the stream into a buffer here
byte[] thisBuffer = new byte[countRemainingForThisRead];
if (!useAsyncRead)
{
countFromStream = base.Read(thisBuffer, 0, countRemainingForThisRead);
}
else
{
#if AWS_ASYNC_API
countFromStream = await base.ReadAsync(thisBuffer, 0, countRemainingForThisRead, cancellationToken).ConfigureAwait(false);
#else
throw new AmazonClientException($"Attempted to call {nameof(TrailingHeadersWrapperStream)}.ReadAsync from an unsupported target platform.");
#endif
}
// Update rolling checksum for that content, and copy it to the output buffer
if (countFromStream != 0)
{
if (_hashAlgorithm != null)
{
_hashAlgorithm.TransformBlock(thisBuffer, 0, countFromStream, thisBuffer, 0);
}
Buffer.BlockCopy(thisBuffer, 0, buffer, offset, countFromStream);
}
else // finished the stream, so finalize checksum
{
if (_hashAlgorithm != null)
{
_hashAlgorithm.TransformFinalBlock(ArrayEx.Empty<byte>(), 0, 0);
}
_haveFinishedStream = true;
_suffix = GenerateTrailingHeaderChunk();
}
offset += countFromStream;
countRemainingForThisRead -= countFromStream;
}
if (countRemainingForThisRead > 0 && _haveFinishedStream && !_haveFinishedSuffix)
{
countFromSuffix = ReadFromSuffix(buffer, offset, countRemainingForThisRead);
}
return countFromPrefix + countFromStream + countFromSuffix;
}
/// <summary>
/// Generates the prefix for the content chunk, which is
/// the content's length in hex followed by CRLF
/// </summary>
/// <returns>Length of a stream chunk</returns>
private string GenerateContentChunkLength()
{
return $"{_baseStream.Length.ToString("X", CultureInfo.InvariantCulture)}{STREAM_NEWLINE}";
}
/// <summary>
/// Copies the chunk length prefix to the output buffer
/// </summary>
/// <param name="buffer">The buffer to write the data into</param>
/// <param name="offset">The byte offset in buffer at which to begin copying data</param>
/// <param name="countRemainingForThisRead">The maximum number of bytes to copy</param>
/// <returns>Number of bytes copied</returns>
private int ReadFromPrefix(byte[] buffer, int offset, int countRemainingForThisRead)
{
var charsLeftInPrefix = _prefix.Length - _prefixPosition;
if (charsLeftInPrefix <= countRemainingForThisRead)
{
Encoding.Default.GetBytes(_prefix, _prefixPosition, charsLeftInPrefix, buffer, offset);
_haveFinishedPrefix = true;
return charsLeftInPrefix;
}
else // can only read a subset of the prefix (the rest of countRemainingForThisRead)
{
Encoding.Default.GetBytes(_prefix, _prefixPosition, countRemainingForThisRead, buffer, offset);
_prefixPosition += countRemainingForThisRead;
return countRemainingForThisRead;
}
}
/// <summary>
/// Generates the trailing header content, assuming the rolling checksum is now finalized
/// </summary>
/// <returns>Trailing headers as a single string</returns>
private string GenerateTrailingHeaderChunk()
{
var trailer = new StringBuilder();
// End the data chunk
trailer.Append(STREAM_NEWLINE);
// Append a chunk of size 0
trailer.Append(EMPTY_CHUNK);
// Append trailing headers, including special handling for the checksum.
// The order here must match the order of keys sent already in the X-Amz-Trailer header.
foreach (var kvp in _trailingHeaders.OrderBy(kvp => kvp.Key))
{
if (_checksumAlgorithm != CoreChecksumAlgorithm.NONE && ChecksumUtils.GetChecksumHeaderKey(_checksumAlgorithm) == kvp.Key)
{
// Use the calculated checksum, since it likely wasn't set in advance
trailer.Append($"{kvp.Key}:{Convert.ToBase64String(_hashAlgorithm.Hash)}{STREAM_NEWLINE}");
}
else
{
trailer.Append($"{kvp.Key}:{kvp.Value}{STREAM_NEWLINE}");
}
}
// Append a final trailing CRLF
trailer.Append(STREAM_NEWLINE);
return trailer.ToString();
}
/// <summary>
/// Copies the trailing header suffix to the output buffer
/// </summary>
/// <param name="buffer">The buffer to write the data into</param>
/// <param name="offset">The byte offset in buffer at which to begin copying data</param>
/// <param name="countRemainingForThisRead">The maximum number of bytes to copy</param>
/// <returns>Number of bytes copied</returns>
private int ReadFromSuffix(byte[] buffer, int offset, int countRemainingForThisRead)
{
var charsLeftInSuffix = _suffix.Length - _suffixPosition;
// If the current suffix fits entirely within the current read buffer
if (charsLeftInSuffix <= countRemainingForThisRead)
{
Encoding.Default.GetBytes(_suffix, _suffixPosition, charsLeftInSuffix, buffer, offset);
_haveFinishedSuffix = true;
return charsLeftInSuffix;
}
else // else we can only read a subset of the prefix (the rest of countRemainingForThisRead)
{
Encoding.Default.GetBytes(_suffix, _suffixPosition, countRemainingForThisRead, buffer, offset);
_suffixPosition += countRemainingForThisRead;
return countRemainingForThisRead;
}
}
/// <summary>
/// Gets the length in bytes of the stream
/// </summary>
public override long Length => CalculateLength(_trailingHeaders, _checksumAlgorithm, _baseStream.Length);
/// <summary>
/// Calculates the length in bytes of a TrailingChecksumWrapperStream initialized
/// with the given trailing headers and optional checksum
/// </summary>
/// <param name="trailingHeaders">Dictionary of trailing headers</param>
/// <param name="checksumAlgorithm">Trailing checksum</param>
/// <param name="baseStreamLength">Length of the base stream in bytes</param>
/// <returns>Length of a TrailingChecksumWrapperStream with given parameters, in bytes</returns>
public static long CalculateLength(IDictionary<string, string> trailingHeaders, CoreChecksumAlgorithm checksumAlgorithm, long baseStreamLength)
{
var prefixLength = baseStreamLength.ToString("X", CultureInfo.InvariantCulture).Length;
var trailingHeaderLength = 0;
if (trailingHeaders != null)
{
foreach (var key in trailingHeaders.Keys)
{
if (checksumAlgorithm != CoreChecksumAlgorithm.NONE && ChecksumUtils.GetChecksumHeaderKey(checksumAlgorithm) == key)
{
trailingHeaderLength += key.Length +
CryptoUtilFactory.GetChecksumBase64Length(checksumAlgorithm) + HEADER_ROW_PADDING_LENGTH;
}
else
{
trailingHeaderLength += key.Length + trailingHeaders[key].Length + HEADER_ROW_PADDING_LENGTH;
}
}
}
return prefixLength +
NEWLINE_LENGTH +
baseStreamLength +
NEWLINE_LENGTH +
EMPTY_CHUNK_LENGTH +
trailingHeaderLength +
NEWLINE_LENGTH;
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking
/// </summary>
public override bool CanSeek => false;
/// <summary>
/// Gets whether this stream has a length
/// </summary>
internal override bool HasLength => (_baseStream != null) || (_trailingHeaders != null);
}
}
| 342 |
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;
using System.IO;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// A wrapper stream.
/// </summary>
public class WrapperStream : Stream
{
/// <summary>
/// Base stream.
/// </summary>
protected Stream BaseStream { get; private set; }
/// <summary>
/// Initializes WrapperStream with a base stream.
/// </summary>
/// <param name="baseStream"></param>
public WrapperStream(Stream baseStream)
{
if (baseStream == null)
throw new ArgumentNullException("baseStream");
BaseStream = baseStream;
}
/// <summary>
/// Returns the first base non-WrapperStream.
/// </summary>
/// <returns>First base stream that is non-WrapperStream.</returns>
public Stream GetNonWrapperBaseStream()
{
Stream baseStream = this;
do
{
var partialStream = baseStream as PartialWrapperStream;
if (partialStream != null)
return partialStream;
baseStream = (baseStream as WrapperStream).BaseStream;
} while (baseStream is WrapperStream);
return baseStream;
}
/// <summary>
/// Returns the first base non-WrapperStream.
/// </summary>
/// <returns>First base stream that is non-WrapperStream.</returns>
public Stream GetSeekableBaseStream()
{
Stream baseStream = this;
do
{
if (baseStream.CanSeek)
return baseStream;
baseStream = (baseStream as WrapperStream).BaseStream;
} while (baseStream is WrapperStream);
if (!baseStream.CanSeek)
throw new InvalidOperationException("Unable to find seekable stream");
return baseStream;
}
/// <summary>
/// Returns the first base non-WrapperStream.
/// </summary>
/// <param name="stream">Potential WrapperStream</param>
/// <returns>Base non-WrapperStream.</returns>
public static Stream GetNonWrapperBaseStream(Stream stream)
{
WrapperStream wrapperStream = stream as WrapperStream;
if (wrapperStream == null)
return stream;
return wrapperStream.GetNonWrapperBaseStream();
}
public Stream SearchWrappedStream(Func<Stream, bool> condition)
{
Stream baseStream = this;
do
{
if (condition(baseStream))
return baseStream;
if (!(baseStream is WrapperStream))
return null;
baseStream = (baseStream as WrapperStream).BaseStream;
} while (baseStream != null);
return baseStream;
}
public static Stream SearchWrappedStream(Stream stream, Func<Stream, bool> condition)
{
WrapperStream wrapperStream = stream as WrapperStream;
if (wrapperStream == null)
return condition(stream) ? stream : null;
return wrapperStream.SearchWrappedStream(condition);
}
#region Stream overrides
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// True if the stream supports reading; otherwise, false.
/// </summary>
public override bool CanRead
{
get { return BaseStream.CanRead; }
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// True if the stream supports seeking; otherwise, false.
/// </summary>
public override bool CanSeek
{
get { return BaseStream.CanSeek; }
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// True if the stream supports writing; otherwise, false.
/// </summary>
public override bool CanWrite
{
get { return BaseStream.CanWrite; }
}
/// <summary>
/// Closes the current stream and releases any resources (such as sockets and
/// file handles) associated with the current stream.
/// </summary>
#if !NETSTANDARD
public override void Close()
{
BaseStream.Close();
}
#else
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
BaseStream.Dispose();
}
#endif
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
public override long Length
{
get { return BaseStream.Length; }
}
/// <summary>
/// Gets or sets the position within the current stream.
/// </summary>
public override long Position
{
get
{
return BaseStream.Position;
}
set
{
BaseStream.Position = value;
}
}
/// <summary>
/// Gets or sets a value, in miliseconds, that determines how long the stream
/// will attempt to read before timing out.
/// </summary>
public override int ReadTimeout
{
get
{
return BaseStream.ReadTimeout;
}
set
{
BaseStream.ReadTimeout = value;
}
}
/// <summary>
/// Gets or sets a value, in miliseconds, that determines how long the stream
/// will attempt to write before timing out.
/// </summary>
public override int WriteTimeout
{
get
{
return BaseStream.WriteTimeout;
}
set
{
BaseStream.WriteTimeout = value;
}
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written
/// to the underlying device.
/// </summary>
public override void Flush()
{
BaseStream.Flush();
}
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position
/// within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the
/// number of bytes requested if that many bytes are not currently available,
/// or zero (0) if the end of the stream has been reached.
/// </returns>
public override int Read(byte[] buffer, int offset, int count)
{
return BaseStream.Read(buffer, offset, count);
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">
/// A value of type System.IO.SeekOrigin indicating the reference point used
/// to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
return BaseStream.Seek(offset, origin);
}
/// <summary>
/// Sets the length of the current stream.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.</param>
public override void SetLength(long value)
{
BaseStream.SetLength(value);
}
/// <summary>
/// Writes a sequence of bytes to the current stream and advances the current
/// position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">
/// An array of bytes. This method copies count bytes from buffer to the current stream.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin copying bytes to the
/// current stream.
/// </param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
public override void Write(byte[] buffer, int offset, int count)
{
BaseStream.Write(buffer, offset, count);
}
#if AWS_ASYNC_API
/// <summary>
/// Asynchronously clears all buffers for this stream and causes any buffered data
/// to be written to the underlying device.
/// </summary>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests. The default value is
/// System.Threading.CancellationToken.None.
/// </param>
/// <returns>
/// A task that represents the asynchronous flush operation.
/// </returns>
public override Task FlushAsync(CancellationToken cancellationToken)
{
return BaseStream.FlushAsync(cancellationToken);
}
/// <summary>
/// Asynchronously reads a sequence of bytes from the current stream, advances
/// the position within the stream by the number of bytes read, and monitors
/// cancellation requests.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified
/// byte array with the values between offset and (offset + count - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin storing the data read
/// from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests. The default value is
/// System.Threading.CancellationToken.None.
/// </param>
/// <returns>
/// A task that represents the asynchronous read operation. The value of the TResult
/// parameter contains the total number of bytes read into the buffer. This can be
/// less than the number of bytes requested if that many bytes are not currently
/// available, or zero (0) if the end of the stream has been reached.
/// </returns>
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return BaseStream.ReadAsync(buffer, offset, count, cancellationToken);
}
/// <summary>
/// Asynchronously writes a sequence of bytes to the current stream and advances the
/// current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">
/// An array of bytes. This method copies count bytes from buffer to the current stream.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin copying bytes to the
/// current stream.
/// </param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
/// <param name="cancellationToken">
/// The token to monitor for cancellation requests. The default value is
/// System.Threading.CancellationToken.None.
/// </param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return BaseStream.WriteAsync(buffer, offset, count, cancellationToken);
}
#endif
#endregion
internal virtual bool HasLength
{
get
{
return true;
}
}
}
}
| 390 |
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;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Overridden StringWriter that escapes additional characters in XML requests for consistency across AWS SDKs.
/// There isn't an XmlWriterSettings.NewLineHandling value which matches the desired
/// encoding, so this replaces the characters that NewLineHandling.Entitize doesn't encode
/// </summary>
public class XMLEncodedStringWriter : StringWriter
{
public XMLEncodedStringWriter(IFormatProvider formatProvider) : base(formatProvider)
{
}
/// <summary>
/// Writes a range of a character array to the underlying string buffer and
/// encodes additional characters for AWS XML requests
/// </summary>
/// <param name="buffer">Characters to write to underlying string buffer</param>
/// <param name="index">Position in buffer to start writing from</param>
/// <param name="count">Number of characters to write</param>
public override void Write(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (buffer.Length - index < count)
{
throw new ArgumentException();
}
// Write directly to the underlying StringWriter's internal StringBuilder
var stringBuilder = GetStringBuilder();
for (int i = index; i < index + count; i++)
{
switch (buffer[i])
{
// We're still relying on NewLineHandling.Entitize to handle \r
case '\n':
stringBuilder.Append("
");
break;
case '\u0085':
stringBuilder.Append("…");
break;
case '\u2028':
stringBuilder.Append("
");
break;
default:
stringBuilder.Append(buffer[i]);
break;
}
}
}
}
}
| 83 |
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.Security.Cryptography;
using System.Text;
using Amazon.Runtime;
using ThirdParty.MD5;
namespace Amazon.Runtime.Internal.Util
{
public partial class HashingWrapper : IHashingWrapper
{
private static string MD5ManagedName = typeof(MD5Managed).FullName;
private HashAlgorithm _algorithm = null;
private void Init(string algorithmName)
{
if (string.Equals(MD5ManagedName, algorithmName, StringComparison.Ordinal))
_algorithm = new MD5Managed();
else
throw new ArgumentOutOfRangeException(algorithmName, "Unsupported hashing algorithm");
}
#region IHashingWrapper Members
public void Clear()
{
_algorithm.Initialize();
}
public byte[] ComputeHash(byte[] buffer)
{
return _algorithm.ComputeHash(buffer);
}
public byte[] ComputeHash(Stream stream)
{
return _algorithm.ComputeHash(stream);
}
public void AppendBlock(byte[] buffer, int offset, int count)
{
// We're not transforming the data, so don't use the outputBuffer arguments
_algorithm.TransformBlock(buffer, offset, count, null, 0);
}
public byte[] AppendLastBlock(byte[] buffer, int offset, int count)
{
_algorithm.TransformFinalBlock(buffer, offset, count);
return _algorithm.Hash;
}
#endregion
#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)
{
var disposable = _algorithm as IDisposable;
if (disposing && disposable != null)
{
disposable.Dispose();
_algorithm = null;
}
}
#endregion
}
public class HashingWrapperMD5 : HashingWrapper
{
public HashingWrapperMD5()
: base(typeof(MD5Managed).FullName)
{ }
}
}
| 103 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// This is a utility class to be used in last resort for code paths that are synchronous but need to call an asynchronous method.
/// This should never be used for methods that are called at high volume as this utility class has a performance cost. For example this
/// class was added for the refreshing credentials like Cognito which would need to use this about once an hour.
/// </summary>
public static class AsyncHelpers
{
public static void RunSync(Func<Task> workItem)
{
var prevContext = SynchronizationContext.Current;
try
{
var synch = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synch);
synch.Post(async _ =>
{
try
{
await workItem().ConfigureAwait(false);
}
catch (Exception e)
{
synch.ObjectException = e;
throw;
}
finally
{
synch.EndMessageLoop();
}
}, null);
synch.BeginMessageLoop();
}
finally
{
SynchronizationContext.SetSynchronizationContext(prevContext);
}
}
public static T RunSync<T>(Func<Task<T>> workItem)
{
var prevContext = SynchronizationContext.Current;
try
{
var synch = new ExclusiveSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(synch);
T ret = default(T);
synch.Post(async _ =>
{
try
{
ret = await workItem().ConfigureAwait(false);
}
catch (Exception e)
{
synch.ObjectException = e;
throw;
}
finally
{
synch.EndMessageLoop();
}
}, null);
synch.BeginMessageLoop();
return ret;
}
finally
{
SynchronizationContext.SetSynchronizationContext(prevContext);
}
}
private class ExclusiveSynchronizationContext : SynchronizationContext
{
private bool done;
public Exception ObjectException { get; set; }
readonly AutoResetEvent pendingObjects = new AutoResetEvent(false);
readonly Queue<Tuple<SendOrPostCallback, object>> objects =
new Queue<Tuple<SendOrPostCallback, object>>();
public override void Send(SendOrPostCallback d, object state)
{
throw new NotSupportedException("We cannot send to our same thread");
}
public override void Post(SendOrPostCallback d, object state)
{
lock (objects)
{
objects.Enqueue(Tuple.Create(d, state));
}
pendingObjects.Set();
}
public void EndMessageLoop()
{
Post(_ => done = true, null);
}
public void BeginMessageLoop()
{
while (!done)
{
Tuple<SendOrPostCallback, object> workItem = null;
lock (objects)
{
if (objects.Count > 0)
{
workItem = objects.Dequeue();
}
}
if (workItem != null)
{
workItem.Item1(workItem.Item2);
if (ObjectException != null)
ExceptionDispatchInfo.Capture(ObjectException).Throw();
}
else
{
pendingObjects.WaitOne();
}
}
}
public override SynchronizationContext CreateCopy()
{
return this;
}
}
}
}
| 141 |
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.Security.Cryptography;
using System.Text;
using Amazon.Runtime;
using ThirdParty.MD5;
namespace Amazon.Runtime.Internal.Util
{
public partial class HashingWrapper : IHashingWrapper
{
private static string MD5ManagedName = typeof(MD5Managed).FullName;
private HashAlgorithm _algorithm = null;
private void Init(string algorithmName)
{
if (string.Equals(MD5ManagedName, algorithmName, StringComparison.Ordinal))
_algorithm = new MD5Managed();
else
throw new ArgumentOutOfRangeException(algorithmName, "Unsupported hashing algorithm");
}
#region IHashingWrapper Members
public void Clear()
{
_algorithm.Initialize();
}
public byte[] ComputeHash(byte[] buffer)
{
return _algorithm.ComputeHash(buffer);
}
public byte[] ComputeHash(Stream stream)
{
return _algorithm.ComputeHash(stream);
}
public void AppendBlock(byte[] buffer, int offset, int count)
{
// We're not transforming the data, so don't use the outputBuffer arguments
_algorithm.TransformBlock(buffer, offset, count, null, 0);
}
public byte[] AppendLastBlock(byte[] buffer, int offset, int count)
{
_algorithm.TransformFinalBlock(buffer, offset, count);
return _algorithm.Hash;
}
#endregion
#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)
{
var disposable = _algorithm as IDisposable;
if (disposing && disposable != null)
{
disposable.Dispose();
_algorithm = null;
}
}
#endregion
}
public class HashingWrapperMD5 : HashingWrapper
{
public HashingWrapperMD5()
: base(typeof(MD5Managed).FullName)
{ }
}
}
| 103 |
aws-sdk-net | aws | C# | using System;
using System.Net;
namespace Amazon.Runtime.Internal.Util
{
/// <summary>
/// Custom WebProxy implementation that creates a webproxy based on
/// user inputs(Host name and port number)
/// </summary>
public class WebProxy : IWebProxy
{
public WebProxy(string proxyUri)
: this(new Uri(proxyUri))
{
}
/// <summary>
/// Set the ProxyUri
/// </summary>
public WebProxy(Uri proxyUri)
{
this.ProxyUri = proxyUri;
}
/// <summary>
/// Create a Uri based on the user inputs(Host name and port number)
/// </summary>
public WebProxy(string proxyHost, int proxyPort): this(new Uri("http://"+ proxyHost + ":" + proxyPort))
{
}
/// <summary>
/// Proxy Uri property
/// </summary>
public Uri ProxyUri { get; set; }
/// <summary>
/// Proxy Credentials property
/// </summary>
public ICredentials Credentials { get; set; }
/// <summary>
/// Getter to fetch the set proxy
/// </summary>
public Uri GetProxy(Uri destination)
{
return this.ProxyUri;
}
/// <summary>
/// Method to determine if the proxy should be bypassed when accessing an internet source
/// </summary>
public bool IsBypassed(Uri host)
{
return false; /* Proxy all requests */
}
}
} | 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.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This class is no longer used anymore and should be avoided as it is just meant
/// as a last resort when blending async and sync operations. The code is still
/// here to support versions before 3.3.9.0 of AWSSDK.DynamoDBv2.
/// </summary>
public static class AsyncRunner
{
public static Task Run(Action action, CancellationToken cancellationToken)
{
return Run<object>(() =>
{
action();
return null;
}, cancellationToken);
}
public static Task<T> Run<T>(Func<T> action, CancellationToken cancellationToken)
{
return Task<T>.Run(async () =>
{
Exception exception = null;
T result = default(T);
using (var semaphore = new SemaphoreSlim(0))
{
Thread thread = new Thread(() =>
{
try
{
result = action();
}
catch (Exception e)
{
exception = e;
}
finally
{
semaphore.Release();
}
});
#if !NETSTANDARD
using (var ctr = cancellationToken.Register(() =>
{
if (thread.IsAlive)
thread.Abort();
}))
#endif
{
thread.Start();
await semaphore.WaitAsync().ConfigureAwait(false);
thread.Join();
if (exception != null)
{
cancellationToken.ThrowIfCancellationRequested();
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(exception).Throw();
}
return result;
}
}
}, cancellationToken);
}
}
} | 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.Linq;
using System.Text;
namespace Amazon.Runtime
{
public abstract partial class AmazonWebServiceRequest
{
private TimeSpan? timeoutInternal = null;
/// <summary>
/// Overrides the default request timeout value.
/// </summary>
/// <remarks>
/// <para>
/// If the value is set, the value is assigned to the Timeout property of the HTTPWebRequest/HttpClient object used
/// to send requests.
/// </para>
/// <para>
/// Please specify a timeout value only if the operation will not complete within the default intervals
/// specified for an HttpWebRequest/HttpClient.
/// </para>
/// </remarks>
/// <exception cref="System.ArgumentNullException">The timeout specified is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">The timeout specified is less than or equal to zero and is not Infinite.</exception>
/// <seealso cref="P:System.Net.HttpWebRequest.Timeout"/>
/// <seealso cref="P:System.Net.Http.HttpClient.Timeout"/>
protected internal TimeSpan? TimeoutInternal
{
get { return this.timeoutInternal; }
protected set
{
ClientConfig.ValidateTimeout(value);
this.timeoutInternal = value;
}
}
private TimeSpan? readWriteTimeoutInternal = null;
/// <summary>
/// Overrides the default read-write timeout value.
/// </summary>
/// <remarks>
/// <para>
/// If the value is set, the value is assigned to the ReadWriteTimeout property of the HTTPWebRequest/WebRequestHandler object used
/// to send requests.
/// </para>
/// <exception cref="System.ArgumentNullException">The timeout specified is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">The timeout specified is less than or equal to zero and is not Infinite.</exception>
/// </remarks>
/// <seealso cref="P:System.Net.HttpWebRequest.ReadWriteTimeout"/>
/// <seealso cref="P:System.Net.Http.WebRequestHandler.ReadWriteTimeout"/>
protected internal TimeSpan? ReadWriteTimeoutInternal
{
get { return this.readWriteTimeoutInternal; }
protected set
{
ClientConfig.ValidateTimeout(value);
this.readWriteTimeoutInternal = value;
}
}
}
}
| 80 |
aws-sdk-net | aws | C# | using System;
using System.Globalization;
using System.Net;
using Amazon.Runtime.Internal.Util;
using Amazon.Runtime.SharedInterfaces;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Collection of helper methods for constructing the necessary Service client to
/// interrogate AWS SSO Services.
/// </summary>
public static class SSOServiceClientHelpers
{
public static ICoreAmazonSSOOIDC BuildSSOIDCClient(
RegionEndpoint region,
#if BCL
WebProxy proxySettings = null
#elif NETSTANDARD
IWebProxy proxySettings = null
#endif
)
{
return CreateClient<ICoreAmazonSSOOIDC>(
region,
ServiceClientHelpers.SSO_OIDC_SERVICE_CLASS_NAME,
ServiceClientHelpers.SSO_OIDC_SERVICE_CONFIG_NAME,
ServiceClientHelpers.SSO_OIDC_ASSEMBLY_NAME,
proxySettings);
}
public static ICoreAmazonSSO BuildSSOClient(
RegionEndpoint region,
#if BCL
WebProxy proxySettings = null
#elif NETSTANDARD
IWebProxy proxySettings = null
#endif
)
{
return CreateClient<ICoreAmazonSSO>(
region,
ServiceClientHelpers.SSO_SERVICE_CLASS_NAME,
ServiceClientHelpers.SSO_SERVICE_CONFIG_NAME,
ServiceClientHelpers.SSO_ASSEMBLY_NAME,
proxySettings);
}
/// <summary>
/// Attempts to get a service client at runtime which cannot be made a project reference.
/// </summary>
private static T CreateClient<T>(
RegionEndpoint region,
string serviceClassName,
string serviceConfigName,
string parentAssemblyName,
#if BCL
WebProxy proxySettings = null
#elif NETSTANDARD
IWebProxy proxySettings = null
#endif
)
where T : class
{
try
{
var serviceConfig = ServiceClientHelpers.CreateServiceConfig(
parentAssemblyName,
serviceConfigName);
serviceConfig.RegionEndpoint = region;
if (null != proxySettings)
{
serviceConfig.SetWebProxy(proxySettings);
}
var serviceClient = ServiceClientHelpers.CreateServiceFromAssembly<T>(
parentAssemblyName,
serviceClassName,
new AnonymousAWSCredentials(), serviceConfig) as T;
return serviceClient;
}
catch (Exception e)
{
var msg = string.Format(CultureInfo.CurrentCulture,
"Assembly {0} could not be found or loaded. This assembly must be available at runtime to use {1}.",
parentAssemblyName,
typeof(SSOServiceClientHelpers).AssemblyQualifiedName);
var exception = new InvalidOperationException(msg, e);
Logger.GetLogger(typeof(SSOServiceClientHelpers)).Error(exception, exception.Message);
throw exception;
}
}
}
} | 98 |
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 Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using System;
using System.Collections.Generic;
using System.Threading;
namespace Amazon.Runtime
{
public interface IRequestContext
{
AmazonWebServiceRequest OriginalRequest { get; }
string RequestName { get; }
IMarshaller<IRequest, AmazonWebServiceRequest> Marshaller { get; }
ResponseUnmarshaller Unmarshaller { get; }
InvokeOptionsBase Options { get; }
RequestMetrics Metrics { get; }
AbstractAWSSigner Signer { get; }
IClientConfig ClientConfig { get; }
ImmutableCredentials ImmutableCredentials { get; set; }
IRequest Request { get; set; }
bool IsSigned { get; set; }
bool IsAsync { get; }
int Retries { get; set; }
CapacityManager.CapacityType LastCapacityType { get; set; }
int EndpointDiscoveryRetries { get; set; }
#if AWS_ASYNC_API
System.Threading.CancellationToken CancellationToken { get; }
#endif
MonitoringAPICallAttempt CSMCallAttempt { get; set; }
MonitoringAPICallEvent CSMCallEvent { get; set; }
IServiceMetadata ServiceMetaData { get; }
bool CSMEnabled { get; }
bool IsLastExceptionRetryable { get; set; }
Guid InvocationId { get; }
}
public interface IResponseContext
{
AmazonWebServiceResponse Response { get; set; }
IWebResponseData HttpResponse { get; set; }
}
public interface IAsyncRequestContext : IRequestContext
{
AsyncCallback Callback { get; }
object State { get; }
}
public interface IAsyncResponseContext : IResponseContext
{
#if AWS_APM_API
Amazon.Runtime.Internal.RuntimeAsyncResult AsyncResult { get; set; }
#endif
}
public interface IExecutionContext
{
IResponseContext ResponseContext { get; }
IRequestContext RequestContext { get; }
}
public interface IAsyncExecutionContext
{
IAsyncResponseContext ResponseContext { get; }
IAsyncRequestContext RequestContext { get; }
object RuntimeState { get; set; }
}
}
namespace Amazon.Runtime.Internal
{
public class RequestContext : IRequestContext
{
private IServiceMetadata _serviceMetadata;
AbstractAWSSigner clientSigner;
public RequestContext(bool enableMetrics, AbstractAWSSigner clientSigner)
{
if (clientSigner == null)
throw new ArgumentNullException("clientSigner");
this.clientSigner = clientSigner;
this.Metrics = new RequestMetrics();
this.Metrics.IsEnabled = enableMetrics;
this.InvocationId = Guid.NewGuid();
}
public IRequest Request { get; set; }
public RequestMetrics Metrics { get; private set; }
public IClientConfig ClientConfig { get; set; }
public int Retries { get; set; }
public CapacityManager.CapacityType LastCapacityType { get; set; } = CapacityManager.CapacityType.Increment;
public int EndpointDiscoveryRetries { get; set; }
public bool IsSigned { get; set; }
public bool IsAsync { get; set; }
public AmazonWebServiceRequest OriginalRequest { get; set; }
public IMarshaller<IRequest, AmazonWebServiceRequest> Marshaller { get; set; }
public ResponseUnmarshaller Unmarshaller { get; set; }
public InvokeOptionsBase Options { get; set; }
public ImmutableCredentials ImmutableCredentials { get; set; }
public AbstractAWSSigner Signer
{
get
{
var requestSigner = OriginalRequest == null ? null : OriginalRequest.GetSigner();
if (requestSigner == null)
return clientSigner;
else
return requestSigner;
}
}
#if AWS_ASYNC_API
public System.Threading.CancellationToken CancellationToken { get; set; }
#endif
public string RequestName
{
get { return this.OriginalRequest.GetType().Name; }
}
public MonitoringAPICallAttempt CSMCallAttempt { get; set; }
public MonitoringAPICallEvent CSMCallEvent { get; set; }
public IServiceMetadata ServiceMetaData
{
get
{
return _serviceMetadata;
}
internal set
{
_serviceMetadata = value;
// The CSMEnabled flag is referred in the runtime pipeline before capturing any CSM data.
// Along with the customer set CSMEnabled flag, the ServiceMetadata.ServiceId needs to be set
// to capture client side metrics. Older service nuget packages might not have a ServiceMetadata
// implementation and in such cases client side metrics will not be captured.
CSMEnabled = DeterminedCSMConfiguration.Instance.CSMConfiguration.Enabled && !string.IsNullOrEmpty(_serviceMetadata.ServiceId);
}
}
public bool CSMEnabled { get; private set; }
/// <summary>
/// Property to denote that the last exception returned by an AWS Service
/// was retryable or not.
/// </summary>
public bool IsLastExceptionRetryable { get; set; }
public Guid InvocationId { get; private set; }
}
public class AsyncRequestContext : RequestContext, IAsyncRequestContext
{
public AsyncRequestContext(bool enableMetrics, AbstractAWSSigner clientSigner):
base(enableMetrics, clientSigner)
{
}
public AsyncCallback Callback { get; set; }
public object State { get; set; }
}
public class ResponseContext : IResponseContext
{
public AmazonWebServiceResponse Response { get; set; }
public IWebResponseData HttpResponse { get; set; }
}
public class AsyncResponseContext : ResponseContext, IAsyncResponseContext
{
#if AWS_APM_API
public Amazon.Runtime.Internal.RuntimeAsyncResult AsyncResult { get; set; }
#endif
}
public class ExecutionContext : IExecutionContext
{
public IRequestContext RequestContext { get; private set; }
public IResponseContext ResponseContext { get; private set; }
public ExecutionContext(bool enableMetrics, AbstractAWSSigner clientSigner)
{
this.RequestContext = new RequestContext(enableMetrics, clientSigner);
this.ResponseContext = new ResponseContext();
}
public ExecutionContext(IRequestContext requestContext, IResponseContext responseContext)
{
this.RequestContext = requestContext;
this.ResponseContext = responseContext;
}
public static IExecutionContext CreateFromAsyncContext(IAsyncExecutionContext asyncContext)
{
return new ExecutionContext(asyncContext.RequestContext,
asyncContext.ResponseContext);
}
}
public class AsyncExecutionContext : IAsyncExecutionContext
{
public IAsyncResponseContext ResponseContext { get; private set; }
public IAsyncRequestContext RequestContext { get; private set; }
public object RuntimeState { get; set; }
public AsyncExecutionContext(bool enableMetrics, AbstractAWSSigner clientSigner)
{
this.RequestContext = new AsyncRequestContext(enableMetrics, clientSigner);
this.ResponseContext = new AsyncResponseContext();
}
public AsyncExecutionContext(IAsyncRequestContext requestContext, IAsyncResponseContext responseContext)
{
this.RequestContext = requestContext;
this.ResponseContext = responseContext;
}
}
}
| 239 |
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.Transform;
using System;
#if !NETSTANDARD
using System.Runtime.Serialization;
#endif
namespace Amazon.Runtime.Internal
{
#if !NETSTANDARD
[Serializable]
#endif
public class HttpErrorResponseException : Exception
{
public IWebResponseData Response { get; private set; }
public HttpErrorResponseException(IWebResponseData response)
{
this.Response = response;
}
public HttpErrorResponseException(string message, IWebResponseData response) :
base(message)
{
this.Response = response;
}
public HttpErrorResponseException(string message, Exception innerException, IWebResponseData response) :
base(message,innerException)
{
this.Response = response;
}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the HttpErrorResponseException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected HttpErrorResponseException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
if (info != null)
{
this.Response = (IWebResponseData)info.GetValue("Response", typeof(IWebResponseData));
}
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
[System.Security.SecurityCritical]
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
if (info != null)
{
info.AddValue("Response", this.Response);
}
}
#endif
}
}
| 88 |
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.Util;
using System;
namespace Amazon.Runtime
{
/// <summary>
/// Interface for a handler in a pipeline.
/// </summary>
public partial interface IPipelineHandler
{
/// <summary>
/// The logger used to log messages.
/// </summary>
ILogger Logger { get; set; }
/// <summary>
/// The inner handler which is called after the current
/// handler completes it's processing.
/// </summary>
IPipelineHandler InnerHandler { get; set; }
/// <summary>
/// The outer handler which encapsulates the current handler.
/// </summary>
IPipelineHandler OuterHandler { get; set; }
/// <summary>
/// Contains the processing logic for a synchronous request invocation.
/// This method should call InnerHandler.InvokeSync to continue processing of the
/// request by the pipeline, unless it's a terminating handler.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
void InvokeSync(IExecutionContext executionContext);
#if AWS_APM_API
/// <summary>
/// Contains the processing logic for an asynchronous request invocation.
/// This method should call InnerHandler.InvokeSync to continue processing of the
/// request by the pipeline, unless it's a terminating handler.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <returns>IAsyncResult which represent a async operation.</returns>
IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext);
/// <summary>
/// This callback method contains the processing logic that should be executed
/// after the underlying asynchronous operation completes.
/// This method is called as part of a callback chain which starts
/// from the InvokeAsyncCallback method of the bottommost handler and then invokes
/// each callback method of the handler above it.
/// This method should call OuterHandler.AsyncCallback to continue processing of the
/// request by the pipeline, unless it's the topmost handler.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
void AsyncCallback(IAsyncExecutionContext executionContext);
#endif
#if AWS_ASYNC_API
/// <summary>
/// Contains the processing logic for an asynchronous request invocation.
/// This method should call InnerHandler.InvokeSync to continue processing of the
/// request by the pipeline, unless it's a terminating handler.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
where T : AmazonWebServiceResponse, new();
#endif
}
}
| 93 |
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.Util;
using System;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// An abstract pipeline handler that has implements IPipelineHandler,
/// and has the default implmentation. This is the base class for most of
/// the handler implementations.
/// </summary>
public abstract partial class PipelineHandler : IPipelineHandler
{
/// <summary>
/// The logger used to log messages.
/// </summary>
public virtual ILogger Logger { get; set; }
/// <summary>
/// The inner handler which is called after the current
/// handler completes it's processing.
/// </summary>
public IPipelineHandler InnerHandler { get; set; }
/// <summary>
/// The outer handler which encapsulates the current handler.
/// </summary>
public IPipelineHandler OuterHandler { get; set; }
/// <summary>
/// Contains the processing logic for a synchronous request invocation.
/// This method calls InnerHandler.InvokeSync to continue processing of the
/// request by the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
// [System.Diagnostics.DebuggerHidden]
public virtual void InvokeSync(IExecutionContext executionContext)
{
if (this.InnerHandler != null)
{
InnerHandler.InvokeSync(executionContext);
return;
}
throw new InvalidOperationException("Cannot invoke InnerHandler. InnerHandler is not set.");
}
#if AWS_APM_API
/// <summary>
/// Contains the processing logic for an asynchronous request invocation.
/// This method should calls InnerHandler.InvokeSync to continue processing of the
/// request by the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <returns>IAsyncResult which represent an async operation.</returns>
[System.Diagnostics.DebuggerHidden]
public virtual IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
if (this.InnerHandler != null)
{
return InnerHandler.InvokeAsync(executionContext);
}
throw new InvalidOperationException("Cannot invoke InnerHandler. InnerHandler is not set.");
}
/// <summary>
/// This callback method is called by the callback method of the inner handler
/// as part of asynchronous processing after any underlying asynchronous
/// operations complete.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
[System.Diagnostics.DebuggerHidden]
public void AsyncCallback(IAsyncExecutionContext executionContext)
{
try
{
this.InvokeAsyncCallback(executionContext);
}
catch (Exception exception)
{
// Log exception
this.Logger.Error(exception, "An exception of type {0} was thrown from InvokeAsyncCallback().",
exception.GetType().Name);
executionContext.RequestContext.Metrics.AddProperty(Metric.Exception, exception);
// An unhandled exception occured in the callback implementation.
// Capture the exception and end the callback processing by signalling the
// wait handle.
executionContext.RequestContext.Metrics.StopEvent(Metric.ClientExecuteTime);
LogMetrics(ExecutionContext.CreateFromAsyncContext(executionContext));
// Sets the exception on the AsyncResult, signals the wait handle and calls the user callback.
executionContext.ResponseContext.AsyncResult.HandleException(exception);
}
}
/// <summary>
/// This callback method contains the processing logic that should be executed
/// after the underlying asynchronous operation completes.
/// This method is called as part of a callback chain which starts
/// from the InvokeAsyncCallback method of the bottommost handler and then invokes
/// each callback method of the handler above it.
/// This method calls OuterHandler.AsyncCallback to continue processing of the
/// request by the pipeline, unless it's the topmost handler.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
[System.Diagnostics.DebuggerHidden]
protected virtual void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
if (this.OuterHandler!=null)
{
this.OuterHandler.AsyncCallback(executionContext);
}
else
{
// No more outer handlers to process, signal completion
executionContext.ResponseContext.AsyncResult.Response =
executionContext.ResponseContext.Response;
// Signals the wait handle and calls the user callback.
executionContext.ResponseContext.AsyncResult.InvokeCallback();
}
}
#endif
#if AWS_ASYNC_API
/// <summary>
/// Contains the processing logic for an asynchronous request invocation.
/// This method calls InnerHandler.InvokeSync to continue processing of the
/// request by the pipeline.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
#if !NETSTANDARD
[System.Diagnostics.DebuggerHidden]
#endif
public virtual System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
where T : AmazonWebServiceResponse, new()
{
if (this.InnerHandler != null)
{
return InnerHandler.InvokeAsync<T>(executionContext);
}
throw new InvalidOperationException("Cannot invoke InnerHandler. InnerHandler is not set.");
}
#endif
/// <summary>
/// Logs the metrics for the current execution context.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected void LogMetrics(IExecutionContext executionContext)
{
var metrics = executionContext.RequestContext.Metrics;
if (executionContext.RequestContext.ClientConfig.LogMetrics)
{
string errors = metrics.GetErrors();
if (!string.IsNullOrEmpty(errors))
this.Logger.InfoFormat("Request metrics errors: {0}", errors);
this.Logger.InfoFormat("Request metrics: {0}", metrics);
}
}
}
}
| 189 |
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.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// A runtime pipeline contains a collection of handlers which represent
/// different stages of request and response processing.
/// </summary>
public partial class RuntimePipeline : IDisposable
{
#region Private members
bool _disposed;
ILogger _logger;
// The top-most handler in the pipeline.
IPipelineHandler _handler;
#endregion
#region Properties
/// <summary>
/// The top-most handler in the pipeline.
/// </summary>
public IPipelineHandler Handler
{
get { return _handler; }
}
#endregion
#region Constructors
/// <summary>
/// Constructor for RuntimePipeline.
/// </summary>
/// <param name="handler">The handler with which the pipeline is initialized.</param>
public RuntimePipeline(IPipelineHandler handler)
{
if (handler == null)
throw new ArgumentNullException("handler");
var logger =
Amazon.Runtime.Internal.Util.Logger.GetLogger(typeof(RuntimePipeline));
_handler = handler;
_handler.Logger = logger;
_logger = logger;
}
/// <summary>
/// Constructor for RuntimePipeline.
/// </summary>
/// <param name="handlers">List of handlers with which the pipeline is initialized.</param>
public RuntimePipeline(IList<IPipelineHandler> handlers)
: this(handlers, Amazon.Runtime.Internal.Util.Logger.GetLogger(typeof(RuntimePipeline)))
{
}
/// <summary>
/// Constructor for RuntimePipeline.
/// </summary>
/// <param name="handlers">List of handlers with which the pipeline is initialized.</param>
/// <param name="logger">The logger used to log messages.</param>
public RuntimePipeline(IList<IPipelineHandler> handlers, ILogger logger)
{
if (handlers == null || handlers.Count == 0)
throw new ArgumentNullException("handlers");
if (logger == null)
throw new ArgumentNullException("logger");
_logger = logger;
foreach (var handler in handlers)
{
this.AddHandler(handler);
}
}
/// <summary>
/// Constructor for RuntimePipeline.
/// </summary>
/// <param name="handler">The handler with which the pipeline is initialized.</param>
/// <param name="logger">The logger used to log messages.</param>
public RuntimePipeline(IPipelineHandler handler, ILogger logger)
{
if (handler == null)
throw new ArgumentNullException("handler");
if (logger == null)
throw new ArgumentNullException("logger");
_handler = handler;
_handler.Logger = logger;
_logger = logger;
}
#endregion
#region Invoke methods
/// <summary>
/// Invokes the pipeline synchronously.
/// </summary>
/// <param name="executionContext">Request context</param>
/// <returns>Response context</returns>
public IResponseContext InvokeSync(IExecutionContext executionContext)
{
ThrowIfDisposed();
_handler.InvokeSync(executionContext);
return executionContext.ResponseContext;
}
#if AWS_ASYNC_API
/// <summary>
/// Invokes the pipeline asynchronously.
/// </summary>
/// <param name="executionContext">Request context</param>
/// <returns>Response context</returns>
public System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
where T : AmazonWebServiceResponse, new()
{
ThrowIfDisposed();
return _handler.InvokeAsync<T>(executionContext);
}
#elif AWS_APM_API
/// <summary>
/// Invokes the pipeline asynchronously.
/// </summary>
/// <param name="executionContext">Request context</param>
/// <returns>IAsyncResult which represents the in progress asynchronous operation.</returns>
public IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
ThrowIfDisposed();
return _handler.InvokeAsync(executionContext);
}
#endif
#endregion
#region Handler methods
/// <summary>
/// Adds a new handler to the top of the pipeline.
/// </summary>
/// <param name="handler">The handler to be added to the pipeline.</param>
public void AddHandler(IPipelineHandler handler)
{
if (handler == null)
throw new ArgumentNullException("handler");
ThrowIfDisposed();
var innerMostHandler = GetInnermostHandler(handler);
if (_handler != null)
{
innerMostHandler.InnerHandler = _handler;
_handler.OuterHandler = innerMostHandler;
}
_handler = handler;
SetHandlerProperties(handler);
}
/// <summary>
/// Adds a handler after the first instance of handler of type T.
/// </summary>
/// <typeparam name="T">Type of the handler after which the given handler instance is added.</typeparam>
/// <param name="handler">The handler to be added to the pipeline.</param>
public void AddHandlerAfter<T>(IPipelineHandler handler)
where T : IPipelineHandler
{
if (handler == null)
throw new ArgumentNullException("handler");
ThrowIfDisposed();
var type = typeof(T);
var current = _handler;
while (current != null)
{
if (current.GetType() == type)
{
InsertHandler(handler, current);
SetHandlerProperties(handler);
return;
}
current = current.InnerHandler;
}
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "Cannot find a handler of type {0}", type.Name));
}
/// <summary>
/// Adds a handler before the first instance of handler of type T.
/// </summary>
/// <typeparam name="T">Type of the handler before which the given handler instance is added.</typeparam>
/// <param name="handler">The handler to be added to the pipeline.</param>
public void AddHandlerBefore<T>(IPipelineHandler handler)
where T : IPipelineHandler
{
if (handler == null)
throw new ArgumentNullException("handler");
ThrowIfDisposed();
var type = typeof(T);
if (_handler.GetType() == type)
{
// Add the handler to the top of the pipeline
AddHandler(handler);
SetHandlerProperties(handler);
return;
}
var current = _handler;
while (current != null)
{
if (current.InnerHandler != null &&
current.InnerHandler.GetType() == type)
{
InsertHandler(handler, current);
SetHandlerProperties(handler);
return;
}
current = current.InnerHandler;
}
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "Cannot find a handler of type {0}", type.Name));
}
/// <summary>
/// Removes the first occurance of a handler of type T.
/// </summary>
/// <typeparam name="T">Type of the handler which will be removed.</typeparam>
public void RemoveHandler<T>()
{
ThrowIfDisposed();
var type = typeof(T);
IPipelineHandler previous = null;
var current = _handler;
while (current != null)
{
if (current.GetType() == type)
{
// Cannot remove the handler if it's the only one in the pipeline
if (current == _handler && _handler.InnerHandler == null)
{
throw new InvalidOperationException(
"The pipeline contains a single handler, cannot remove the only handler in the pipeline.");
}
// current is the top, point top to current's inner handler
if (current == _handler)
_handler = current.InnerHandler;
// Wireup outer handler to current's inner handler
if (current.OuterHandler != null)
current.OuterHandler.InnerHandler = current.InnerHandler;
// Wireup inner handler to current's outer handler
if (current.InnerHandler != null)
current.InnerHandler.OuterHandler = current.OuterHandler;
// Cleanup current
current.InnerHandler = null;
current.OuterHandler = null;
return;
}
previous = current;
current = current.InnerHandler;
}
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "Cannot find a handler of type {0}", type.Name));
}
/// <summary>
/// Replaces the first occurance of a handler of type T with the given handler.
/// </summary>
/// <typeparam name="T">Type of the handler which will be replaced.</typeparam>
/// <param name="handler">The handler to be added to the pipeline.</param>
public void ReplaceHandler<T>(IPipelineHandler handler)
where T : IPipelineHandler
{
if (handler == null)
throw new ArgumentNullException("handler");
ThrowIfDisposed();
var type = typeof(T);
IPipelineHandler previous = null;
var current = _handler;
while (current != null)
{
if (current.GetType() == type)
{
// Replace current with handler.
handler.InnerHandler = current.InnerHandler;
handler.OuterHandler = current.OuterHandler;
if(previous != null)
{
// Wireup previous handler
previous.InnerHandler = handler;
}
else
{
// Current is the top, replace it.
_handler = handler;
}
if (current.InnerHandler != null)
{
// Wireup next handler
current.InnerHandler.OuterHandler = handler;
}
// Cleanup current
current.InnerHandler = null;
current.OuterHandler = null;
SetHandlerProperties(handler);
return;
}
previous = current;
current = current.InnerHandler;
}
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "Cannot find a handler of type {0}", type.Name));
}
/// <summary>
/// Inserts the given handler after current handler in the pipeline.
/// </summary>
/// <param name="handler">Handler to be inserted in the pipeline.</param>
/// <param name="current">Handler after which the given handler is inserted.</param>
private static void InsertHandler(IPipelineHandler handler, IPipelineHandler current)
{
var next = current.InnerHandler;
current.InnerHandler = handler;
handler.OuterHandler = current;
if (next!=null)
{
var innerMostHandler = GetInnermostHandler(handler);
innerMostHandler.InnerHandler = next;
next.OuterHandler = innerMostHandler;
}
}
/// <summary>
/// Gets the innermost handler by traversing the inner handler till
/// it reaches the last one.
/// </summary>
private static IPipelineHandler GetInnermostHandler(IPipelineHandler handler)
{
var current = handler;
while (current.InnerHandler != null)
{
current = current.InnerHandler;
}
return current;
}
private void SetHandlerProperties(IPipelineHandler handler)
{
ThrowIfDisposed();
handler.Logger = _logger;
}
/// <summary>
/// Retrieves a list of handlers, in the order of their execution.
/// </summary>
/// <returns>Handlers in the current pipeline.</returns>
public List<IPipelineHandler> Handlers
{
get
{
return EnumerateHandlers().ToList();
}
}
/// <summary>
/// Retrieves current handlers, in the order of their execution.
/// </summary>
/// <returns>Handlers in the current pipeline.</returns>
public IEnumerable<IPipelineHandler> EnumerateHandlers()
{
var handler = this.Handler;
while(handler != null)
{
yield return handler;
handler = handler.InnerHandler;
}
}
#endregion
#region Dispose methods
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
var handler = this.Handler;
while (handler != null)
{
var innerHandler = handler.InnerHandler;
var disposable = handler as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
handler = innerHandler;
}
_disposed = true;
}
}
private void ThrowIfDisposed()
{
if (this._disposed)
throw new ObjectDisposedException(GetType().FullName);
}
#endregion
}
}
| 479 |
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.Util;
using Amazon.Util.Internal;
using System;
using System.Collections.Generic;
using System.Net;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This handler processes exceptions thrown from the HTTP handler and
/// unmarshalls error responses.
/// </summary>
public class ErrorHandler : PipelineHandler
{
/// <summary>
/// Default set of exception handlers.
/// </summary>
private IDictionary<Type, IExceptionHandler> _exceptionHandlers;
/// <summary>
/// Default set of exception handlers.
/// </summary>
public IDictionary<Type, IExceptionHandler> ExceptionHandlers
{
get
{
return _exceptionHandlers;
}
}
/// <summary>
/// Constructor for ErrorHandler.
/// </summary>
/// <param name="logger">an ILogger instance.</param>
public ErrorHandler(ILogger logger)
{
this.Logger = logger;
_exceptionHandlers = new Dictionary<Type, IExceptionHandler>
{
#if BCL
{typeof(WebException), new WebExceptionHandler(this.Logger)},
#endif
{typeof(HttpErrorResponseException), new HttpErrorResponseExceptionHandler(this.Logger)}
};
}
/// <summary>
/// Handles and processes any exception thrown from underlying handlers.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
try
{
base.InvokeSync(executionContext);
return;
}
catch (Exception exception)
{
DisposeReponse(executionContext.ResponseContext);
bool rethrowOriginalException = ProcessException(executionContext, exception);
if (rethrowOriginalException)
{
throw;
}
}
}
#if AWS_ASYNC_API
/// <summary>
/// Handles and processes any exception thrown from underlying handlers.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
try
{
return await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
}
catch (Exception exception)
{
DisposeReponse(executionContext.ResponseContext);
bool rethrowOriginalException = await ProcessExceptionAsync(executionContext, exception).ConfigureAwait(false);
if (rethrowOriginalException)
{
throw;
}
}
// If response if set and an exception is not rethrown, return the response.
// E.g. S3 GetLifecycleConfiguration, GetBucket policy and few other operations
// return a 404 which is not returned back as an exception but as a empty response with
// error code.
if(executionContext.ResponseContext != null && executionContext.ResponseContext.Response != null)
{
return executionContext.ResponseContext.Response as T;
}
return null;
}
#elif AWS_APM_API
/// <summary>
/// Handles and processes any exception thrown from underlying handlers.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected override void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
var responseContext = executionContext.ResponseContext;
var exception = responseContext.AsyncResult.Exception;
if (exception != null)
{
try
{
DisposeReponse(executionContext.ResponseContext);
bool rethrow = ProcessException(
ExecutionContext.CreateFromAsyncContext(executionContext),
exception);
// Suppress exception
if (!rethrow)
responseContext.AsyncResult.Exception = null;
}
catch (Exception processedException)
{
// Catch any new exception thrown by ProcessException()
responseContext.AsyncResult.Exception = processedException;
}
}
// Call outer handler
base.InvokeAsyncCallback(executionContext);
}
#endif
/// <summary>
/// Disposes the response body.
/// </summary>
/// <param name="responseContext">The response context.</param>
private static void DisposeReponse(IResponseContext responseContext)
{
if (responseContext.HttpResponse != null &&
responseContext.HttpResponse.ResponseBody != null)
{
responseContext.HttpResponse.ResponseBody.Dispose();
}
}
/// <summary>
/// Processes an exception by invoking a matching exception handler
/// for the given exception.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <param name="exception">The exception to be processed.</param>
/// <returns>
/// This method returns a boolean value which indicates if the original exception
/// should be rethrown.
/// This method can also throw a new exception that may be thrown by exception
/// processing by a matching exception handler.
/// </returns>
private bool ProcessException(IExecutionContext executionContext, Exception exception)
{
// Log the exception
this.Logger.Error(exception, "An exception of type {0} was handled in ErrorHandler.", exception.GetType().Name);
executionContext.RequestContext.Metrics.AddProperty(Metric.Exception, exception);
// Find the matching handler which can process the exception
// Start by checking if there is a matching handler for the specific exception type,
// if not check for handlers for it's base type till we find a match.
var exceptionType = exception.GetType();
var exceptionTypeInfo = TypeFactory.GetTypeInfo(exception.GetType());
do
{
IExceptionHandler exceptionHandler = null;
if (this.ExceptionHandlers.TryGetValue(exceptionType, out exceptionHandler))
{
return exceptionHandler.Handle(executionContext, exception);
}
exceptionType = exceptionTypeInfo.BaseType;
exceptionTypeInfo = TypeFactory.GetTypeInfo(exceptionTypeInfo.BaseType);
} while (exceptionType != typeof(Exception));
// No match found, rethrow the original exception.
return true;
}
#if AWS_ASYNC_API
/// <summary>
/// Processes an exception by invoking a matching exception handler
/// for the given exception.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <param name="exception">The exception to be processed.</param>
/// <returns>
/// This method returns a boolean value which indicates if the original exception
/// should be rethrown.
/// This method can also throw a new exception that may be thrown by exception
/// processing by a matching exception handler.
/// </returns>
private async System.Threading.Tasks.Task<bool> ProcessExceptionAsync(IExecutionContext executionContext, Exception exception)
{
// Log the exception
this.Logger.Error(exception, "An exception of type {0} was handled in ErrorHandler.", exception.GetType().Name);
executionContext.RequestContext.Metrics.AddProperty(Metric.Exception, exception);
// Find the matching handler which can process the exception
// Start by checking if there is a matching handler for the specific exception type,
// if not check for handlers for it's base type till we find a match.
var exceptionType = exception.GetType();
var exceptionTypeInfo = TypeFactory.GetTypeInfo(exception.GetType());
do
{
IExceptionHandler exceptionHandler = null;
if (this.ExceptionHandlers.TryGetValue(exceptionType, out exceptionHandler))
{
return await exceptionHandler.HandleAsync(executionContext, exception).ConfigureAwait(false);
}
exceptionType = exceptionTypeInfo.BaseType;
exceptionTypeInfo = TypeFactory.GetTypeInfo(exceptionTypeInfo.BaseType);
} while (exceptionType != typeof(Exception));
// No match found, rethrow the original exception.
return true;
}
#endif
}
}
| 259 |
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.Util;
using System;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The abstract base class for exception handlers.
/// </summary>
/// <typeparam name="T">The exception type.</typeparam>
public abstract class ExceptionHandler<T> : IExceptionHandler<T> where T : Exception
{
private ILogger _logger;
protected ILogger Logger { get { return _logger; } }
protected ExceptionHandler(ILogger logger)
{
_logger = logger;
}
public bool Handle(IExecutionContext executionContext, Exception exception)
{
return HandleException(executionContext, exception as T);
}
public abstract bool HandleException(IExecutionContext executionContext, T exception);
#if AWS_ASYNC_API
public async System.Threading.Tasks.Task<bool> HandleAsync(IExecutionContext executionContext, Exception exception)
{
return await HandleExceptionAsync(executionContext, exception as T).ConfigureAwait(false);
}
public abstract System.Threading.Tasks.Task<bool> HandleExceptionAsync(IExecutionContext executionContext, T exception);
#endif
}
}
| 52 |
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.Transform;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using System;
using System.Diagnostics;
using System.Net;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The exception handler for HttpErrorResponseException exception.
/// </summary>
public class HttpErrorResponseExceptionHandler : ExceptionHandler<HttpErrorResponseException>
{
/// <summary>
/// The constructor for HttpErrorResponseExceptionHandler.
/// </summary>
/// <param name="logger">in instance of ILogger.</param>
public HttpErrorResponseExceptionHandler(ILogger logger) :
base(logger)
{
}
/// <summary>
/// Handles an exception for the given execution context.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <param name="exception">The exception to handle.</param>
/// <returns>
/// Returns a boolean value which indicates if the original exception
/// should be rethrown.
/// This method can also throw a new exception to replace the original exception.
/// </returns>
public override bool HandleException(IExecutionContext executionContext, HttpErrorResponseException exception)
{
var requestContext = executionContext.RequestContext;
var httpErrorResponse = exception.Response;
// If 404 was suppressed and successfully unmarshalled,
// don't rethrow the original exception.
if (HandleSuppressed404(executionContext, httpErrorResponse))
return false;
using (httpErrorResponse.ResponseBody)
{
var responseStream = httpErrorResponse.ResponseBody.OpenResponse();
return HandleExceptionStream(requestContext, httpErrorResponse, exception, responseStream);
}
}
#if AWS_ASYNC_API
/// <summary>
/// Handles an exception for the given execution context.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <param name="exception">The exception to handle.</param>
/// <returns>
/// Returns a boolean value which indicates if the original exception
/// should be rethrown.
/// This method can also throw a new exception to replace the original exception.
/// </returns>
public override async System.Threading.Tasks.Task<bool> HandleExceptionAsync(IExecutionContext executionContext, HttpErrorResponseException exception)
{
var requestContext = executionContext.RequestContext;
var httpErrorResponse = exception.Response;
// If 404 was suppressed and successfully unmarshalled,
// don't rethrow the original exception.
if (HandleSuppressed404(executionContext, httpErrorResponse))
return false;
using(httpErrorResponse.ResponseBody)
{
var responseStream = await httpErrorResponse.ResponseBody.OpenResponseAsync().ConfigureAwait(false);
return HandleExceptionStream(requestContext, httpErrorResponse, exception, responseStream);
}
}
#endif
/// <summary>
/// Shared logic for the HandleException and HandleExceptionAsync
/// </summary>
/// <param name="requestContext"></param>
/// <param name="httpErrorResponse"></param>
/// <param name="exception"></param>
/// <param name="responseStream"></param>
/// <returns></returns>
private bool HandleExceptionStream(IRequestContext requestContext, IWebResponseData httpErrorResponse, HttpErrorResponseException exception, System.IO.Stream responseStream)
{
requestContext.Metrics.AddProperty(Metric.StatusCode, httpErrorResponse.StatusCode);
AmazonServiceException errorResponseException = null;
// Unmarshall the service error response and throw the corresponding service exception.
try
{
var unmarshaller = requestContext.Unmarshaller;
var readEntireResponse = true;
var errorContext = unmarshaller.CreateContext(httpErrorResponse,
readEntireResponse,
responseStream,
requestContext.Metrics,
true,
requestContext);
try
{
errorResponseException = unmarshaller.UnmarshallException(errorContext,
exception, httpErrorResponse.StatusCode);
}
catch (Exception e)
{
// Rethrow Amazon service or client exceptions
if (e is AmazonServiceException ||
e is AmazonClientException)
{
throw;
}
// Else, there was an issue with the response body, throw AmazonUnmarshallingException
var requestId = httpErrorResponse.GetHeaderValue(HeaderKeys.RequestIdHeader);
var body = errorContext.ResponseBody;
throw new AmazonUnmarshallingException(requestId, lastKnownLocation: null, responseBody: body,
innerException: e, statusCode: httpErrorResponse.StatusCode);
}
requestContext.Metrics.AddProperty(Metric.AWSRequestID, errorResponseException.RequestId);
requestContext.Metrics.AddProperty(Metric.AWSErrorCode, errorResponseException.ErrorCode);
var logResponseBody = requestContext.ClientConfig.LogResponse ||
AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never;
if (logResponseBody)
{
this.Logger.Error(errorResponseException, "Received error response: [{0}]",
errorContext.ResponseBody);
}
}
catch (Exception unmarshallException)
{
this.Logger.Error(unmarshallException, "Failed to unmarshall a service error response.");
throw;
}
throw errorResponseException;
}
/// <summary>
/// Checks if a HTTP 404 status code is returned which needs to be suppressed and
/// processes it.
/// If a suppressed 404 is present, it unmarshalls the response and returns true to
/// indicate that a suppressed 404 was processed, else returns false.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <param name="httpErrorResponse"></param>
/// <returns>
/// If a suppressed 404 is present, returns true, else returns false.
/// </returns>
private bool HandleSuppressed404(IExecutionContext executionContext, IWebResponseData httpErrorResponse)
{
var requestContext = executionContext.RequestContext;
var responseContext = executionContext.ResponseContext;
// If the error is a 404 and the request is configured to supress it,
// then unmarshall as much as we can.
if (httpErrorResponse != null &&
httpErrorResponse.StatusCode == HttpStatusCode.NotFound &&
requestContext.Request.Suppress404Exceptions)
{
using (httpErrorResponse.ResponseBody)
{
var unmarshaller = requestContext.Unmarshaller;
var readEntireResponse = requestContext.ClientConfig.LogResponse ||
AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never;
UnmarshallerContext errorContext = unmarshaller.CreateContext(
httpErrorResponse,
readEntireResponse,
httpErrorResponse.ResponseBody.OpenResponse(),
requestContext.Metrics,
true,
requestContext);
try
{
responseContext.Response = unmarshaller.Unmarshall(errorContext);
responseContext.Response.ContentLength = httpErrorResponse.ContentLength;
responseContext.Response.HttpStatusCode = httpErrorResponse.StatusCode;
return true;
}
catch (Exception unmarshallException)
{
this.Logger.Debug(unmarshallException, "Failed to unmarshall 404 response when it was supressed.");
}
}
}
return false;
}
}
}
| 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.
*/
using System;
namespace Amazon.Runtime
{
/// <summary>
/// The interface for an exception handler.
/// </summary>
public interface IExceptionHandler
{
/// <summary>
/// Handles an exception for the given execution context.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <param name="exception">The exception to handle.</param>
/// <returns>
/// Returns a boolean value which indicates if the original exception
/// should be rethrown.
/// This method can also throw a new exception to replace the original exception.
/// </returns>
bool Handle(IExecutionContext executionContext, Exception exception);
#if AWS_ASYNC_API
/// <summary>
/// Handles an exception for the given execution context.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <param name="exception">The exception to handle.</param>
/// <returns>
/// Returns a boolean value which indicates if the original exception
/// should be rethrown.
/// This method can also throw a new exception to replace the original exception.
/// </returns>
System.Threading.Tasks.Task<bool> HandleAsync(IExecutionContext executionContext, Exception exception);
#endif
}
/// <summary>
/// The interface for an exception handler with a generic parameter for the exception type.
/// </summary>
/// <typeparam name="T">The exception type.</typeparam>
public interface IExceptionHandler<T> : IExceptionHandler where T : Exception
{
/// <summary>
/// Handles an exception for the given execution context.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <param name="exception">The exception to handle.</param>
/// <returns>
/// Returns a boolean value which indicates if the original exception
/// should be rethrown.
/// This method can also throw a new exception to replace the original exception.
/// </returns>
bool HandleException(IExecutionContext executionContext, T exception);
}
}
| 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 Amazon.Runtime.Internal.Util;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The exception handler for HttpErrorResponseException exception.
/// </summary>
public class WebExceptionHandler : ExceptionHandler<WebException>
{
public WebExceptionHandler(ILogger logger) :
base(logger)
{
}
public override bool HandleException(IExecutionContext executionContext, WebException exception)
{
var requestContext = executionContext.RequestContext;
var httpErrorResponse = exception.Response as HttpWebResponse;
var message = string.Format(CultureInfo.InvariantCulture,
"A WebException with status {0} was thrown.", exception.Status);
if (httpErrorResponse != null)
{
requestContext.Metrics.AddProperty(Metric.StatusCode, httpErrorResponse.StatusCode);
throw new AmazonServiceException(message, exception, httpErrorResponse.StatusCode);
}
throw new AmazonServiceException(message, exception);
}
#if AWS_ASYNC_API
public override System.Threading.Tasks.Task<bool> HandleExceptionAsync(IExecutionContext executionContext, WebException exception)
{
return System.Threading.Tasks.Task.FromResult(this.HandleException(executionContext, exception));
}
#endif
}
}
| 59 |
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.Linq;
using System.Collections;
using System.Collections.Generic;
using Amazon.Runtime.Endpoints;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Custom PipelineHandler responsible for resolving endpoint and setting authentication parameters for service requests.
/// Collects values for EndpointParameters and then resolves endpoint via global or service-specific EndpointProvider.
/// Responsible for setting authentication and http headers provided by resolved endpoint.
/// </summary>
public class BaseEndpointResolver : PipelineHandler
{
public override void InvokeSync(IExecutionContext executionContext)
{
PreInvoke(executionContext);
base.InvokeSync(executionContext);
}
#if AWS_ASYNC_API
public override System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
PreInvoke(executionContext);
return base.InvokeAsync<T>(executionContext);
}
#elif AWS_APM_API
public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
PreInvoke(ExecutionContext.CreateFromAsyncContext(executionContext));
return base.InvokeAsync(executionContext);
}
#endif
protected virtual void PreInvoke(IExecutionContext executionContext)
{
ProcessRequestHandlers(executionContext);
}
public virtual void ProcessRequestHandlers(IExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
var parameters = MapEndpointsParameters(requestContext);
var config = requestContext.ClientConfig;
Endpoint endpoint = null;
if (GlobalEndpoints.Provider != null)
{
endpoint = GlobalEndpoints.Provider.ResolveEndpoint(requestContext.ServiceMetaData?.ServiceId, parameters);
}
else if (endpoint == null && config.EndpointProvider != null)
{
endpoint = config.EndpointProvider.ResolveEndpoint(parameters);
}
// Ensure url ends with "/" to avoid signature mismatch issues.
if (!endpoint.URL.EndsWith("/") && (string.IsNullOrEmpty(requestContext.Request.ResourcePath) || requestContext.Request.ResourcePath == "/"))
{
endpoint.URL += "/";
}
requestContext.Request.Endpoint = new Uri(endpoint.URL);
// If an explicit ServiceURL was provided, do not manipulate it based on UseHttp
// This preserves existing behavior prior to 3.7.100
if (config.UseHttp && string.IsNullOrEmpty(requestContext.ClientConfig.ServiceURL))
{
var uriBuilder = new UriBuilder(requestContext.Request.Endpoint)
{
Scheme = Uri.UriSchemeHttp,
Port = requestContext.Request.Endpoint.IsDefaultPort ? -1 : requestContext.Request.Endpoint.Port
};
requestContext.Request.Endpoint = uriBuilder.Uri;
}
// set authentication parameters and headers
SetAuthenticationAndHeaders(requestContext.Request, endpoint);
// service-specific handling, code-generated
ServiceSpecificHandler(executionContext, parameters);
// override AuthenticationRegion from ClientConfig if specified
if (!string.IsNullOrEmpty(config.AuthenticationRegion))
{
requestContext.Request.AuthenticationRegion = config.AuthenticationRegion;
}
}
/// <summary>
/// Service-specific handling, we code-gen override per service.
/// </summary>
protected virtual void ServiceSpecificHandler(IExecutionContext executionContext, EndpointParameters parameters)
{
}
private static readonly string[] SupportedAuthSchemas = { "sigv4", "sigv4a" };
private static void SetAuthenticationAndHeaders(IRequest request, Endpoint endpoint)
{
if (endpoint.Attributes != null)
{
var authSchemes = (IList)endpoint.Attributes["authSchemes"];
if (authSchemes != null)
{
var schemaFound = false;
foreach (PropertyBag schema in authSchemes)
{
var schemaName = (string)schema["name"];
if (SupportedAuthSchemas.Contains(schemaName))
{
switch (schemaName)
{
case "sigv4":
{
request.SignatureVersion = SignatureVersion.SigV4;
var signingRegion = (string)schema["signingRegion"];
if (!string.IsNullOrEmpty(signingRegion))
{
request.AuthenticationRegion = signingRegion;
}
ApplyCommonSchema(request, schema);
break;
}
case "sigv4a":
{
request.SignatureVersion = SignatureVersion.SigV4a;
var signingRegions = ((List<object>)schema["signingRegionSet"]).OfType<string>().ToArray();
var authenticationRegion = string.Join(",", signingRegions);
if (!string.IsNullOrEmpty(authenticationRegion))
{
request.AuthenticationRegion = authenticationRegion;
}
ApplyCommonSchema(request, schema);
break;
}
}
schemaFound = true;
break;
}
}
if (!schemaFound && authSchemes.Count > 0)
{
throw new AmazonClientException("Cannot find supported authentication schema");
}
}
}
if (endpoint.Headers != null)
{
foreach (var header in endpoint.Headers)
{
request.Headers[header.Key] = string.Join(",", header.Value.ToArray());
}
}
}
private static void ApplyCommonSchema(IRequest request, PropertyBag schema)
{
var signingName = (string)schema["signingName"];
if (!string.IsNullOrEmpty(signingName))
{
request.OverrideSigningServiceName = signingName;
}
var disableDoubleEncoding = schema["disableDoubleEncoding"];
if (disableDoubleEncoding != null)
{
request.UseDoubleEncoding = !(bool)disableDoubleEncoding;
}
}
/// <summary>
/// Inject host prefix into request endpoint.
/// </summary>
protected static void InjectHostPrefix(IRequestContext requestContext)
{
if (requestContext.ClientConfig.DisableHostPrefixInjection ||
string.IsNullOrEmpty(requestContext.Request.HostPrefix))
{
return;
}
var hostPrefixUri = new UriBuilder(requestContext.Request.Endpoint);
hostPrefixUri.Host = requestContext.Request.HostPrefix + hostPrefixUri.Host;
requestContext.Request.Endpoint = hostPrefixUri.Uri;
}
/// <summary>
/// Service-specific mapping of endpoints parameters, we code-gen override per service.
/// </summary>
protected virtual EndpointParameters MapEndpointsParameters(IRequestContext requestContext)
{
return null;
}
}
} | 213 |
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.Internal
{
/// <summary>
/// A pipeline handler which provides hooks to run
/// external code in the pre-invoke and post-invoke phases.
/// </summary>
public class CallbackHandler : PipelineHandler
{
/// <summary>
/// Action to execute on the pre invoke phase.
/// </summary>
public Action<IExecutionContext> OnPreInvoke { get; set; }
/// <summary>
/// Action to execute on the post invoke phase.
/// </summary>
public Action<IExecutionContext> OnPostInvoke { get; set; }
/// <summary>
/// Calls the PreInvoke and PostInvoke methods before and after calling the next handler
/// in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
PreInvoke(executionContext);
base.InvokeSync(executionContext);
PostInvoke(executionContext);
}
#if AWS_ASYNC_API
/// <summary>
/// Calls the PreInvoke and PostInvoke methods before and after calling the next handler
/// in the pipeline.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
PreInvoke(executionContext);
var response = await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
PostInvoke(executionContext);
return response;
}
#elif AWS_APM_API
/// <summary>
/// Calls the PreInvoke method before calling the next handler in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <returns>IAsyncResult which represent an async operation.</returns>
public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
PreInvoke(ExecutionContext.CreateFromAsyncContext(executionContext));
return base.InvokeAsync(executionContext);
}
/// <summary>
/// Calls the PostInvoke methods after calling the next handler
/// in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected override void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
// Process the response if an exception hasn't occured
if (executionContext.ResponseContext.AsyncResult.Exception == null)
{
PostInvoke(ExecutionContext.CreateFromAsyncContext(executionContext));
}
base.InvokeAsyncCallback(executionContext);
}
#endif
/// <summary>
/// Executes the OnPreInvoke action as part of pre-invoke.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected void PreInvoke(IExecutionContext executionContext)
{
RaiseOnPreInvoke(executionContext);
}
/// <summary>
/// Executes the OnPreInvoke action as part of post-invoke.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected void PostInvoke(IExecutionContext executionContext)
{
RaiseOnPostInvoke(executionContext);
}
private void RaiseOnPreInvoke(IExecutionContext context)
{
if (this.OnPreInvoke != null)
this.OnPreInvoke(context);
}
private void RaiseOnPostInvoke(IExecutionContext context)
{
if (this.OnPostInvoke != null)
this.OnPostInvoke(context);
}
}
}
| 130 |
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.Auth;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using System;
using System.IO;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This handler retrieved the AWS credentials to be used for the current call.
/// </summary>
public class CredentialsRetriever : PipelineHandler
{
/// <summary>
/// The constructor for CredentialsRetriever.
/// </summary>
/// <param name="credentials">An AWSCredentials instance.</param>
public CredentialsRetriever(AWSCredentials credentials)
{
this.Credentials = credentials;
}
protected AWSCredentials Credentials
{
get;
private set;
}
/// <summary>
/// Retrieves the credentials to be used for the current call before
/// invoking the next handler.
/// </summary>
/// <param name="executionContext"></param>
protected virtual void PreInvoke(IExecutionContext executionContext)
{
ImmutableCredentials ic = null;
if (Credentials != null && !(Credentials is AnonymousAWSCredentials) && !(executionContext.RequestContext.Signer is BearerTokenSigner))
{
using(executionContext.RequestContext.Metrics.StartEvent(Metric.CredentialsRequestTime))
{
ic = Credentials.GetCredentials();
}
}
executionContext.RequestContext.ImmutableCredentials = ic;
}
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
PreInvoke(executionContext);
base.InvokeSync(executionContext);
}
#if AWS_ASYNC_API
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
ImmutableCredentials ic = null;
if (Credentials != null && !(Credentials is AnonymousAWSCredentials))
{
using(executionContext.RequestContext.Metrics.StartEvent(Metric.CredentialsRequestTime))
{
ic = await Credentials.GetCredentialsAsync().ConfigureAwait(false);
}
}
executionContext.RequestContext.ImmutableCredentials = ic;
return await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
}
#elif AWS_APM_API
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <returns>IAsyncResult which represent an async operation.</returns>
public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
PreInvoke(ExecutionContext.CreateFromAsyncContext(executionContext));
return base.InvokeAsync(executionContext);
}
#endif
}
}
| 119 |
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.Net;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This handler resolves the endpoint to be used for the current request.
/// </summary>
public class EndpointDiscoveryHandler : PipelineHandler
{
//The status code returned from a service request when an invalid endpoint is used.
private const int INVALID_ENDPOINT_EXCEPTION_STATUSCODE = 421;
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
var regionalEndpoint = requestContext.Request.Endpoint;
PreInvoke(executionContext);
try
{
base.InvokeSync(executionContext);
return;
}
catch (Exception exception)
{
if (IsInvalidEndpointException(exception))
{
EvictCacheKeyForRequest(requestContext, regionalEndpoint);
}
throw;
}
}
#if AWS_ASYNC_API
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
var regionalEndpoint = requestContext.Request.Endpoint;
PreInvoke(executionContext);
try
{
return await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
}
catch (Exception exception)
{
var capturedException = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(exception);
if (IsInvalidEndpointException(capturedException.SourceException))
{
EvictCacheKeyForRequest(requestContext, regionalEndpoint);
}
capturedException.Throw();
}
throw new AmazonClientException("Neither a response was returned nor an exception was thrown in the Runtime EndpointDiscoveryResolver.");
}
#elif AWS_APM_API
/// <summary>
/// Invokes the inner handler
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
protected override void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
try
{
var requestContext = executionContext.RequestContext;
var responseContext = executionContext.ResponseContext;
var regionalEndpoint = requestContext.Request.Endpoint;
var exception = responseContext.AsyncResult.Exception;
if (exception != null)
{
if (IsInvalidEndpointException(exception))
{
EvictCacheKeyForRequest(requestContext, regionalEndpoint);
}
}
else
{
PreInvoke(ExecutionContext.CreateFromAsyncContext(executionContext));
}
}
catch(Exception e)
{
executionContext.ResponseContext.AsyncResult.Exception = e;
}
finally
{
// Call outer handler
base.InvokeAsyncCallback(executionContext);
}
}
#endif
/// <summary>
/// Resolves the endpoint to be used for the current request
/// before invoking the next handler.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected static void PreInvoke(IExecutionContext executionContext)
{
DiscoverEndpoints(executionContext.RequestContext, false);
}
public static void EvictCacheKeyForRequest(IRequestContext requestContext, Uri regionalEndpoint)
{
DiscoverEndpoints(requestContext, true);
requestContext.Request.Endpoint = regionalEndpoint;
}
public static void DiscoverEndpoints(IRequestContext requestContext, bool evictCacheKey)
{
var discoveryEndpoints = ProcessEndpointDiscovery(requestContext, evictCacheKey, requestContext.Request.Endpoint);
if (discoveryEndpoints != null)
{
foreach (var endpoint in discoveryEndpoints)
{
//A null address can occur if this endpoint does not require endpoint discovery
//and we couldn't get an endpoint back during an asynchronous discovery
//attempt. The null address endpoint will be evicted after 60 seconds but will
//prevent multiple server requests during this time.
if(endpoint.Address == null)
{
continue;
}
//Only the first endpoint should be used currently
requestContext.Request.Endpoint = new Uri(endpoint.Address);
break;
}
}
}
private static IEnumerable<DiscoveryEndpointBase> ProcessEndpointDiscovery(IRequestContext requestContext, bool evictCacheKey, Uri evictUri)
{
var options = requestContext.Options;
if (options.EndpointDiscoveryMarshaller != null && options.EndpointOperation != null && requestContext.ImmutableCredentials != null)
{
//Endpoint discovery is supported by this operation and we have an endpoint operation available to use
var endpointDiscoveryData = options.EndpointDiscoveryMarshaller.Marshall(requestContext.OriginalRequest);
var operationName = string.Empty;
if (endpointDiscoveryData.Identifiers != null && endpointDiscoveryData.Identifiers.Count > 0)
{
operationName = OperationNameFromRequestName(requestContext.RequestName);
}
return options.EndpointOperation(new EndpointOperationContext(requestContext.ImmutableCredentials.AccessKey, operationName, endpointDiscoveryData, evictCacheKey, evictUri));
}
return null;
}
private static string OperationNameFromRequestName(string requestName)
{
if (requestName.EndsWith("Request", StringComparison.Ordinal))
{
return requestName.Substring(0, requestName.Length - 7);
}
return requestName;
}
private static bool IsInvalidEndpointException(Exception exception)
{
var serviceException = exception as AmazonServiceException;
if (serviceException != null && serviceException.StatusCode == (HttpStatusCode)INVALID_ENDPOINT_EXCEPTION_STATUSCODE)
{
return true;
}
return false;
}
}
}
| 211 |
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.Internal
{
/// <summary>
/// This handler resolves the endpoint to be used for the current request.
/// </summary>
public class EndpointResolver : PipelineHandler
{
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
PreInvoke(executionContext);
base.InvokeSync(executionContext);
}
#if AWS_ASYNC_API
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
PreInvoke(executionContext);
return base.InvokeAsync<T>(executionContext);
}
#elif AWS_APM_API
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <returns>IAsyncResult which represent an async operation.</returns>
public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
PreInvoke(ExecutionContext.CreateFromAsyncContext(executionContext));
return base.InvokeAsync(executionContext);
}
#endif
/// <summary>
/// Resolves the endpoint to be used for the current request
/// before invoking the next handler.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected void PreInvoke(IExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
if (requestContext.Request.Endpoint == null)
requestContext.Request.Endpoint = DetermineEndpoint(requestContext);
}
/// <summary>
/// Determines the endpoint for the request.
/// </summary>
/// <param name="requestContext">The request context.</param>
/// <returns></returns>
public virtual Uri DetermineEndpoint(IRequestContext requestContext)
{
return DetermineEndpoint(requestContext.ClientConfig, requestContext.Request);
}
public static Uri DetermineEndpoint(IClientConfig config, IRequest request)
{
Uri endpoint = request.AlternateEndpoint != null
? new Uri(ClientConfig.GetUrl(config, request.AlternateEndpoint))
: new Uri(config.DetermineServiceURL());
return InjectHostPrefix(config, request, endpoint);
}
private static Uri InjectHostPrefix(IClientConfig config, IRequest request, Uri endpoint)
{
if (config.DisableHostPrefixInjection || string.IsNullOrEmpty(request.HostPrefix))
{
return endpoint;
}
var hostPrefixUri = new UriBuilder(endpoint);
hostPrefixUri.Host = request.HostPrefix + hostPrefixUri.Host;
return hostPrefixUri.Uri;
}
}
}
| 113 |
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.Text;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This handler provides an OnError action that can be used as hook for
/// external code to handle exceptions in the runtime pipeline.
/// </summary>
public class ErrorCallbackHandler : PipelineHandler
{
/// <summary>
/// Action to execute if an exception occurs during the
/// execution of any underlying handlers.
/// </summary>
public Action<IExecutionContext,Exception> OnError { get; set; }
public override void InvokeSync(IExecutionContext executionContext)
{
try
{
base.InvokeSync(executionContext);
}
catch (Exception exception)
{
HandleException(executionContext, exception);
throw;
}
}
#if AWS_ASYNC_API
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
try
{
return await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
}
catch(Exception exception)
{
HandleException(executionContext, exception);
throw;
}
}
#elif AWS_APM_API
protected override void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
var exception = executionContext.ResponseContext.AsyncResult.Exception;
if (executionContext.ResponseContext.AsyncResult.Exception != null)
{
HandleException(ExecutionContext.CreateFromAsyncContext(executionContext), exception);
}
// Call outer handler
base.InvokeAsyncCallback(executionContext);
}
#endif
/// <summary>
/// Executes the OnError action if an exception occurs during the
/// execution of any underlying handlers.
/// </summary>
/// <param name="executionContext"></param>
/// <param name="exception"></param>
protected void HandleException(IExecutionContext executionContext, Exception exception)
{
OnError(executionContext, exception);
}
}
}
| 86 |
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 Amazon.Util;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This handler marshalls the request before calling invoking the next handler.
/// </summary>
public class Marshaller : PipelineHandler
{
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
PreInvoke(executionContext);
base.InvokeSync(executionContext);
}
#if AWS_ASYNC_API
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
PreInvoke(executionContext);
return base.InvokeAsync<T>(executionContext);
}
#elif AWS_APM_API
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <returns>IAsyncResult which represent an async operation.</returns>
public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
PreInvoke(ExecutionContext.CreateFromAsyncContext(executionContext));
return base.InvokeAsync(executionContext);
}
#endif
/// <summary>
/// Marshalls the request before calling invoking the next handler.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected static void PreInvoke(IExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
requestContext.Request = requestContext.Marshaller.Marshall(requestContext.OriginalRequest);
requestContext.Request.AuthenticationRegion = requestContext.ClientConfig.AuthenticationRegion;
var userAgent = $"{requestContext.ClientConfig.UserAgent} " +
$"{(executionContext.RequestContext.IsAsync ? "ClientAsync" : "ClientSync")}{requestContext.OriginalRequest.UserAgentAddition}";
if(requestContext.ClientConfig.UseAlternateUserAgentHeader)
{
requestContext.Request.Headers[HeaderKeys.XAmzUserAgentHeader] = userAgent;
}
else
{
requestContext.Request.Headers[HeaderKeys.UserAgentHeader] = userAgent;
}
#if NETSTANDARD
var method = requestContext.Request.HttpMethod.ToUpperInvariant();
#else
var method = requestContext.Request.HttpMethod.ToUpper(CultureInfo.InvariantCulture);
#endif
if (method != "GET" && method != "DELETE" && method != "HEAD")
{
if (!requestContext.Request.Headers.ContainsKey(HeaderKeys.ContentTypeHeader))
{
if (requestContext.Request.UseQueryString)
requestContext.Request.Headers[HeaderKeys.ContentTypeHeader] = "application/x-amz-json-1.0";
else
requestContext.Request.Headers[HeaderKeys.ContentTypeHeader] = AWSSDKUtils.UrlEncodedContent;
}
}
SetRecursionDetectionHeader(requestContext.Request.Headers);
}
/// <summary>
/// Sets the X-Amzn-Trace-Id header for recursion detection within Lambda workloads.
/// </summary>
/// <param name="headers">Current request headers before marshalling.</param>
private static void SetRecursionDetectionHeader(IDictionary<string, string> headers)
{
if (!headers.ContainsKey(HeaderKeys.XAmznTraceIdHeader))
{
var lambdaFunctionName = Environment.GetEnvironmentVariable(EnvironmentVariables.AWS_LAMBDA_FUNCTION_NAME);
var amznTraceId = Environment.GetEnvironmentVariable(EnvironmentVariables._X_AMZN_TRACE_ID);
if (!string.IsNullOrEmpty(lambdaFunctionName) && !string.IsNullOrEmpty(amznTraceId))
{
headers[HeaderKeys.XAmznTraceIdHeader] = AWSSDKUtils.EncodeTraceIdHeaderValue(amznTraceId);
}
}
}
}
}
| 132 |
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;
using Amazon.Runtime.Internal.Util;
using System.Globalization;
using System;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This handler manages the metrics used to time the complete call and
/// logs the final metrics.
/// </summary>
public class MetricsHandler : PipelineHandler
{
/// <summary>
/// Captures the overall execution time and logs final metrics.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
executionContext.RequestContext.Metrics.AddProperty(Metric.AsyncCall, false);
try
{
executionContext.RequestContext.Metrics.StartEvent(Metric.ClientExecuteTime);
base.InvokeSync(executionContext);
}
finally
{
executionContext.RequestContext.Metrics.StopEvent(Metric.ClientExecuteTime);
this.LogMetrics(executionContext);
}
}
#if AWS_ASYNC_API
/// <summary>
/// Captures the overall execution time and logs final metrics.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">
/// The execution context, it contains the request and response context.
/// </param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
executionContext.RequestContext.Metrics.AddProperty(Metric.AsyncCall, true);
try
{
executionContext.RequestContext.Metrics.StartEvent(Metric.ClientExecuteTime);
var response = await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
return response;
}
finally
{
executionContext.RequestContext.Metrics.StopEvent(Metric.ClientExecuteTime);
this.LogMetrics(executionContext);
}
}
#elif AWS_APM_API
/// <summary>
/// Captures the overall execution time.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <returns>IAsyncResult which represent an async operation.</returns>
public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
executionContext.RequestContext.Metrics.AddProperty(Metric.AsyncCall, true);
executionContext.RequestContext.Metrics.StartEvent(Metric.ClientExecuteTime);
return base.InvokeAsync(executionContext);
}
/// <summary>
/// Captures the overall execution time and logs final metrics.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected override void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
executionContext.RequestContext.Metrics.StopEvent(Metric.ClientExecuteTime);
this.LogMetrics(ExecutionContext.CreateFromAsyncContext(executionContext));
base.InvokeAsyncCallback(executionContext);
}
#endif
}
}
| 105 |
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.Transform;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using System;
using System.Net;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This handler processes HTTP redirects and reissues the call to the
/// redirected location.
/// </summary>
public class RedirectHandler : PipelineHandler
{
/// <summary>
/// Processes HTTP redirects and reissues the call to the
/// redirected location.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
do
{
base.InvokeSync(executionContext);
} while (HandleRedirect(executionContext));
}
#if AWS_ASYNC_API
/// <summary>
/// Processes HTTP redirects and reissues the call to the
/// redirected location.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
T result = null;
do
{
result = await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
} while (HandleRedirect(executionContext));
return result;
}
#elif AWS_APM_API
/// <summary>
/// Processes HTTP redirects and reissues the call to the
/// redirected location.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected override void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
// Check for redirect if an exception hasn't occured
if (executionContext.ResponseContext.AsyncResult.Exception == null)
{
// Check if a redirect is required
if (HandleRedirect(ExecutionContext.CreateFromAsyncContext(executionContext)))
{
// Call InvokeAsync to redirect to new location.
base.InvokeAsync(executionContext);
return;
}
}
// Not a redirect, call outer callbacks to continue processing response.
base.InvokeAsyncCallback(executionContext);
}
#endif
/// <summary>
/// Checks if an HTTP 307 (temporary redirect) has occured and changes the
/// request endpoint to the redirected location.
/// </summary>
/// <param name="executionContext">
/// The execution context, it contains the request and response context.
/// </param>
/// <returns>
/// A boolean value that indicates if a redirect has occured.
/// </returns>
private bool HandleRedirect(IExecutionContext executionContext)
{
var response = executionContext.ResponseContext.HttpResponse;
// Handle all HTTP 3xx status codes
if (response.StatusCode >= HttpStatusCode.Ambiguous &&
response.StatusCode < HttpStatusCode.BadRequest)
{
if (response.StatusCode == HttpStatusCode.TemporaryRedirect &&
response.IsHeaderPresent(HeaderKeys.LocationHeader))
{
var requestContext = executionContext.RequestContext;
string redirectedLocation = response.GetHeaderValue(HeaderKeys.LocationHeader);
requestContext.Metrics.AddProperty(Metric.RedirectLocation, redirectedLocation);
var isRewindableStream = executionContext.RequestContext.Request.IsRequestStreamRewindable();
if (isRewindableStream &&
!string.IsNullOrEmpty(redirectedLocation))
{
FinalizeForRedirect(executionContext, redirectedLocation);
// Dispose the current response body before we redirect.
if (response.ResponseBody != null)
{
response.ResponseBody.Dispose();
}
return true;
}
}
// Set HttpResponse on ResponseContext to null,
// as the HttpResponse will be wrapped in an exception.
executionContext.ResponseContext.HttpResponse = null;
// Throw an exception contain the HTTP response, so that an
// appropriate exception can be returned to the user.
throw new HttpErrorResponseException(response);
}
return false;
}
protected virtual void FinalizeForRedirect(IExecutionContext executionContext, string redirectedLocation)
{
this.Logger.InfoFormat("Request {0} is being redirected to {1}.",
executionContext.RequestContext.RequestName,
redirectedLocation);
var uri = new Uri(redirectedLocation);
var requestContext = executionContext.RequestContext;
if (uri.IsDefaultPort)
{
requestContext.Request.Endpoint = new UriBuilder(uri.Scheme, uri.Host).Uri;
}
else
{
requestContext.Request.Endpoint = new UriBuilder(uri.Scheme, uri.Host, uri.Port).Uri;
}
RetryHandler.PrepareForRetry(executionContext.RequestContext);
}
}
}
| 166 |
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.Auth;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using System;
using System.IO;
#if AWS_ASYNC_API
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This handler signs the request.
/// </summary>
public class Signer : PipelineHandler
{
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
PreInvoke(executionContext);
base.InvokeSync(executionContext);
}
#if AWS_ASYNC_API
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
await PreInvokeAsync(executionContext).ConfigureAwait(false);
return await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
}
#elif AWS_APM_API
/// <summary>
/// Calls pre invoke logic before calling the next handler
/// in the pipeline.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <returns>IAsyncResult which represent an async operation.</returns>
public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
PreInvoke(ExecutionContext.CreateFromAsyncContext(executionContext));
return base.InvokeAsync(executionContext);
}
#endif
/// <summary>
/// Signs the request before invoking the next handler.
/// </summary>
/// <param name="executionContext">
/// The execution context, it contains the request and response context.
/// </param>
protected static void PreInvoke(IExecutionContext executionContext)
{
if (ShouldSign(executionContext.RequestContext))
{
SignRequest(executionContext.RequestContext);
executionContext.RequestContext.IsSigned = true;
}
}
#if AWS_ASYNC_API
protected static async System.Threading.Tasks.Task PreInvokeAsync(IExecutionContext executionContext)
{
if (ShouldSign(executionContext.RequestContext))
{
await SignRequestAsync(executionContext.RequestContext).ConfigureAwait(false);
executionContext.RequestContext.IsSigned = true;
}
}
#endif
/// <summary>
/// Determines if the request should be signed.
/// </summary>
/// <param name="requestContext">The request context.</param>
/// <returns>A boolean value that indicated if the request should be signed.</returns>
private static bool ShouldSign(IRequestContext requestContext)
{
return !requestContext.IsSigned ||
requestContext.ClientConfig.ResignRetries;
}
/// <summary>
/// Signs the request.
/// </summary>
/// <param name="requestContext">The request context.</param>
public static void SignRequest(IRequestContext requestContext)
{
ImmutableCredentials immutableCredentials = requestContext.ImmutableCredentials;
// credentials would be null in the case of anonymous users getting public resources from S3
if (immutableCredentials == null && requestContext.Signer.RequiresCredentials)
return;
using (requestContext.Metrics.StartEvent(Metric.RequestSigningTime))
{
if (immutableCredentials?.UseToken == true &&
!(requestContext.Signer is NullSigner) &&
!(requestContext.Signer is BearerTokenSigner))
{
ClientProtocol protocol = requestContext.Signer.Protocol;
switch (protocol)
{
case ClientProtocol.QueryStringProtocol:
requestContext.Request.Parameters["SecurityToken"] = immutableCredentials.Token;
break;
case ClientProtocol.RestProtocol:
requestContext.Request.Headers[HeaderKeys.XAmzSecurityTokenHeader] = immutableCredentials.Token;
break;
default:
throw new InvalidDataException("Cannot determine protocol");
}
}
requestContext.Signer.Sign(requestContext.Request, requestContext.ClientConfig, requestContext.Metrics, immutableCredentials);
}
}
#if AWS_ASYNC_API
/// <summary>
/// Signs the request.
/// </summary>
/// <param name="requestContext">The request context.</param>
private static async Task SignRequestAsync(IRequestContext requestContext)
{
ImmutableCredentials immutableCredentials = requestContext.ImmutableCredentials;
// credentials would be null in the case of anonymous users getting public resources from S3
if (immutableCredentials == null && requestContext.Signer.RequiresCredentials)
return;
using (requestContext.Metrics.StartEvent(Metric.RequestSigningTime))
{
if (immutableCredentials?.UseToken == true &&
!(requestContext.Signer is NullSigner) &&
!(requestContext.Signer is BearerTokenSigner))
{
ClientProtocol protocol = requestContext.Signer.Protocol;
switch (protocol)
{
case ClientProtocol.QueryStringProtocol:
requestContext.Request.Parameters["SecurityToken"] = immutableCredentials.Token;
break;
case ClientProtocol.RestProtocol:
requestContext.Request.Headers[HeaderKeys.XAmzSecurityTokenHeader] = immutableCredentials.Token;
break;
default:
throw new InvalidDataException("Cannot determine protocol");
}
}
await requestContext.Signer
.SignAsync(
requestContext.Request,
requestContext.ClientConfig,
requestContext.Metrics,
immutableCredentials)
.ConfigureAwait(false);
}
}
#endif
}
}
| 192 |
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.Internal.Transform;
using Amazon.Util;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// This handler unmarshalls the HTTP response.
/// </summary>
public class Unmarshaller : PipelineHandler
{
private bool _supportsResponseLogging;
/// <summary>
/// The constructor for Unmarshaller.
/// </summary>
/// <param name="supportsResponseLogging">
/// Boolean value which indicated if the unmarshaller
/// handler supports response logging.
/// </param>
public Unmarshaller(bool supportsResponseLogging)
{
_supportsResponseLogging = supportsResponseLogging;
}
/// <summary>
/// Unmarshalls the response returned by the HttpHandler.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
base.InvokeSync(executionContext);
if (executionContext.ResponseContext.HttpResponse.IsSuccessStatusCode)
{
// Unmarshall the http response.
Unmarshall(executionContext);
}
}
#if BCL45
/// <summary>
/// Unmarshalls the response returned by the HttpHandler.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
// Unmarshall the response
Unmarshall(executionContext);
return (T)executionContext.ResponseContext.Response;
}
#elif NETSTANDARD
/// <summary>
/// Unmarshalls the response returned by the HttpHandler.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
// Unmarshall the response
await UnmarshallAsync(executionContext).ConfigureAwait(false);
return (T)executionContext.ResponseContext.Response;
}
#elif AWS_APM_API
/// <summary>
/// Unmarshalls the response returned by the HttpHandler.
/// </summary>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
protected override void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
// Unmarshall the response if an exception hasn't occured
if (executionContext.ResponseContext.AsyncResult.Exception == null)
{
Unmarshall(ExecutionContext.CreateFromAsyncContext(executionContext));
}
base.InvokeAsyncCallback(executionContext);
}
#endif
/// <summary>
/// Unmarshalls the HTTP response.
/// </summary>
/// <param name="executionContext">
/// The execution context, it contains the request and response context.
/// </param>
private void Unmarshall(IExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
var responseContext = executionContext.ResponseContext;
using (requestContext.Metrics.StartEvent(Metric.ResponseProcessingTime))
{
var unmarshaller = requestContext.Unmarshaller;
try
{
var readEntireResponse = _supportsResponseLogging;
var context = unmarshaller.CreateContext(responseContext.HttpResponse,
readEntireResponse,
responseContext.HttpResponse.ResponseBody.OpenResponse(),
requestContext.Metrics,
false,
requestContext);
try
{
var response = UnmarshallResponse(context, requestContext);
responseContext.Response = response;
}
catch(Exception e)
{
// Rethrow Amazon service or client exceptions
if (e is AmazonServiceException ||
e is AmazonClientException)
{
throw;
}
// Else, there was an issue with the response body, throw AmazonUnmarshallingException
var requestId = responseContext.HttpResponse.GetHeaderValue(HeaderKeys.RequestIdHeader);
var body = context.ResponseBody;
throw new AmazonUnmarshallingException(requestId, lastKnownLocation: null, responseBody: body, innerException: e,
statusCode: responseContext.HttpResponse.StatusCode);
}
}
finally
{
if (!unmarshaller.HasStreamingProperty)
responseContext.HttpResponse.ResponseBody.Dispose();
}
}
}
#if NETSTANDARD
/// <summary>
/// Unmarshalls the HTTP response.
/// </summary>
/// <param name="executionContext">
/// The execution context, it contains the request and response context.
/// </param>
private async System.Threading.Tasks.Task UnmarshallAsync(IExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
var responseContext = executionContext.ResponseContext;
using (requestContext.Metrics.StartEvent(Metric.ResponseProcessingTime))
{
var unmarshaller = requestContext.Unmarshaller;
try
{
var readEntireResponse = _supportsResponseLogging &&
(requestContext.ClientConfig.LogResponse || requestContext.ClientConfig.ReadEntireResponse
|| AWSConfigs.LoggingConfig.LogResponses != ResponseLoggingOption.Never);
var responseStream = await responseContext.HttpResponse.
ResponseBody.OpenResponseAsync().ConfigureAwait(false);
var context = unmarshaller.CreateContext(responseContext.HttpResponse,
readEntireResponse,
responseStream,
requestContext.Metrics,
false,
requestContext);
var response = UnmarshallResponse(context, requestContext);
responseContext.Response = response;
}
finally
{
if (!unmarshaller.HasStreamingProperty)
responseContext.HttpResponse.ResponseBody.Dispose();
}
}
}
#endif
private AmazonWebServiceResponse UnmarshallResponse(UnmarshallerContext context,
IRequestContext requestContext)
{
try
{
var unmarshaller = requestContext.Unmarshaller;
AmazonWebServiceResponse response = null;
using (requestContext.Metrics.StartEvent(Metric.ResponseUnmarshallTime))
{
response = unmarshaller.UnmarshallResponse(context);
}
requestContext.Metrics.AddProperty(Metric.StatusCode, response.HttpStatusCode);
requestContext.Metrics.AddProperty(Metric.BytesProcessed, response.ContentLength);
if (response.ResponseMetadata != null)
{
requestContext.Metrics.AddProperty(Metric.AWSRequestID, response.ResponseMetadata.RequestId);
}
context.ValidateCRC32IfAvailable();
context.ValidateFlexibleCheckumsIfAvailable(response.ResponseMetadata);
return response;
}
finally
{
var logResponseBody = ShouldLogResponseBody(_supportsResponseLogging, requestContext);
if (logResponseBody)
{
this.Logger.DebugFormat("Received response (truncated to {0} bytes): [{1}]",
AWSConfigs.LoggingConfig.LogResponsesSizeLimit,
context.ResponseBody);
}
}
}
private static bool ShouldLogResponseBody(bool supportsResponseLogging, IRequestContext requestContext)
{
return supportsResponseLogging &&
(requestContext.ClientConfig.LogResponse || AWSConfigs.LoggingConfig.LogResponses == ResponseLoggingOption.Always);
}
}
}
| 249 |
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;
using Amazon.Runtime.Internal.Util;
using System.Globalization;
using System;
using System.Text;
using System.Collections.Generic;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The CSM handler has the logic for capturing data for CSM attempts when enabled.
/// </summary>
public class CSMCallAttemptHandler : PipelineHandler
{
/// <summary>
/// Invokes the CSM handler and captures data for the CSM attempts.
/// </summary>
public override void InvokeSync(IExecutionContext executionContext)
{
try
{
PreInvoke(executionContext);
base.InvokeSync(executionContext);
}
catch (AmazonServiceException e)
{
CaptureAmazonException(executionContext.RequestContext.CSMCallAttempt, e);
throw;
}
catch (Exception e)
{
CaptureSDKExceptionMessage(executionContext.RequestContext.CSMCallAttempt, e);
throw;
}
finally
{
CSMCallAttemptMetricsCapture(executionContext.RequestContext, executionContext.ResponseContext);
CSMUtilities.SerializetoJsonAndPostOverUDP(executionContext.RequestContext.CSMCallAttempt);
}
}
#if AWS_ASYNC_API
/// <summary>
/// Calls the PreInvoke and PostInvoke methods before and after calling the next handler
/// in the pipeline.
/// </summary>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
try
{
PreInvoke(executionContext);
var response = await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
return response;
}
catch (AmazonServiceException e)
{
CaptureAmazonException(executionContext.RequestContext.CSMCallAttempt, e);
throw;
}
catch (Exception e)
{
CaptureSDKExceptionMessage(executionContext.RequestContext.CSMCallAttempt, e);
throw;
}
finally
{
CSMCallAttemptMetricsCapture(executionContext.RequestContext, executionContext.ResponseContext);
CSMUtilities.SerializetoJsonAndPostOverUDPAsync(executionContext.RequestContext.CSMCallAttempt).ConfigureAwait(false);
}
}
#elif AWS_APM_API
/// <summary>
/// Invokes the CSM handler and captures data for the CSM attempts.
/// </summary>
public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
PreInvoke(ExecutionContext.CreateFromAsyncContext(executionContext));
return base.InvokeAsync(executionContext);
}
protected override void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
var syncExecutionContext = ExecutionContext.CreateFromAsyncContext(executionContext);
if (executionContext.ResponseContext.AsyncResult.Exception != null)
{
var exception = executionContext.ResponseContext.AsyncResult.Exception;
if (exception is AmazonServiceException)
{
CaptureAmazonException(syncExecutionContext.RequestContext.CSMCallAttempt, exception as AmazonServiceException);
}
else
{
if(syncExecutionContext.ResponseContext.HttpResponse == null)
{
CaptureSDKExceptionMessage(syncExecutionContext.RequestContext.CSMCallAttempt, exception);
}
}
}
CSMCallAttemptMetricsCapture(syncExecutionContext.RequestContext, syncExecutionContext.ResponseContext);
CSMUtilities.BeginSerializetoJsonAndPostOverUDP(executionContext.RequestContext.CSMCallAttempt);
base.InvokeAsyncCallback(executionContext);
}
#endif
/// <summary>
/// Method that gets called in the final clause that captures data for each http request
/// from the request and response context.
/// </summary>
protected static void CSMCallAttemptMetricsCapture(IRequestContext requestContext, IResponseContext responseContext)
{
requestContext.CSMCallAttempt.Service = requestContext.CSMCallEvent.Service;
requestContext.CSMCallAttempt.Fqdn = requestContext.Request.GetHeaderValue(HeaderKeys.HostHeader);
bool useAlternateUserAgentHeader = (requestContext.ClientConfig as ClientConfig)?.UseAlternateUserAgentHeader ?? false;
requestContext.CSMCallAttempt.UserAgent = requestContext.Request.GetHeaderValue(useAlternateUserAgentHeader ? HeaderKeys.XAmzUserAgentHeader : HeaderKeys.UserAgentHeader);
requestContext.CSMCallAttempt.SessionToken = requestContext.Request.GetHeaderValue(HeaderKeys.XAmzSecurityTokenHeader);
requestContext.CSMCallAttempt.Region = requestContext.Request.DeterminedSigningRegion;
requestContext.CSMCallAttempt.Api = CSMUtilities.
GetApiNameFromRequest(requestContext.Request.RequestName, requestContext.ServiceMetaData.OperationNameMapping, requestContext.CSMCallAttempt.Service);
requestContext.CSMCallAttempt.AccessKey = requestContext.ImmutableCredentials.AccessKey;
requestContext.CSMCallAttempt.AttemptLatency = AWSSDKUtils.ConvertTimeSpanToMilliseconds(requestContext
.Metrics.StopEvent(Metric.CSMAttemptLatency)
.ElapsedTime);
if (responseContext.HttpResponse != null)
{
if((int) responseContext.HttpResponse.StatusCode > 0)
{
requestContext.CSMCallAttempt.HttpStatusCode = (int)responseContext.HttpResponse.StatusCode;
}
requestContext.CSMCallAttempt.XAmznRequestId = responseContext.HttpResponse.GetHeaderValue(HeaderKeys.RequestIdHeader);
requestContext.CSMCallAttempt.XAmzRequestId = responseContext.HttpResponse.GetHeaderValue(HeaderKeys.XAmzRequestIdHeader);
requestContext.CSMCallAttempt.XAmzId2 = responseContext.HttpResponse.GetHeaderValue(HeaderKeys.XAmzId2Header);
}
}
/// <summary>
/// Executes the OnPreInvoke action as part of pre-invoke.
/// </summary>
protected virtual void PreInvoke(IExecutionContext executionContext)
{
executionContext.RequestContext.CSMCallAttempt = new MonitoringAPICallAttempt(executionContext.RequestContext);
executionContext.RequestContext.Metrics.StartEvent(Metric.CSMAttemptLatency);
}
/// <summary>
/// Method to collect data in case of connection exception
/// </summary>
private static void CaptureSDKExceptionMessage(MonitoringAPICallAttempt monitoringAPICallAttempt, Exception e)
{
monitoringAPICallAttempt.SdkException = e.GetType().Name.ToString().Length <= 128 ? e.GetType().Name.ToString() : string.Empty;
monitoringAPICallAttempt.SdkExceptionMessage = e.Message.Length <= 512 ? e.Message : string.Empty;
}
/// <summary>
/// Method to collect data in case of Amazon service exception
/// </summary>
private static void CaptureAmazonException(MonitoringAPICallAttempt monitoringAPICallAttempt, AmazonServiceException e)
{
if ((int)e.StatusCode > 0)
{
monitoringAPICallAttempt.HttpStatusCode = (int)e.StatusCode;
}
if (e.ErrorCode == null)
{
CaptureSDKExceptionMessage(monitoringAPICallAttempt, e);
return;
}
monitoringAPICallAttempt.AWSException = e.ErrorCode.Length <= 128 ? e.ErrorCode : string.Empty;
monitoringAPICallAttempt.AWSExceptionMessage =
e.Message.Length <= 512 ? e.Message : string.Empty;
}
}
}
| 200 |
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;
using Amazon.Runtime.Internal.Util;
using System.Globalization;
using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The CSM handler has the logic for capturing data for CSM events when enabled.
/// </summary>
public class CSMCallEventHandler : PipelineHandler
{
// Stopwatch to measure API call latency.
private Stopwatch stopWatch;
/// <summary>
/// Invokes the CSM handler and captures data for the CSM events.
/// </summary>
public override void InvokeSync(IExecutionContext executionContext)
{
try
{
PreInvoke(executionContext);
base.InvokeSync(executionContext);
}
catch (Exception e)
{
CaptureCSMCallEventExceptionData(executionContext.RequestContext, e);
throw;
}
finally
{
CSMCallEventMetricsCapture(executionContext);
CSMUtilities.SerializetoJsonAndPostOverUDP(executionContext.RequestContext.CSMCallEvent);
}
}
#if AWS_ASYNC_API
/// <summary>
/// Calls the PreInvoke and PostInvoke methods before and after calling the next handler
/// in the pipeline.
/// </summary>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
try
{
PreInvoke(executionContext);
var response = await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
return response;
}
catch (Exception e)
{
CaptureCSMCallEventExceptionData(executionContext.RequestContext, e);
throw;
}
finally
{
CSMCallEventMetricsCapture(executionContext);
CSMUtilities.SerializetoJsonAndPostOverUDPAsync(executionContext.RequestContext.CSMCallEvent).ConfigureAwait(false);
}
}
#elif AWS_APM_API
/// <summary>
/// Invokes the CSM handler and captures data for the CSM events.
/// </summary>
public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
PreInvoke(ExecutionContext.CreateFromAsyncContext(executionContext));
return base.InvokeAsync(executionContext);
}
protected override void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
if (executionContext.ResponseContext.AsyncResult.Exception != null)
{
CaptureCSMCallEventExceptionData(executionContext.RequestContext, executionContext.ResponseContext.AsyncResult.Exception);
}
CSMCallEventMetricsCapture(ExecutionContext.CreateFromAsyncContext(executionContext));
CSMUtilities.BeginSerializetoJsonAndPostOverUDP(executionContext.RequestContext.CSMCallEvent);
base.InvokeAsyncCallback(executionContext);
}
#endif
/// <summary>
/// Invoked from the finally block of CSMCallEventHandler's Invoke method.
/// This method is used to capture CSM Call event metrics.
/// </summary>
/// <param name="executionContext"></param>
private void CSMCallEventMetricsCapture(IExecutionContext executionContext)
{
// Stop timer for measuring API call latency.
stopWatch.Stop();
// Record CSM call event metrics.
executionContext.RequestContext.CSMCallEvent.AttemptCount = executionContext.RequestContext.Retries + 1;
executionContext.RequestContext.CSMCallEvent.Service = executionContext.RequestContext.ServiceMetaData.ServiceId;
executionContext.RequestContext.CSMCallEvent.Api = executionContext.RequestContext.CSMCallAttempt.Api;
executionContext.RequestContext.CSMCallEvent.Region = executionContext.RequestContext.CSMCallAttempt.Region;
executionContext.RequestContext.CSMCallEvent.Latency = stopWatch.ElapsedMilliseconds;
executionContext.RequestContext.CSMCallEvent.FinalHttpStatusCode = executionContext.RequestContext.CSMCallAttempt.HttpStatusCode;
bool useAlternateUserAgentHeader = (executionContext.RequestContext.ClientConfig as ClientConfig)?.UseAlternateUserAgentHeader ?? false;
executionContext.RequestContext.CSMCallEvent.UserAgent = executionContext.RequestContext.Request.GetHeaderValue(useAlternateUserAgentHeader ? HeaderKeys.XAmzUserAgentHeader : HeaderKeys.UserAgentHeader);
}
/// <summary>
/// Method that gets invoked in case of an exception in the API request completion.
/// </summary>
/// <param name="requestContext"></param>
/// <param name="exception"></param>
private static void CaptureCSMCallEventExceptionData(IRequestContext requestContext, Exception exception)
{
// Set IsLastExceptionRetryable value on CSMCallEvent to whether the final exception thrown as part of
// of the API request completion was retryable or not.
requestContext.CSMCallEvent.IsLastExceptionRetryable = requestContext.IsLastExceptionRetryable;
if(exception is AmazonServiceException)
{
requestContext.CSMCallEvent.FinalAWSException = requestContext.CSMCallAttempt.AWSException;
requestContext.CSMCallEvent.FinalAWSExceptionMessage = requestContext.CSMCallAttempt.AWSExceptionMessage;
}
else
{
requestContext.CSMCallEvent.FinalSdkException = requestContext.CSMCallAttempt.SdkException;
requestContext.CSMCallEvent.FinalSdkExceptionMessage = requestContext.CSMCallAttempt.SdkExceptionMessage;
}
}
protected void PreInvoke(IExecutionContext executionContext)
{
stopWatch = Stopwatch.StartNew();
}
}
}
| 150 |
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.Net;
namespace Amazon.Runtime.Internal
{
public interface IAmazonSecurityProtocolManager
{
bool IsSecurityProtocolSystemDefault();
void UpdateProtocolsToSupported();
}
public class AmazonSecurityProtocolManager : IAmazonSecurityProtocolManager
{
private const SecurityProtocolType Tls11 = (SecurityProtocolType)0x00000300; // 0x00000300 adds support for TLS 1.1
private const SecurityProtocolType Tls12 = (SecurityProtocolType)0x00000C00; // 0x00000C00 adds support for TLS 1.2
private const SecurityProtocolType SupportedTls = Tls11 | Tls12;
private const SecurityProtocolType SystemDefault = 0x00000000; // 0x00000000 SystemDefault was introduced in .NET 4.7
public bool IsSecurityProtocolSystemDefault()
{
return ServicePointManager.SecurityProtocol == SystemDefault;
}
public void UpdateProtocolsToSupported()
{
var existingSecurityProtocol = ServicePointManager.SecurityProtocol;
try
{
ServicePointManager.SecurityProtocol |= SupportedTls;
}
catch (NotSupportedException ex)
{
ServicePointManager.SecurityProtocol = existingSecurityProtocol;
throw new NotSupportedException(
"TLS version 1.1 or 1.2 are not supported on this system. Some AWS services will refuse traffic." +
" Please consider updating to a system that supports newer security protocols.", ex);
}
}
}
} | 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.
*/
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using Amazon.Util.Internal;
using System;
using System.Globalization;
using System.Net;
using System.Reflection;
using System.Text;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The HTTP handler contains common logic for issuing an HTTP request that is
/// independent of the underlying HTTP infrastructure.
/// </summary>
/// <typeparam name="TRequestContent"></typeparam>
public class HttpHandler<TRequestContent> : PipelineHandler, IDisposable
{
private bool _disposed;
private IHttpRequestFactory<TRequestContent> _requestFactory;
/// <summary>
/// The sender parameter used in any events raised by this handler.
/// </summary>
public object CallbackSender { get; private set; }
/// <summary>
/// The constructor for HttpHandler.
/// </summary>
/// <param name="requestFactory">The request factory used to create HTTP Requests.</param>
/// <param name="callbackSender">The sender parameter used in any events raised by this handler.</param>
public HttpHandler(IHttpRequestFactory<TRequestContent> requestFactory, object callbackSender)
{
_requestFactory = requestFactory;
this.CallbackSender = callbackSender;
}
/// <summary>
/// Issues an HTTP request for the current request context.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
IHttpRequest<TRequestContent> httpRequest = null;
try
{
SetMetrics(executionContext.RequestContext);
IRequest wrappedRequest = executionContext.RequestContext.Request;
httpRequest = CreateWebRequest(executionContext.RequestContext);
httpRequest.SetRequestHeaders(wrappedRequest.Headers);
using (executionContext.RequestContext.Metrics.StartEvent(Metric.HttpRequestTime))
{
// Send request body if present.
if (wrappedRequest.HasRequestBody())
{
try
{
var requestContent = httpRequest.GetRequestContent();
WriteContentToRequestBody(requestContent, httpRequest, executionContext.RequestContext);
}
catch
{
CompleteFailedRequest(httpRequest);
throw;
}
}
executionContext.ResponseContext.HttpResponse = httpRequest.GetResponse();
}
}
finally
{
if (httpRequest != null)
httpRequest.Dispose();
}
}
private static void CompleteFailedRequest(IHttpRequest<TRequestContent> httpRequest)
{
try
{
// In some cases where writing the request body fails, HttpWebRequest.Abort
// may not dispose of the underlying Socket, so we need to retrieve and dispose
// the web response to close the socket
IWebResponseData response = null;
try
{
response = httpRequest.GetResponse();
}
catch (WebException webException)
{
if (webException.Response != null)
{
#if BCL35
webException.Response.Close();
#else
webException.Response.Dispose();
#endif
}
}
catch (HttpErrorResponseException httpErrorResponse)
{
if (httpErrorResponse.Response != null && httpErrorResponse.Response.ResponseBody != null)
httpErrorResponse.Response.ResponseBody.Dispose();
}
finally
{
if (response != null && response.ResponseBody != null)
response.ResponseBody.Dispose();
}
}
catch { }
}
#if AWS_ASYNC_API
/// <summary>
/// Issues an HTTP request for the current request context.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
IHttpRequest<TRequestContent> httpRequest = null;
try
{
SetMetrics(executionContext.RequestContext);
IRequest wrappedRequest = executionContext.RequestContext.Request;
httpRequest = CreateWebRequest(executionContext.RequestContext);
httpRequest.SetRequestHeaders(wrappedRequest.Headers);
using(executionContext.RequestContext.Metrics.StartEvent(Metric.HttpRequestTime))
{
// Send request body if present.
if (wrappedRequest.HasRequestBody())
{
System.Runtime.ExceptionServices.ExceptionDispatchInfo edi = null;
try
{
// In .NET Framework, there needs to be a cancellation token in this method since GetRequestStreamAsync
// does not accept a cancellation token. A workaround is used. This isn't necessary in .NET Standard
// where the stream is a property of the request.
#if BCL45
var requestContent = await httpRequest.GetRequestContentAsync(executionContext.RequestContext.CancellationToken).ConfigureAwait(false);
await WriteContentToRequestBodyAsync(requestContent, httpRequest, executionContext.RequestContext).ConfigureAwait(false);
#else
var requestContent = await httpRequest.GetRequestContentAsync().ConfigureAwait(false);
WriteContentToRequestBody(requestContent, httpRequest, executionContext.RequestContext);
#endif
}
catch(Exception e)
{
edi = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e);
}
if (edi != null)
{
await CompleteFailedRequest(executionContext, httpRequest).ConfigureAwait(false);
edi.Throw();
}
}
var response = await httpRequest.GetResponseAsync(executionContext.RequestContext.CancellationToken).
ConfigureAwait(false);
executionContext.ResponseContext.HttpResponse = response;
}
// The response is not unmarshalled yet.
return null;
}
finally
{
if (httpRequest != null)
httpRequest.Dispose();
}
}
private static async System.Threading.Tasks.Task CompleteFailedRequest(IExecutionContext executionContext, IHttpRequest<TRequestContent> httpRequest)
{
// In some cases where writing the request body fails, HttpWebRequest.Abort
// may not dispose of the underlying Socket, so we need to retrieve and dispose
// the web response to close the socket
IWebResponseData iwrd = null;
try
{
iwrd = await httpRequest.GetResponseAsync(executionContext.RequestContext.CancellationToken).ConfigureAwait(false);
}
catch { }
finally
{
if (iwrd != null && iwrd.ResponseBody != null)
iwrd.ResponseBody.Dispose();
}
}
#elif AWS_APM_API
/// <summary>
/// Issues an HTTP request for the current request context.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <returns>IAsyncResult which represent an async operation.</returns>
public override IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
IHttpRequest<TRequestContent> httpRequest = null;
try
{
SetMetrics(executionContext.RequestContext);
httpRequest = CreateWebRequest(executionContext.RequestContext);
executionContext.RuntimeState = httpRequest;
IRequest wrappedRequest = executionContext.RequestContext.Request;
if (executionContext.RequestContext.Retries == 0)
{
// First call, initialize an async result.
executionContext.ResponseContext.AsyncResult =
new RuntimeAsyncResult(executionContext.RequestContext.Callback,
executionContext.RequestContext.State);
}
// Set request headers
httpRequest.SetRequestHeaders(executionContext.RequestContext.Request.Headers);
executionContext.RequestContext.Metrics.StartEvent(Metric.HttpRequestTime);
if (wrappedRequest.HasRequestBody())
{
// Send request body if present.
httpRequest.BeginGetRequestContent(new AsyncCallback(GetRequestStreamCallback), executionContext);
}
else
{
// Get response if there is no response body to send.
httpRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), executionContext);
}
return executionContext.ResponseContext.AsyncResult;
}
catch (Exception exception)
{
if (executionContext.ResponseContext.AsyncResult != null)
{
// An exception will be thrown back to the calling code.
// Dispose AsyncResult as it will not be used further.
executionContext.ResponseContext.AsyncResult.Dispose();
executionContext.ResponseContext.AsyncResult = null;
}
if (httpRequest != null)
{
httpRequest.Dispose();
}
// Log this exception as it will not be caught by ErrorHandler.
this.Logger.Error(exception, "An exception occured while initiating an asynchronous HTTP request.");
throw;
}
}
private void GetRequestStreamCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
System.Threading.ThreadPool.QueueUserWorkItem(GetRequestStreamCallbackHelper, result);
}
else
{
GetRequestStreamCallbackHelper(result);
}
}
private void GetRequestStreamCallbackHelper(object state)
{
IAsyncResult result = state as IAsyncResult;
IAsyncExecutionContext executionContext = null;
IHttpRequest<TRequestContent> httpRequest = null;
try
{
executionContext = result.AsyncState as IAsyncExecutionContext;
httpRequest = executionContext.RuntimeState as IHttpRequest<TRequestContent>;
var requestContent = httpRequest.EndGetRequestContent(result);
WriteContentToRequestBody(requestContent, httpRequest, executionContext.RequestContext);
//var requestStream = httpRequest.EndSetRequestBody(result);
httpRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), executionContext);
}
catch (Exception exception)
{
httpRequest.Dispose();
// Capture the exception and invoke outer handlers to
// process the exception.
executionContext.ResponseContext.AsyncResult.Exception = exception;
base.InvokeAsyncCallback(executionContext);
}
}
private void GetResponseCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
System.Threading.ThreadPool.QueueUserWorkItem(GetResponseCallbackHelper, result);
}
else
{
GetResponseCallbackHelper(result);
}
}
private void GetResponseCallbackHelper(object state)
{
IAsyncResult result = state as IAsyncResult;
IAsyncExecutionContext executionContext = null;
IHttpRequest<TRequestContent> httpRequest = null;
try
{
executionContext = result.AsyncState as IAsyncExecutionContext;
httpRequest = executionContext.RuntimeState as IHttpRequest<TRequestContent>;
var httpResponse = httpRequest.EndGetResponse(result);
executionContext.ResponseContext.HttpResponse = httpResponse;
}
catch (Exception exception)
{
// Capture the exception and invoke outer handlers to
// process the exception.
executionContext.ResponseContext.AsyncResult.Exception = exception;
}
finally
{
executionContext.RequestContext.Metrics.StopEvent(Metric.HttpRequestTime);
httpRequest.Dispose();
base.InvokeAsyncCallback(executionContext);
}
}
#endif
private static void SetMetrics(IRequestContext requestContext)
{
requestContext.Metrics.AddProperty(Metric.ServiceName, requestContext.Request.ServiceName);
requestContext.Metrics.AddProperty(Metric.ServiceEndpoint, requestContext.Request.Endpoint);
requestContext.Metrics.AddProperty(Metric.MethodName, requestContext.Request.RequestName);
}
/// <summary>
/// Determines the content for request body and uses the HTTP request
/// to write the content to the HTTP request body.
/// </summary>
/// <param name="requestContent">Content to be written.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <param name="requestContext">The request context.</param>
private void WriteContentToRequestBody(TRequestContent requestContent,
IHttpRequest<TRequestContent> httpRequest,
IRequestContext requestContext)
{
IRequest wrappedRequest = requestContext.Request;
// This code path ends up using a ByteArrayContent for System.Net.HttpClient used by .NET Core.
// HttpClient can't seem to handle ByteArrayContent with 0 length so in that case use
// the StreamContent code path.
if (wrappedRequest.Content != null && wrappedRequest.Content.Length > 0)
{
byte[] requestData = wrappedRequest.Content;
requestContext.Metrics.AddProperty(Metric.RequestSize, requestData.Length);
httpRequest.WriteToRequestBody(requestContent, requestData, requestContext.Request.Headers);
}
else
{
System.IO.Stream originalStream;
if (wrappedRequest.ContentStream == null)
{
originalStream = new System.IO.MemoryStream();
originalStream.Write(wrappedRequest.Content, 0, wrappedRequest.Content.Length);
originalStream.Position = 0;
}
else
{
originalStream = wrappedRequest.ContentStream;
}
var callback = ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)wrappedRequest.OriginalRequest).StreamUploadProgressCallback;
if (callback != null)
originalStream = httpRequest.SetupProgressListeners(originalStream, requestContext.ClientConfig.ProgressUpdateInterval, this.CallbackSender, callback);
var inputStream = GetInputStream(requestContext, originalStream, wrappedRequest);
httpRequest.WriteToRequestBody(requestContent, inputStream,
requestContext.Request.Headers, requestContext);
}
}
#if BCL45
/// <summary>
/// Determines the content for request body and uses the HTTP request
/// to write the content to the HTTP request body.
/// </summary>
/// <param name="requestContent">Content to be written.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <param name="requestContext">The request context.</param>
private async System.Threading.Tasks.Task WriteContentToRequestBodyAsync(TRequestContent requestContent,
IHttpRequest<TRequestContent> httpRequest,
IRequestContext requestContext)
{
IRequest wrappedRequest = requestContext.Request;
// This code path ends up using a ByteArrayContent for System.Net.HttpClient used by .NET Core.
// HttpClient can't seem to handle ByteArrayContent with 0 length so in that case use
// the StreamContent code path.
if (wrappedRequest.Content != null && wrappedRequest.Content.Length > 0)
{
byte[] requestData = wrappedRequest.Content;
requestContext.Metrics.AddProperty(Metric.RequestSize, requestData.Length);
await httpRequest.WriteToRequestBodyAsync(requestContent, requestData, requestContext.Request.Headers, requestContext.CancellationToken).ConfigureAwait(false);
}
else
{
System.IO.Stream originalStream;
if (wrappedRequest.ContentStream == null)
{
originalStream = new System.IO.MemoryStream();
await originalStream.WriteAsync(wrappedRequest.Content, 0, wrappedRequest.Content.Length, requestContext.CancellationToken).ConfigureAwait(false);
originalStream.Position = 0;
}
else
{
originalStream = wrappedRequest.ContentStream;
}
var callback = ((Amazon.Runtime.Internal.IAmazonWebServiceRequest)wrappedRequest.OriginalRequest).StreamUploadProgressCallback;
if (callback != null)
originalStream = httpRequest.SetupProgressListeners(originalStream, requestContext.ClientConfig.ProgressUpdateInterval, this.CallbackSender, callback);
var inputStream = GetInputStream(requestContext, originalStream, wrappedRequest);
await httpRequest.WriteToRequestBodyAsync(requestContent, inputStream,
requestContext.Request.Headers, requestContext).ConfigureAwait(false);
}
}
#endif
/// <summary>
/// Creates the HttpWebRequest and configures the end point, content, user agent and proxy settings.
/// </summary>
/// <param name="requestContext">The async request.</param>
/// <returns>The web request that actually makes the call.</returns>
protected virtual IHttpRequest<TRequestContent> CreateWebRequest(IRequestContext requestContext)
{
IRequest request = requestContext.Request;
Uri url = AmazonServiceClient.ComposeUrl(request);
var httpRequest = _requestFactory.CreateHttpRequest(url);
httpRequest.ConfigureRequest(requestContext);
httpRequest.Method = request.HttpMethod;
if (request.MayContainRequestBody())
{
var content = request.Content;
if (request.SetContentFromParameters || (content == null && request.ContentStream == null))
{
// Mapping parameters to query string or body are mutually exclusive.
if (!request.UseQueryString)
{
string queryString = AWSSDKUtils.GetParametersAsString(request);
content = Encoding.UTF8.GetBytes(queryString);
request.Content = content;
request.SetContentFromParameters = true;
}
else
{
request.Content = ArrayEx.Empty<byte>();
}
}
if (content != null)
{
request.Headers[HeaderKeys.ContentLengthHeader] =
content.Length.ToString(CultureInfo.InvariantCulture);
}
else if (request.ContentStream != null && request.ContentStream.CanSeek && !request.Headers.ContainsKey(HeaderKeys.ContentLengthHeader))
{
request.Headers[HeaderKeys.ContentLengthHeader] =
request.ContentStream.Length.ToString(CultureInfo.InvariantCulture);
}
}
return httpRequest;
}
/// <summary>
/// Disposes the HTTP handler.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_requestFactory != null)
_requestFactory.Dispose();
_disposed = true;
}
}
private static System.IO.Stream GetInputStream(IRequestContext requestContext, System.IO.Stream originalStream, IRequest wrappedRequest)
{
var requestHasConfigForChunkStream = wrappedRequest.UseChunkEncoding && (wrappedRequest.AWS4SignerResult != null || wrappedRequest.AWS4aSignerResult != null);
var hasTransferEncodingHeader = wrappedRequest.Headers.ContainsKey(HeaderKeys.TransferEncodingHeader);
var isTransferEncodingHeaderChunked = hasTransferEncodingHeader && wrappedRequest.Headers[HeaderKeys.TransferEncodingHeader] == "chunked";
var hasTrailingHeaders = wrappedRequest.TrailingHeaders?.Count > 0;
if (requestHasConfigForChunkStream || isTransferEncodingHeaderChunked)
{
AWSSigningResultBase signingResult;
if (wrappedRequest.AWS4aSignerResult != null)
{
signingResult = wrappedRequest.AWS4aSignerResult;
}
else
{
signingResult = wrappedRequest.AWS4SignerResult;
}
if (hasTrailingHeaders)
{
return new ChunkedUploadWrapperStream(originalStream,
requestContext.ClientConfig.BufferSize,
signingResult,
wrappedRequest.SelectedChecksum,
wrappedRequest.TrailingHeaders);
}
else // no trailing headers
{
return new ChunkedUploadWrapperStream(originalStream,
requestContext.ClientConfig.BufferSize,
signingResult);
}
}
else if (hasTrailingHeaders) // and is unsigned/unchunked
{
if (wrappedRequest.SelectedChecksum != CoreChecksumAlgorithm.NONE)
{
return new TrailingHeadersWrapperStream(originalStream, wrappedRequest.TrailingHeaders, wrappedRequest.SelectedChecksum);
}
else
{
return new TrailingHeadersWrapperStream(originalStream, wrappedRequest.TrailingHeaders);
}
}
else
{
return originalStream;
}
}
}
}
| 586 |
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.Transform;
using Amazon.Runtime.Internal.Util;
using System;
using System.Collections.Generic;
using System.IO;
namespace Amazon.Runtime
{
/// <summary>
/// The interface for a HTTP request factory.
/// </summary>
/// <typeparam name="TRequestContent">The type used by the underlying HTTP API to represent the request body.</typeparam>
public interface IHttpRequestFactory<TRequestContent> : IDisposable
{
/// <summary>
/// Creates an HTTP request for the given URI.
/// </summary>
/// <param name="requestUri">The request URI.</param>
/// <returns>An HTTP request.</returns>
IHttpRequest<TRequestContent> CreateHttpRequest(Uri requestUri);
}
/// <summary>
/// The interface for an HTTP request that is agnostic of the underlying HTTP API.
/// </summary>
/// <typeparam name="TRequestContent">The type used by the underlying HTTP API to represent the HTTP request content.</typeparam>
public interface IHttpRequest<TRequestContent> : IDisposable
{
/// <summary>
/// The HTTP method or verb.
/// </summary>
string Method { get; set; }
/// <summary>
/// The request URI.
/// </summary>
Uri RequestUri { get; }
/// <summary>
/// Configures a request as per the request context.
/// </summary>
/// <param name="requestContext">The request context.</param>
void ConfigureRequest(IRequestContext requestContext);
/// <summary>
/// Sets the headers on the request.
/// </summary>
/// <param name="headers">A dictionary of header names and values.</param>
void SetRequestHeaders(IDictionary<string, string> headers);
/// <summary>
/// Gets a handle to the request content.
/// </summary>
/// <returns>The request content.</returns>
TRequestContent GetRequestContent();
/// <summary>
/// Returns the HTTP response.
/// </summary>
/// <returns>The HTTP response.</returns>
IWebResponseData GetResponse();
/// <summary>
/// Writes a stream to the request body.
/// </summary>
/// <param name="requestContent">The destination where the content stream is written.</param>
/// <param name="contentStream">The content stream to be written.</param>
/// <param name="contentHeaders">HTTP content headers.</param>
/// <param name="requestContext">The request context.</param>
void WriteToRequestBody(TRequestContent requestContent, Stream contentStream, IDictionary<string,string> contentHeaders, IRequestContext requestContext);
/// <summary>
/// Writes a byte array to the request body.
/// </summary>
/// <param name="requestContent">The destination where the content stream is written.</param>
/// <param name="content">The content stream to be written.</param>
/// <param name="contentHeaders">HTTP content headers.</param>
void WriteToRequestBody(TRequestContent requestContent, byte[] content, IDictionary<string,string> contentHeaders);
/// <summary>
/// Sets up the progress listeners
/// </summary>
/// <param name="originalStream">The content stream</param>
/// <param name="progressUpdateInterval">The interval at which progress needs to be published</param>
/// <param name="sender">The objects which is trigerring the progress changes</param>
/// <param name="callback">The callback which will be invoked when the progress changed event is trigerred</param>
/// <returns>an <see cref="EventStream"/> object, incase the progress is setup, else returns the original stream</returns>
Stream SetupProgressListeners(Stream originalStream, long progressUpdateInterval, object sender, EventHandler<StreamTransferProgressArgs> callback);
/// <summary>
/// Aborts the HTTP request.
/// </summary>
void Abort();
#if AWS_ASYNC_API
/// <summary>
/// Gets a handle to the request content.
/// </summary>
/// <returns></returns>
System.Threading.Tasks.Task<TRequestContent> GetRequestContentAsync();
#if BCL45
System.Threading.Tasks.Task<TRequestContent> GetRequestContentAsync(System.Threading.CancellationToken cancellationToken);
#endif
/// <summary>
/// Returns the HTTP response.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
/// <returns></returns>
System.Threading.Tasks.Task<IWebResponseData> GetResponseAsync(System.Threading.CancellationToken cancellationToken);
#if BCL45
System.Threading.Tasks.Task WriteToRequestBodyAsync(TRequestContent requestContent, Stream contentStream, IDictionary<string, string> contentHeaders, IRequestContext requestContext);
System.Threading.Tasks.Task WriteToRequestBodyAsync(TRequestContent requestContent, byte[] requestData, IDictionary<string, string> headers, System.Threading.CancellationToken cancellationToken);
#endif
#elif AWS_APM_API
/// <summary>
/// Initiates the operation to gets a handle to the request content.
/// </summary>
/// <param name="callback">The async callback invoked when the operation completes.</param>
/// <param name="state">The state object to be passed to the async callback.</param>
/// <returns>IAsyncResult that represents an async operation.</returns>
IAsyncResult BeginGetRequestContent(AsyncCallback callback, object state);
/// <summary>
/// Ends the operation to gets a handle to the request content.
/// </summary>
/// <param name="asyncResult">IAsyncResult that represents an async operation.</param>
/// <returns>The request content.</returns>
TRequestContent EndGetRequestContent(IAsyncResult asyncResult);
/// <summary>
/// Initiates the operation to Returns the HTTP response.
/// </summary>
/// <param name="callback">The async callback invoked when the operation completes.</param>
/// <param name="state">The state object to be passed to the async callback.</param>
/// <returns>IAsyncResult that represents an async operation.</returns>
IAsyncResult BeginGetResponse(AsyncCallback callback, object state);
/// <summary>
/// Ends the operation to Returns the HTTP response.
/// </summary>
/// <param name="asyncResult">IAsyncResult that represents an async operation.</param>
/// <returns>The HTTP response.</returns>
IWebResponseData EndGetResponse(IAsyncResult asyncResult);
#endif
}
}
| 168 |
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.Transform;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
#if AWS_ASYNC_API
using System.Threading;
using System.Threading.Tasks;
#endif
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The request factory for System.Net.HttpWebRequest.
/// </summary>
public class HttpWebRequestFactory : IHttpRequestFactory<Stream>
{
/// <summary>
/// Creates an HTTP request for the given URI.
/// </summary>
/// <param name="requestUri">The request URI.</param>
/// <returns>An HTTP request.</returns>
public IHttpRequest<Stream> CreateHttpRequest(Uri requestUri)
{
return new HttpRequest(requestUri);
}
/// <summary>
/// Disposes the HttpWebRequestFactory.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
}
/// <summary>
/// HTTP request wrapper for System.Net.HttpWebRequest.
/// </summary>
public class HttpRequest : IHttpRequest<Stream>
{
private bool _isAborted = false;
private HttpWebRequest _request;
/// <summary>
/// Constructor for HttpRequest.
/// </summary>
/// <param name="requestUri">The request URI.</param>
public HttpRequest(Uri requestUri)
{
_request = WebRequest.Create(requestUri) as HttpWebRequest;
}
/// <summary>
/// The underlying HTTP web request.
/// </summary>
public HttpWebRequest Request
{
get { return _request; }
}
/// <summary>
/// The HTTP method or verb.
/// </summary>
public string Method
{
get { return _request.Method; }
set { _request.Method = value; }
}
/// <summary>
/// The request URI.
/// </summary>
public Uri RequestUri
{
get { return _request.RequestUri; }
}
/// <summary>
/// Returns the HTTP response.
/// </summary>
/// <returns>The HTTP response.</returns>
public virtual IWebResponseData GetResponse()
{
try
{
var response = _request.GetResponse() as HttpWebResponse;
return new HttpWebRequestResponseData(response);
}
catch (WebException webException)
{
var errorResponse = webException.Response as HttpWebResponse;
if (errorResponse != null)
{
throw new HttpErrorResponseException(webException.Message,
webException,
new HttpWebRequestResponseData(errorResponse));
}
throw;
}
}
/// <summary>
/// Gets a handle to the request content.
/// </summary>
/// <returns>The request content.</returns>
public Stream GetRequestContent()
{
return _request.GetRequestStream();
}
/// <summary>
/// Writes a stream to the request body.
/// </summary>
/// <param name="requestContent">The destination where the content stream is written.</param>
/// <param name="contentStream">The content stream to be written.</param>
/// <param name="contentHeaders">HTTP content headers.</param>
/// <param name="requestContext">The request context.</param>
public void WriteToRequestBody(Stream requestContent, Stream contentStream,
IDictionary<string, string> contentHeaders, IRequestContext requestContext)
{
bool gotException = false;
try
{
var buffer = new byte[requestContext.ClientConfig.BufferSize];
int bytesRead = 0;
int bytesToRead = buffer.Length;
while ((bytesRead = contentStream.Read(buffer, 0, bytesToRead)) > 0)
{
requestContent.Write(buffer, 0, bytesRead);
}
}
catch
{
gotException = true;
// If an exception occurred while reading the input stream,
// Abort the request to signal failure to the server and prevent
// potentially writing an incomplete stream to the server.
this.Abort();
throw;
}
finally
{
// Only bubble up exception from the close method if we haven't already got an exception
// reading and writing from the streams.
try
{
requestContent.Close();
}
catch
{
if (!gotException)
throw;
}
}
}
/// <summary>
/// Writes a byte array to the request body.
/// </summary>
/// <param name="requestContent">The destination where the content stream is written.</param>
/// <param name="content">The content stream to be written.</param>
/// <param name="contentHeaders">HTTP content headers.</param>
public void WriteToRequestBody(Stream requestContent, byte[] content, IDictionary<string, string> contentHeaders)
{
using (requestContent)
{
requestContent.Write(content, 0, content.Length);
}
}
/// <summary>
/// Aborts the HTTP request.
/// </summary>
public void Abort()
{
if (!_isAborted)
{
_request.Abort();
_isAborted = true;
}
}
#if AWS_ASYNC_API
/// <summary>
/// Writes a stream to the request body.
/// </summary>
/// <param name="requestContent">The destination where the content stream is written.</param>
/// <param name="contentStream">The content stream to be written.</param>
/// <param name="contentHeaders">HTTP content headers.</param>
/// <param name="requestContext">The request context.</param>
public async Task WriteToRequestBodyAsync(Stream requestContent, Stream contentStream,
IDictionary<string, string> contentHeaders, IRequestContext requestContext)
{
bool gotException = false;
try
{
var buffer = new byte[requestContext.ClientConfig.BufferSize];
int bytesRead = 0;
int bytesToRead = buffer.Length;
while ((bytesRead = await contentStream.ReadAsync(buffer, 0, bytesToRead, requestContext.CancellationToken).ConfigureAwait(false)) > 0)
{
requestContext.CancellationToken.ThrowIfCancellationRequested();
await requestContent.WriteAsync(buffer, 0, bytesRead, requestContext.CancellationToken).ConfigureAwait(false);
}
}
catch
{
gotException = true;
// If an exception occurred while reading the input stream,
// Abort the request to signal failure to the server and prevent
// potentially writing an incomplete stream to the server.
this.Abort();
throw;
}
finally
{
// Only bubble up exception from the close method if we haven't already got an exception
// reading and writing from the streams.
try
{
requestContent.Close();
}
catch
{
if (!gotException)
throw;
}
}
}
/// <summary>
/// Writes a byte array to the request body.
/// </summary>
/// <param name="requestContent">The destination where the content stream is written.</param>
/// <param name="content">The content stream to be written.</param>
/// <param name="contentHeaders">HTTP content headers.</param>
public async Task WriteToRequestBodyAsync(Stream requestContent, byte[] content, IDictionary<string, string> contentHeaders, CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
using (requestContent)
{
await requestContent.WriteAsync(content, 0, content.Length, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>
/// Gets a handle to the request content.
/// </summary>
/// <returns></returns>
public async Task<Stream> GetRequestContentAsync()
{
return await GetRequestContentAsync(CancellationToken.None).ConfigureAwait(false);
}
/// <summary>
/// Gets a handle to the request content.
/// </summary>
/// <param name="cancellationToken">Used to cancel the request on demand</param>
/// <returns></returns>
public async Task<Stream> GetRequestContentAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
using (cancellationToken.Register(() => this.Abort(), useSynchronizationContext:false))
{
try
{
return await _request.GetRequestStreamAsync().ConfigureAwait(false);
}
catch (WebException webException)
{
// After HttpWebRequest.Abort() is called, GetRequestStreamAsync throws a WebException.
// If request has been cancelled using cancellationToken, wrap the
// WebException in an OperationCancelledException.
if (cancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException(webException.Message, webException, cancellationToken);
}
var errorResponse = webException.Response as HttpWebResponse;
if (errorResponse != null)
{
throw new HttpErrorResponseException(webException.Message,
webException,
new HttpWebRequestResponseData(errorResponse));
}
throw;
}
}
}
/// <summary>
/// Returns the HTTP response.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
/// <returns></returns>
public virtual async Task<IWebResponseData> GetResponseAsync(System.Threading.CancellationToken cancellationToken)
{
using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
using (linkedTokenSource.Token.Register(() => this.Abort(), useSynchronizationContext: false))
{
linkedTokenSource.CancelAfter(_request.Timeout);
try
{
var response = await _request.GetResponseAsync().ConfigureAwait(false) as HttpWebResponse;
return new HttpWebRequestResponseData(response);
}
catch (WebException webException)
{
// After HttpWebRequest.Abort() is called, GetResponseAsync throws a WebException.
// If request has been cancelled using cancellationToken, wrap the
// WebException in an OperationCancelledException.
if (cancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException(webException.Message, webException, cancellationToken);
}
if (linkedTokenSource.Token.IsCancellationRequested)
{
throw new OperationCanceledException(webException.Message, webException, linkedTokenSource.Token);
}
var errorResponse = webException.Response as HttpWebResponse;
if (errorResponse != null)
{
throw new HttpErrorResponseException(webException.Message,
webException,
new HttpWebRequestResponseData(errorResponse));
}
throw;
}
}
}
#elif AWS_APM_API
/// <summary>
/// Initiates the operation to gets a handle to the request content.
/// </summary>
/// <param name="callback">The async callback invoked when the operation completes.</param>
/// <param name="state">The state object to be passed to the async callback.</param>
/// <returns>IAsyncResult that represents an async operation.</returns>
public IAsyncResult BeginGetRequestContent(AsyncCallback callback, object state)
{
return _request.BeginGetRequestStream(callback, state);
}
/// <summary>
/// Ends the operation to gets a handle to the request content.
/// </summary>
/// <param name="asyncResult">IAsyncResult that represents an async operation.</param>
/// <returns>The request content.</returns>
public Stream EndGetRequestContent(IAsyncResult asyncResult)
{
return _request.EndGetRequestStream(asyncResult);
}
/// <summary>
/// Initiates the operation to Returns the HTTP response.
/// </summary>
/// <param name="callback">The async callback invoked when the operation completes.</param>
/// <param name="state">The state object to be passed to the async callback.</param>
/// <returns>IAsyncResult that represents an async operation.</returns>
public IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
return _request.BeginGetResponse(callback, state);
}
/// <summary>
/// Ends the operation to Returns the HTTP response.
/// </summary>
/// <param name="asyncResult">IAsyncResult that represents an async operation.</param>
/// <returns>The HTTP response.</returns>
public virtual IWebResponseData EndGetResponse(IAsyncResult asyncResult)
{
try
{
var response = _request.EndGetResponse(asyncResult) as HttpWebResponse;
return new HttpWebRequestResponseData(response);
}
catch (WebException webException)
{
var errorResponse = webException.Response as HttpWebResponse;
if (errorResponse != null)
{
throw new HttpErrorResponseException(webException.Message,
webException,
new HttpWebRequestResponseData(errorResponse));
}
throw;
}
}
#endif
/// <summary>
/// Configures a request as per the request context.
/// </summary>
/// <param name="requestContext">The request context.</param>
public virtual void ConfigureRequest(IRequestContext requestContext)
{
// Set HttpWebRequest specific properties which are
// not exposed in the IHttpRequest interface.
var clientConfig = requestContext.ClientConfig;
var originalRequest = requestContext.OriginalRequest;
// If System.Net.WebRequest.AllowAutoRedirect is set to true (default value),
// redirects for GET requests are automatically followed and redirects for POST
// requests are thrown back as exceptions.
// If System.Net.WebRequest.AllowAutoRedirect is set to false (e.g. S3),
// redirects are returned as responses.
_request.AllowAutoRedirect = clientConfig.AllowAutoRedirect;
// Configure timeouts.
if (requestContext.Request.ContentStream != null)
{
_request.Timeout = int.MaxValue;
_request.ReadWriteTimeout = int.MaxValue;
_request.AllowWriteStreamBuffering = false;
}
// Override the Timeout and ReadWriteTimeout values if set at the request or config level.
// Public Timeout and ReadWriteTimeout properties are present on client config objects.
var timeout = ClientConfig.GetTimeoutValue(clientConfig.Timeout, originalRequest.TimeoutInternal);
var readWriteTimeout = ClientConfig.GetTimeoutValue(clientConfig.ReadWriteTimeout, originalRequest.ReadWriteTimeoutInternal);
if (timeout != null)
{
_request.Timeout = (int)timeout.Value.TotalMilliseconds;
}
if (readWriteTimeout != null)
{
_request.ReadWriteTimeout = (int)readWriteTimeout.Value.TotalMilliseconds;
}
// Set proxy related properties
IWebProxy proxy = requestContext.ClientConfig.GetWebProxy();
if (proxy != null)
{
requestContext.Metrics.AddProperty(Metric.ProxyHost, requestContext.ClientConfig.ProxyHost);
requestContext.Metrics.AddProperty(Metric.ProxyPort, requestContext.ClientConfig.ProxyPort);
_request.Proxy = proxy;
}
// Set service point properties.
_request.ServicePoint.ConnectionLimit = clientConfig.ConnectionLimit;
_request.ServicePoint.UseNagleAlgorithm = clientConfig.UseNagleAlgorithm;
_request.ServicePoint.MaxIdleTime = clientConfig.MaxIdleTime;
_request.ServicePoint.Expect100Continue = originalRequest.GetExpect100Continue();
var tcpKeepAlive = clientConfig.TcpKeepAlive;
_request.ServicePoint.SetTcpKeepAlive(
tcpKeepAlive.Enabled,
(int) tcpKeepAlive.Timeout.Value.TotalMilliseconds,
(int) tcpKeepAlive.Interval.Value.TotalMilliseconds);
}
/// <summary>
/// Sets the headers on the request.
/// </summary>
/// <param name="headers">A dictionary of header names and values.</param>
public void SetRequestHeaders(IDictionary<string, string> headers)
{
AddHeaders(_request, headers);
}
private static System.Reflection.MethodInfo _addWithoutValidateHeadersMethod =
typeof(WebHeaderCollection).GetMethod("AddWithoutValidate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
// As per MSDN documentation (http://msdn.microsoft.com/en-us/library/system.net.webheadercollection%28v=VS.80%29.aspx)
// some headers are restricted, cannot be set through the request.Headers property and must be
// set through properties on the HttpWebRequest
internal static void AddHeaders(HttpWebRequest request, IDictionary<string, string> headersToAdd)
{
var headers = request.Headers;
foreach (var kvp in headersToAdd)
{
if (WebHeaderCollection.IsRestricted(kvp.Key) || string.Equals(kvp.Key, HeaderKeys.RangeHeader, StringComparison.OrdinalIgnoreCase))
{
if (string.Equals(kvp.Key, HeaderKeys.AcceptHeader, StringComparison.OrdinalIgnoreCase))
request.Accept = kvp.Value;
else if (string.Equals(kvp.Key, HeaderKeys.ContentTypeHeader, StringComparison.OrdinalIgnoreCase))
request.ContentType = kvp.Value;
else if (string.Equals(kvp.Key, HeaderKeys.ContentLengthHeader, StringComparison.OrdinalIgnoreCase))
request.ContentLength = long.Parse(kvp.Value, CultureInfo.InvariantCulture);
else if (string.Equals(kvp.Key, HeaderKeys.UserAgentHeader, StringComparison.OrdinalIgnoreCase))
request.UserAgent = kvp.Value;
else if (string.Equals(kvp.Key, HeaderKeys.TransferEncodingHeader, StringComparison.OrdinalIgnoreCase)
&& string.Equals(kvp.Value, "chunked", StringComparison.OrdinalIgnoreCase))
request.SendChunked = true;
// Date accessor is only present in .NET 4.0, so using reflection
else if (string.Equals(kvp.Key, HeaderKeys.DateHeader, StringComparison.OrdinalIgnoreCase))
_addWithoutValidateHeadersMethod.Invoke(request.Headers, new[] { HeaderKeys.DateHeader, kvp.Value });
// Host accessor is only present in .NET 4.0, so using reflection
else if (string.Equals(kvp.Key, HeaderKeys.HostHeader, StringComparison.OrdinalIgnoreCase))
_addWithoutValidateHeadersMethod.Invoke(request.Headers, new[] { HeaderKeys.HostHeader, kvp.Value });
else if (string.Equals(kvp.Key, HeaderKeys.RangeHeader, StringComparison.OrdinalIgnoreCase))
_addWithoutValidateHeadersMethod.Invoke(request.Headers, new[] { HeaderKeys.RangeHeader, kvp.Value });
else if (string.Equals(kvp.Key, HeaderKeys.IfModifiedSinceHeader, StringComparison.OrdinalIgnoreCase))
_addWithoutValidateHeadersMethod.Invoke(request.Headers, new[] { kvp.Key, kvp.Value });
else
throw new NotSupportedException("Header with name " + kvp.Key + " is not supported");
}
else
{
headers[kvp.Key] = kvp.Value;
}
}
}
/// <summary>
/// Disposes the HttpRequest.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// NOP since HttWebRequest does not implement IDisposable.
}
/// <summary>
/// Sets up the progress listeners
/// </summary>
/// <param name="originalStream">The content stream</param>
/// <param name="progressUpdateInterval">The interval at which progress needs to be published</param>
/// <param name="sender">The objects which is trigerring the progress changes</param>
/// <param name="callback">The callback which will be invoked when the progress changed event is trigerred</param>
/// <returns>an <see cref="EventStream"/> object, incase the progress is setup, else returns the original stream</returns>
public Stream SetupProgressListeners(Stream originalStream, long progressUpdateInterval, object sender, EventHandler<StreamTransferProgressArgs> callback)
{
var eventStream = new EventStream(originalStream, true);
var tracker = new StreamReadTracker(sender, callback, originalStream.Length,
progressUpdateInterval);
eventStream.OnRead += tracker.ReadProgress;
return eventStream;
}
}
}
| 576 |
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 Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Amazon.Runtime
{
/// <summary>
/// A factory which creates HTTP clients.
/// </summary>
[CLSCompliant(false)]
public abstract class HttpClientFactory
{
/// <summary>
/// Create and configure an HttpClient.
/// </summary>
/// <returns></returns>
public abstract HttpClient CreateHttpClient(IClientConfig clientConfig);
/// <summary>
/// If true the SDK will internally cache the clients created by CreateHttpClient.
/// If false the sdk will not cache the clients.
/// Override this method to return false if your HttpClientFactory will handle its own caching
/// or if you don't want clients to be cached.
/// </summary>
/// <param name="clientConfig"></param>
/// <returns></returns>
public virtual bool UseSDKHttpClientCaching(IClientConfig clientConfig)
{
return clientConfig.CacheHttpClient;
}
/// <summary>
/// Determines if the SDK will dispose clients after they're used.
/// If HttpClients are cached, either by the SDK or by your HttpClientFactory, this should be false.
/// If there is no caching then this should be true.
/// </summary>
/// <param name="clientConfig"></param>
/// <returns></returns>
public virtual bool DisposeHttpClientsAfterUse(IClientConfig clientConfig)
{
return !UseSDKHttpClientCaching(clientConfig);
}
/// <summary>
/// Returns a string that's used to group equivalent HttpClients into caches.
/// This method isn't used unless UseSDKHttpClientCaching returns true;
///
/// A null return value signals the SDK caching mechanism to cache HttpClients per SDK client.
/// So when the SDK client is disposed, the HttpClients are as well.
///
/// A non-null return value signals the SDK that HttpClients created with the given clientConfig
/// should be cached and reused globally. ClientConfigs that produce the same result for
/// GetConfigUniqueString will be grouped together and considered equivalent for caching purposes.
/// </summary>
/// <param name="clientConfig"></param>
/// <returns></returns>
public virtual string GetConfigUniqueString(IClientConfig clientConfig)
{
return null;
}
}
/// <summary>
/// A factory which creates HTTP requests which uses System.Net.Http.HttpClient.
/// </summary>
[CLSCompliant(false)]
public class HttpRequestMessageFactory : IHttpRequestFactory<HttpContent>
{
// This is the global cache of HttpClient for service clients that are using
static readonly ReaderWriterLockSlim _httpClientCacheRWLock = new ReaderWriterLockSlim();
static readonly IDictionary<string, HttpClientCache> _httpClientCaches = new Dictionary<string, HttpClientCache>();
private HttpClientCache _httpClientCache;
private bool _useGlobalHttpClientCache;
private IClientConfig _clientConfig;
/// <summary>
/// The constructor for HttpRequestMessageFactory.
/// </summary>
/// <param name="clientConfig">Configuration setting for a client.</param>
public HttpRequestMessageFactory(IClientConfig clientConfig)
{
_clientConfig = clientConfig;
}
/// <summary>
/// Creates an HTTP request for the given URI.
/// </summary>
/// <param name="requestUri">The request URI.</param>
/// <returns>An HTTP request.</returns>
public IHttpRequest<HttpContent> CreateHttpRequest(Uri requestUri)
{
HttpClient httpClient = null;
if(ClientConfig.CacheHttpClients(_clientConfig))
{
if(_httpClientCache == null)
{
if (!ClientConfig.UseGlobalHttpClientCache(_clientConfig))
{
_useGlobalHttpClientCache = false;
_httpClientCacheRWLock.EnterWriteLock();
try
{
if (_httpClientCache == null)
{
_httpClientCache = CreateHttpClientCache(_clientConfig);
}
}
finally
{
_httpClientCacheRWLock.ExitWriteLock();
}
}
else
{
_useGlobalHttpClientCache = true;
// Check to see if an HttpClient was created by another service client with the
// same settings on the ClientConfig.
var configUniqueString = ClientConfig.CreateConfigUniqueString(_clientConfig);
_httpClientCacheRWLock.EnterReadLock();
try
{
_httpClientCaches.TryGetValue(configUniqueString, out _httpClientCache);
}
finally
{
_httpClientCacheRWLock.ExitReadLock();
}
// If a HttpClientCache is not found in the global cache then create one
// for this and other service clients to use.
if (_httpClientCache == null)
{
_httpClientCacheRWLock.EnterWriteLock();
try
{
// Check if the HttpClientCache was created by some other thread
// while this thread was waiting for the lock.
if (!_httpClientCaches.TryGetValue(configUniqueString, out _httpClientCache))
{
_httpClientCache = CreateHttpClientCache(_clientConfig);
_httpClientCaches[configUniqueString] = _httpClientCache;
}
}
finally
{
_httpClientCacheRWLock.ExitWriteLock();
}
}
}
}
// Now that we have a HttpClientCache from either the global cache or just created a new HttpClientCache
// get the next HttpClient to be used for making a web request.
httpClient = _httpClientCache.GetNextClient();
}
else
{
httpClient = CreateHttpClient(_clientConfig);
}
return new HttpWebRequestMessage(httpClient, requestUri, _clientConfig);
}
/// <summary>
/// Disposes the HttpRequestMessageFactory.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose the factory
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// if the http cache is local to this instance then dispose it
if (!_useGlobalHttpClientCache && _httpClientCache != null)
{
_httpClientCache.Dispose();
}
}
}
private static HttpClientCache CreateHttpClientCache(IClientConfig clientConfig)
{
var clients = new HttpClient[clientConfig.HttpClientCacheSize];
for(int i = 0; i < clients.Length; i++)
{
clients[i] = CreateHttpClient(clientConfig);
}
var cache = new HttpClientCache(clients);
return cache;
}
private static HttpClient CreateHttpClient(IClientConfig clientConfig)
{
if (clientConfig.HttpClientFactory == null)
{
return CreateManagedHttpClient(clientConfig);
}
else
{
return clientConfig.HttpClientFactory.CreateHttpClient(clientConfig);
}
}
/// <summary>
/// Create and configure a managed HttpClient instance.
/// The use of HttpClientHandler in the constructor for HttpClient implicitly creates a managed HttpClient.
/// </summary>
/// <param name="clientConfig"></param>
/// <returns></returns>
private static HttpClient CreateManagedHttpClient(IClientConfig clientConfig)
{
var httpMessageHandler = new HttpClientHandler();
if (clientConfig.MaxConnectionsPerServer.HasValue)
httpMessageHandler.MaxConnectionsPerServer = clientConfig.MaxConnectionsPerServer.Value;
try
{
// If HttpClientHandler.AllowAutoRedirect is set to true (default value),
// redirects for GET requests are automatically followed and redirects for POST
// requests are thrown back as exceptions.
// If HttpClientHandler.AllowAutoRedirect is set to false (e.g. S3),
// redirects are returned as responses.
httpMessageHandler.AllowAutoRedirect = clientConfig.AllowAutoRedirect;
// Disable automatic decompression when Content-Encoding header is present
httpMessageHandler.AutomaticDecompression = DecompressionMethods.None;
}
catch (PlatformNotSupportedException pns)
{
Logger.GetLogger(typeof(HttpRequestMessageFactory)).Debug(pns, $"The current runtime does not support modifying the configuration of HttpClient.");
}
try
{
var proxy = clientConfig.GetWebProxy();
if (proxy != null)
{
httpMessageHandler.Proxy = proxy;
}
if (httpMessageHandler.Proxy != null && clientConfig.ProxyCredentials != null)
{
httpMessageHandler.Proxy.Credentials = clientConfig.ProxyCredentials;
}
}
catch (PlatformNotSupportedException pns)
{
Logger.GetLogger(typeof(HttpRequestMessageFactory)).Debug(pns, $"The current runtime does not support modifying proxy settings of HttpClient.");
}
var httpClient = new HttpClient(httpMessageHandler);
if (clientConfig.Timeout.HasValue)
{
// Timeout value is set to ClientConfig.MaxTimeout for S3 and Glacier.
// Use default value (100 seconds) for other services.
httpClient.Timeout = clientConfig.Timeout.Value;
}
return httpClient;
}
}
/// <summary>
/// A cache of HttpClient objects. The GetNextClient method does a round robin cycle through the clients
/// to distribute the load even across.
/// </summary>
public class HttpClientCache : IDisposable
{
HttpClient[] _clients;
/// <summary>
/// Constructs a container for a cache of HttpClient objects
/// </summary>
/// <param name="clients">The HttpClient to cache</param>
public HttpClientCache(HttpClient[] clients)
{
_clients = clients;
}
private int count = 0;
/// <summary>
/// Returns the next HttpClient using a round robin rotation. It is expected that individual clients will be used
/// by more then one Thread.
/// </summary>
/// <returns></returns>
public HttpClient GetNextClient()
{
if (_clients.Length == 1)
{
return _clients[0];
}
else
{
int next = Interlocked.Increment(ref count);
int nextIndex = Math.Abs(next % _clients.Length);
return _clients[nextIndex];
}
}
/// <summary>
/// Disposes the HttpClientCache.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose the HttpClientCache
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_clients != null)
{
foreach (var client in _clients)
{
client.Dispose();
}
}
}
}
}
/// <summary>
/// HTTP request wrapper for System.Net.Http.HttpRequestMessage.
/// </summary>
[CLSCompliant(false)]
public class HttpWebRequestMessage : IHttpRequest<HttpContent>
{
/// <summary>
/// Set of content header names.
/// </summary>
private static HashSet<string> ContentHeaderNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
HeaderKeys.ContentLengthHeader,
HeaderKeys.ContentTypeHeader,
HeaderKeys.ContentRangeHeader,
HeaderKeys.ContentMD5Header,
HeaderKeys.ContentEncodingHeader,
HeaderKeys.ContentDispositionHeader,
HeaderKeys.Expires
};
private bool _disposed;
private HttpRequestMessage _request;
private HttpClient _httpClient;
private IClientConfig _clientConfig;
/// <summary>
/// The constructor for HttpWebRequestMessage.
/// </summary>
/// <param name="httpClient">The HttpClient used to make the request.</param>
/// <param name="requestUri">The request URI.</param>
/// <param name="config">The service client config.</param>
public HttpWebRequestMessage(HttpClient httpClient, Uri requestUri, IClientConfig config)
{
_clientConfig = config;
_httpClient = httpClient;
_request = new HttpRequestMessage();
_request.RequestUri = requestUri;
}
/// <summary>
/// The underlying HttpClient
/// </summary>
public HttpClient HttpClient
{
get { return _httpClient; }
}
/// <summary>
/// The underlying HTTP web request.
/// </summary>
public HttpRequestMessage Request
{
get { return _request; }
}
/// <summary>
/// The HTTP method or verb.
/// </summary>
public string Method
{
get { return _request.Method.Method; }
set { _request.Method = new HttpMethod(value); }
}
/// <summary>
/// The request URI.
/// </summary>
public Uri RequestUri
{
get { return _request.RequestUri; }
}
/// <summary>
/// Configures a request as per the request context.
/// </summary>
/// <param name="requestContext">The request context.</param>
public void ConfigureRequest(IRequestContext requestContext)
{
// Configure the Expect 100-continue header
if (requestContext != null && requestContext.OriginalRequest != null)
{
_request.Headers.ExpectContinue = requestContext.OriginalRequest.GetExpect100Continue();
}
}
/// <summary>
/// Sets the headers on the request.
/// </summary>
/// <param name="headers">A dictionary of header names and values.</param>
public void SetRequestHeaders(IDictionary<string, string> headers)
{
foreach (var kvp in headers)
{
if (ContentHeaderNames.Contains(kvp.Key))
continue;
_request.Headers.TryAddWithoutValidation(kvp.Key, kvp.Value);
}
}
/// <summary>
/// Gets a handle to the request content.
/// </summary>
/// <returns>The request content.</returns>
#pragma warning disable CA1024
public HttpContent GetRequestContent()
{
return _request.Content;
}
#pragma warning restore CA1024
/// <summary>
/// Returns the HTTP response.
/// </summary>
/// <returns>The HTTP response.</returns>
public IWebResponseData GetResponse()
{
try
{
return this.GetResponseAsync(System.Threading.CancellationToken.None).Result;
}
catch (AggregateException e)
{
throw e.InnerException;
}
}
/// <summary>
/// Aborts the HTTP request.
/// </summary>
public void Abort()
{
// NOP since HttRequestMessage does not have an Abort operation.
}
/// <summary>
/// Returns the HTTP response.
/// </summary>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
/// <returns></returns>
public async System.Threading.Tasks.Task<IWebResponseData> GetResponseAsync(System.Threading.CancellationToken cancellationToken)
{
try
{
var responseMessage = await _httpClient.SendAsync(_request, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
.ConfigureAwait(continueOnCapturedContext: false);
bool disposeClient = ClientConfig.DisposeHttpClients(_clientConfig);
// If AllowAutoRedirect is set to false, HTTP 3xx responses are returned back as response.
if (!_clientConfig.AllowAutoRedirect &&
responseMessage.StatusCode >= HttpStatusCode.Ambiguous &&
responseMessage.StatusCode < HttpStatusCode.BadRequest)
{
return new HttpClientResponseData(responseMessage, _httpClient, disposeClient);
}
if (!responseMessage.IsSuccessStatusCode)
{
// For all responses other than HTTP 2xx, return an exception.
throw new Amazon.Runtime.Internal.HttpErrorResponseException(
new HttpClientResponseData(responseMessage, _httpClient, disposeClient));
}
return new HttpClientResponseData(responseMessage, _httpClient, disposeClient);
}
catch (HttpRequestException httpException)
{
if (httpException.InnerException != null)
{
if (httpException.InnerException is IOException)
{
throw httpException.InnerException;
}
#if !NETSTANDARD
if (httpException.InnerException is WebException)
throw httpException.InnerException;
#endif
}
throw;
}
catch (OperationCanceledException canceledException)
{
if (!cancellationToken.IsCancellationRequested)
{
//OperationCanceledException thrown by HttpClient not the CancellationToken supplied by the user.
//This exception can wrap at least IOExceptions, ObjectDisposedExceptions and should be retried.
//Throw the underlying exception if it exists.
if(canceledException.InnerException != null)
{
throw canceledException.InnerException;
}
}
throw;
}
}
/// <summary>
/// Writes a stream to the request body.
/// </summary>
/// <param name="requestContent">The destination where the content stream is written.</param>
/// <param name="contentStream">The content stream to be written.</param>
/// <param name="contentHeaders">HTTP content headers.</param>
/// <param name="requestContext">The request context.</param>
public void WriteToRequestBody(HttpContent requestContent, Stream contentStream,
IDictionary<string, string> contentHeaders, IRequestContext requestContext)
{
var wrapperStream = new Amazon.Runtime.Internal.Util.NonDisposingWrapperStream(contentStream);
_request.Content = new StreamContent(wrapperStream, requestContext.ClientConfig.BufferSize);
var chunkedUploadWrapperStream = (contentStream as ChunkedUploadWrapperStream);
var trailingHeadersWrapperStream = (contentStream as TrailingHeadersWrapperStream);
if ((chunkedUploadWrapperStream == null && trailingHeadersWrapperStream == null) ||
(chunkedUploadWrapperStream != null && chunkedUploadWrapperStream.HasLength) ||
(trailingHeadersWrapperStream != null && trailingHeadersWrapperStream.HasLength))
{
_request.Content.Headers.ContentLength = contentStream.Length;
}
WriteContentHeaders(contentHeaders);
}
/// <summary>
/// Writes a byte array to the request body.
/// </summary>
/// <param name="requestContent">The destination where the content stream is written.</param>
/// <param name="content">The content stream to be written.</param>
/// <param name="contentHeaders">HTTP content headers.</param>
public void WriteToRequestBody(HttpContent requestContent,
byte[] content, IDictionary<string, string> contentHeaders)
{
_request.Content = new ByteArrayContent(content);
_request.Content.Headers.ContentLength = content.Length;
WriteContentHeaders(contentHeaders);
}
/// <summary>
/// Gets a handle to the request content.
/// </summary>
/// <returns></returns>
public System.Threading.Tasks.Task<HttpContent> GetRequestContentAsync()
{
return System.Threading.Tasks.Task.FromResult(_request.Content);
}
private void WriteContentHeaders(IDictionary<string, string> contentHeaders)
{
_request.Content.Headers.ContentType =
MediaTypeHeaderValue.Parse(contentHeaders[HeaderKeys.ContentTypeHeader]);
if (contentHeaders.TryGetValue(HeaderKeys.ContentRangeHeader, out var contentRangeHeader))
_request.Content.Headers.TryAddWithoutValidation(HeaderKeys.ContentRangeHeader,
contentRangeHeader);
if (contentHeaders.TryGetValue(HeaderKeys.ContentMD5Header, out var contentMd5Header))
_request.Content.Headers.TryAddWithoutValidation(HeaderKeys.ContentMD5Header,
contentMd5Header);
if (contentHeaders.TryGetValue(HeaderKeys.ContentEncodingHeader, out var contentEncodingHeader))
_request.Content.Headers.TryAddWithoutValidation(HeaderKeys.ContentEncodingHeader,
contentEncodingHeader);
if (contentHeaders.TryGetValue(HeaderKeys.ContentDispositionHeader, out var contentDispositionHeader))
_request.Content.Headers.TryAddWithoutValidation(HeaderKeys.ContentDispositionHeader,
contentDispositionHeader);
if (contentHeaders.TryGetValue(HeaderKeys.Expires, out var expiresHeaderValue) &&
DateTime.TryParse(expiresHeaderValue, CultureInfo.InvariantCulture, DateTimeStyles.None, out var expires))
_request.Content.Headers.Expires = expires;
}
/// <summary>
/// Disposes the HttpWebRequestMessage.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
///
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_request != null)
_request.Dispose();
_disposed = true;
}
}
/// <summary>
/// Sets up the progress listeners
/// </summary>
/// <param name="originalStream">The content stream</param>
/// <param name="progressUpdateInterval">The interval at which progress needs to be published</param>
/// <param name="sender">The objects which is triggering the progress changes</param>
/// <param name="callback">The callback which will be invoked when the progress changed event is triggered</param>
/// <returns>an <see cref="EventStream"/> object, incase the progress is setup, else returns the original stream</returns>
public Stream SetupProgressListeners(Stream originalStream, long progressUpdateInterval, object sender, EventHandler<StreamTransferProgressArgs> callback)
{
var eventStream = new EventStream(originalStream, true);
var tracker = new StreamReadTracker(sender, callback, originalStream.Length,
progressUpdateInterval);
eventStream.OnRead += tracker.ReadProgress;
return eventStream;
}
}
}
| 690 |
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;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The default implementation of the adaptive retry policy.
/// </summary>
public partial class AdaptiveRetryPolicy : StandardRetryPolicy
{
protected TokenBucket TokenBucket { get; set; } = new TokenBucket();
/// <summary>
/// Constructor for AdaptiveRetryPolicy.
/// </summary>
/// <param name="maxRetries">The maximum number of retries before throwing
/// back a exception. This does not count the initial request.</param>
public AdaptiveRetryPolicy(int maxRetries) : base(maxRetries)
{
}
/// <summary>
/// Constructor for AdaptiveRetryPolicy.
/// </summary>
/// <param name="config">The Client config object. This is used to
/// retrieve the maximum number of retries before throwing
/// back a exception(This does not count the initial request) and
/// the service URL for the request.</param>
public AdaptiveRetryPolicy(IClientConfig config) : base(config)
{
}
/// <summary>
/// OnRetry is called when a retry request is initiated to determine if the request will be retried.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="bypassAcquireCapacity">true to bypass any attempt to acquire capacity on a retry</param>
/// <param name="isThrottlingError">true if the error that will be retried is a throtting error</param>
/// <returns>True if retry throttling is disabled or retry throttling is enabled and capacity can be obtained.</returns>
public override bool OnRetry(IExecutionContext executionContext, bool bypassAcquireCapacity, bool isThrottlingError)
{
TokenBucket.UpdateClientSendingRate(isThrottlingError);
return base.OnRetry(executionContext, bypassAcquireCapacity, isThrottlingError);
}
/// <summary>
/// This method uses a token bucket to enforce the maximum sending rate.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="exception">If the prior request failed, this exception is expected to be
/// the exception that occurred during the prior request failure.</param>
public override void ObtainSendToken(IExecutionContext executionContext, Exception exception)
{
if (!TokenBucket.TryAcquireToken(1, executionContext.RequestContext.ClientConfig.FastFailRequests))
{
var whyFail = exception == null ? "The initial request cannot be attempted because capacity could not be obtained"
: "While attempting to retry a request error capacity could not be obtained";
if (executionContext.RequestContext.ClientConfig.FastFailRequests)
{
throw new AmazonClientException($"{whyFail}. The client is configured to fail fast and there is insufficent capacity to attempt the request.", exception);
}
//Else we were unable to obtain capacity after looping.
throw new AmazonClientException($"{whyFail}. There is insufficent capacity to attempt the request after attempting to obtain capacity multiple times.", exception);
}
}
/// <summary>
/// Virtual method that gets called on a success Response. If its a retry success response, the entire
/// retry acquired capacity is released(default is 5). If its just a success response a lesser value capacity
/// is released(default is 1).
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
public override void NotifySuccess(IExecutionContext executionContext)
{
TokenBucket.UpdateClientSendingRate(false);
base.NotifySuccess(executionContext);
}
}
}
| 104 |
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;
using AWSSDK.Runtime.Internal.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The default implementation of the legacy retry policy.
/// </summary>
public partial class DefaultRetryPolicy : RetryPolicy
{
//The status code returned from a service request when an invalid endpoint is used.
private const int INVALID_ENDPOINT_EXCEPTION_STATUSCODE = 421;
//Holds on to the singleton instance.
private static readonly CapacityManager _capacityManagerInstance = new CapacityManager(throttleRetryCount: 100, throttleRetryCost: 5, throttleCost: 1);
private static readonly HashSet<string> _netStandardRetryErrorMessages = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"The server returned an invalid or unrecognized response",
"The connection with the server was terminated abnormally",
"An error occurred while sending the request.",
"Failed sending data to the peer"
};
/// <summary>
/// The maximum value of exponential backoff in milliseconds, which will be used to wait
/// before retrying a request. The default is 30000 milliseconds.
/// </summary>
public int MaxBackoffInMilliseconds { get; set; } = 30000;
/// <summary>
/// Constructor for DefaultRetryPolicy.
/// </summary>
/// <param name="maxRetries">The maximum number of retries before throwing
/// back a exception. This does not count the initial request.</param>
public DefaultRetryPolicy(int maxRetries)
{
this.MaxRetries = maxRetries;
}
/// <summary>
/// Constructor for DefaultRetryPolicy.
/// </summary>
/// <param name="config">The Client config object. This is used to
/// retrieve the maximum number of retries before throwing
/// back a exception(This does not count the initial request) and
/// the service URL for the request.</param>
public DefaultRetryPolicy(IClientConfig config)
{
this.MaxRetries = config.MaxErrorRetry;
if (config.ThrottleRetries)
{
RetryCapacity = _capacityManagerInstance.GetRetryCapacity(GetRetryCapacityKey(config));
}
}
/// <summary>
/// Returns true if the request is in a state where it can be retried, else false.
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
/// <returns>Returns true if the request is in a state where it can be retried, else false.</returns>
public override bool CanRetry(IExecutionContext executionContext)
{
return executionContext.RequestContext.Request.IsRequestStreamRewindable();
}
/// <summary>
/// Return true if the request should be retried.
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
/// <param name="exception">The exception thrown by the previous request.</param>
/// <returns>Return true if the request should be retried.</returns>
public override bool RetryForException(IExecutionContext executionContext, Exception exception)
{
return RetryForExceptionSync(exception, executionContext);
}
/// <summary>
/// Virtual method that gets called when a retry request is initiated. If retry throttling is
/// enabled, the value returned is true if the required capacity is retured, false otherwise.
/// If retry throttling is disabled, true is returned.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override bool OnRetry(IExecutionContext executionContext)
{
return OnRetry(executionContext, false, false);
}
/// <summary>
/// Virtual method that gets called when a retry request is initiated. If retry throttling is
/// enabled, the value returned is true if the required capacity is retured, false otherwise.
/// If retry throttling is disabled, true is returned.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="bypassAcquireCapacity">true to bypass any attempt to acquire capacity on a retry</param>
public override bool OnRetry(IExecutionContext executionContext, bool bypassAcquireCapacity)
{
return OnRetry(executionContext, bypassAcquireCapacity, false);
}
/// <summary>
/// Virtual method that gets called when a retry request is initiated. If retry throttling is
/// enabled, the value returned is true if the required capacity is retured, false otherwise.
/// If retry throttling is disabled, true is returned.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="bypassAcquireCapacity">true to bypass any attempt to acquire capacity on a retry</param>
/// <param name="isThrottlingError">true if the error that will be retried is a throtting error</param>
public override bool OnRetry(IExecutionContext executionContext, bool bypassAcquireCapacity, bool isThrottlingError)
{
if (!bypassAcquireCapacity && executionContext.RequestContext.ClientConfig.ThrottleRetries && RetryCapacity != null)
{
return _capacityManagerInstance.TryAcquireCapacity(RetryCapacity, executionContext.RequestContext.LastCapacityType);
}
return true;
}
/// <summary>
/// Virtual method that gets called on a success Response. If its a retry success response, the entire
/// retry acquired capacity is released(default is 5). If its just a success response a lesser value capacity
/// is released(default is 1).
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
public override void NotifySuccess(IExecutionContext executionContext)
{
if(executionContext.RequestContext.ClientConfig.ThrottleRetries && RetryCapacity != null)
{
_capacityManagerInstance.ReleaseCapacity(executionContext.RequestContext.LastCapacityType, RetryCapacity);
}
}
/// <summary>
/// Perform the processor-bound portion of the RetryForException logic.
/// This is shared by the sync, async, and APM versions of the RetryForException method.
/// </summary>
/// <param name="exception">The exception thrown by the previous request.</param>
/// <returns>Return true if the request should be retried.</returns>
private bool RetryForExceptionSync(Exception exception)
{
return RetryForExceptionSync(exception, null);
}
/// <summary>
/// Perform the processor-bound portion of the RetryForException logic.
/// This is shared by the sync, async, and APM versions of the RetryForException method.
/// </summary>
/// <param name="exception">The exception thrown by the previous request.</param>
/// <param name="executionContext">Request context containing the state of the request.</param>
/// <returns>Return true if the request should be retried.</returns>
private bool RetryForExceptionSync(Exception exception, IExecutionContext executionContext)
{
// AmazonServiceException is thrown by ErrorHandler if it is this type of exception.
var serviceException = exception as AmazonServiceException;
// To try and smooth out an occasional throttling error, we'll pause and
// retry, hoping that the pause is long enough for the request to get through
// the next time. Only the error code should be used to determine if an
// error is a throttling error.
if (IsThrottlingError(exception))
{
return true;
}
// Check for transient errors, but we need to use
// an exponential back-off strategy so that we don't overload
// a server with a flood of retries. If we've surpassed our
// retry limit we handle the error response as a non-retryable
// error and go ahead and throw it back to the user as an exception.
if (IsTransientError(executionContext, exception) || IsServiceTimeoutError(exception))
{
return true;
}
//Check for Invalid Endpoint Exception indicating that the Endpoint Discovery
//endpoint used was invalid for the request. One retry attempt is allowed for this
//type of exception.
if (serviceException?.StatusCode == (HttpStatusCode)INVALID_ENDPOINT_EXCEPTION_STATUSCODE)
{
if (executionContext.RequestContext.EndpointDiscoveryRetries < 1)
{
executionContext.RequestContext.EndpointDiscoveryRetries++;
return true;
}
return false;
}
return false;
}
/// <summary>
/// Checks if the retry limit is reached.
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
/// <returns>Return false if the request can be retried, based on number of retries.</returns>
public override bool RetryLimitReached(IExecutionContext executionContext)
{
return executionContext.RequestContext.Retries >= this.MaxRetries;
}
/// <summary>
/// Waits before retrying a request. The default policy implements a exponential backoff.
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
public override void WaitBeforeRetry(IExecutionContext executionContext)
{
DefaultRetryPolicy.WaitBeforeRetry(executionContext.RequestContext.Retries, this.MaxBackoffInMilliseconds);
}
/// <summary>
/// Waits for an amount of time using an exponential backoff algorithm.
/// </summary>
/// <param name="retries">The request retry index. The first request is expected to be 0 while
/// the first retry will be 1.</param>
/// <param name="maxBackoffInMilliseconds">The max number of milliseconds to wait</param>
public static void WaitBeforeRetry(int retries, int maxBackoffInMilliseconds)
{
AWSSDKUtils.Sleep(CalculateRetryDelay(retries, maxBackoffInMilliseconds));
}
private static int CalculateRetryDelay(int retries, int maxBackoffInMilliseconds)
{
int delay;
if (retries < 12 ) delay = Convert.ToInt32(Math.Pow(4, retries) * 100.0);
else delay = Int32.MaxValue;
if (retries > 0 && (delay > maxBackoffInMilliseconds || delay <= 0))
delay = maxBackoffInMilliseconds;
return delay;
}
[Obsolete("This method is no longer used within DefaultRetryPolicy")]
protected static bool ContainErrorMessage(Exception exception)
{
return ContainErrorMessage(exception, _netStandardRetryErrorMessages);
}
[Obsolete("This method has been moved to AWSSDK.Runtime.Internal.Util.ExceptionUtils")]
protected static bool IsInnerException<T>(Exception exception)
where T : Exception
{
return ExceptionUtils.IsInnerException<T>(exception);
}
[Obsolete("This method has been moved to AWSSDK.Runtime.Internal.Util.ExceptionUtils")]
protected static bool IsInnerException<T>(Exception exception, out T inner)
where T : Exception
{
return ExceptionUtils.IsInnerException<T>(exception, out inner);
}
}
}
| 275 |
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.Util;
using Amazon.Util;
using System;
using System.Net;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The retry handler has the generic logic for retrying requests.
/// It uses a retry policy which specifies when
/// a retry should be performed.
/// </summary>
public class RetryHandler : PipelineHandler
{
private ILogger _logger;
/// <summary>
/// The logger used to log messages.
/// </summary>
public override ILogger Logger
{
get { return _logger; }
set
{
_logger = value;
this.RetryPolicy.Logger = value;
}
}
/// <summary>
/// The retry policy which specifies when
/// a retry should be performed.
/// </summary>
public RetryPolicy RetryPolicy { get; private set; }
/// <summary>
/// Constructor which takes in a retry policy.
/// </summary>
/// <param name="retryPolicy">Retry Policy</param>
public RetryHandler(RetryPolicy retryPolicy)
{
this.RetryPolicy = retryPolicy;
}
/// <summary>
/// Invokes the inner handler and performs a retry, if required as per the
/// retry policy.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override void InvokeSync(IExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
var responseContext = executionContext.ResponseContext;
bool shouldRetry = false;
this.RetryPolicy.ObtainSendToken(executionContext, null);
do
{
try
{
SetRetryHeaders(requestContext);
base.InvokeSync(executionContext);
this.RetryPolicy.NotifySuccess(executionContext);
return;
}
catch (Exception exception)
{
shouldRetry = this.RetryPolicy.Retry(executionContext, exception);
if (!shouldRetry)
{
LogForError(requestContext, exception);
throw;
}
else
{
requestContext.Retries++;
requestContext.Metrics.SetCounter(Metric.AttemptCount, requestContext.Retries);
LogForRetry(requestContext, exception);
}
this.RetryPolicy.ObtainSendToken(executionContext, exception);
}
PrepareForRetry(requestContext);
using (requestContext.Metrics.StartEvent(Metric.RetryPauseTime))
this.RetryPolicy.WaitBeforeRetry(executionContext);
} while (shouldRetry);
}
#if AWS_ASYNC_API
/// <summary>
/// Invokes the inner handler and performs a retry, if required as per the
/// retry policy.
/// </summary>
/// <typeparam name="T">The response type for the current request.</typeparam>
/// <param name="executionContext">The execution context, it contains the
/// request and response context.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public override async System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
var responseContext = executionContext.ResponseContext;
bool shouldRetry = false;
await this.RetryPolicy.ObtainSendTokenAsync(executionContext, null).ConfigureAwait(false);
do
{
System.Runtime.ExceptionServices.ExceptionDispatchInfo capturedException = null;
try
{
SetRetryHeaders(requestContext);
T result = await base.InvokeAsync<T>(executionContext).ConfigureAwait(false);
this.RetryPolicy.NotifySuccess(executionContext);
return result;
}
catch (Exception e)
{
capturedException = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e);
}
if (capturedException != null)
{
shouldRetry = await this.RetryPolicy.RetryAsync(executionContext, capturedException.SourceException).ConfigureAwait(false);
if (!shouldRetry)
{
LogForError(requestContext, capturedException.SourceException);
capturedException.Throw();
}
else
{
requestContext.Retries++;
requestContext.Metrics.SetCounter(Metric.AttemptCount, requestContext.Retries);
LogForRetry(requestContext, capturedException.SourceException);
}
await this.RetryPolicy.ObtainSendTokenAsync(executionContext, capturedException.SourceException).ConfigureAwait(false);
}
PrepareForRetry(requestContext);
using (requestContext.Metrics.StartEvent(Metric.RetryPauseTime))
await RetryPolicy.WaitBeforeRetryAsync(executionContext).ConfigureAwait(false);
} while (shouldRetry);
throw new AmazonClientException("Neither a response was returned nor an exception was thrown in the Runtime RetryHandler.");
}
#endif
#if AWS_APM_API
/// <summary>
/// Invokes the inner handler and performs a retry, if required as per the
/// retry policy.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
protected override void InvokeAsyncCallback(IAsyncExecutionContext executionContext)
{
var requestContext = executionContext.RequestContext;
var responseContext = executionContext.ResponseContext;
var exception = responseContext.AsyncResult.Exception;
var syncExecutionContext = ExecutionContext.CreateFromAsyncContext(executionContext);
if (exception != null)
{
var shouldRetry = this.RetryPolicy.Retry(syncExecutionContext, exception);
if (shouldRetry)
{
requestContext.Retries++;
requestContext.Metrics.SetCounter(Metric.AttemptCount, requestContext.Retries);
LogForRetry(requestContext, exception);
PrepareForRetry(requestContext);
// Clear out current exception
responseContext.AsyncResult.Exception = null;
using (requestContext.Metrics.StartEvent(Metric.RetryPauseTime))
this.RetryPolicy.WaitBeforeRetry(syncExecutionContext);
// Retry by calling InvokeAsync
this.InvokeAsync(executionContext);
return;
}
else
{
LogForError(requestContext, exception);
}
}
else
{
this.RetryPolicy.NotifySuccess(syncExecutionContext);
}
// Call outer handler
base.InvokeAsyncCallback(executionContext);
}
#endif
/// <summary>
/// Prepares the request for retry.
/// </summary>
/// <param name="requestContext">Request context containing the state of the request.</param>
internal static void PrepareForRetry(IRequestContext requestContext)
{
if (requestContext.Request.ContentStream != null &&
requestContext.Request.OriginalStreamPosition >= 0)
{
var stream = requestContext.Request.ContentStream;
// If the stream is wrapped in a HashStream, reset the HashStream
var hashStream = stream as HashStream;
if (hashStream != null)
{
hashStream.Reset();
stream = hashStream.GetSeekableBaseStream();
}
stream.Position = requestContext.Request.OriginalStreamPosition;
}
}
private void LogForRetry(IRequestContext requestContext, Exception exception)
{
#if !NETSTANDARD
var webException = exception as WebException;
if (webException != null)
{
Logger.InfoFormat("WebException ({1}) making request {2} to {3}. Attempting retry {4} of {5}.",
webException.Status,
requestContext.RequestName,
requestContext.Request.Endpoint.ToString(),
requestContext.Retries,
this.RetryPolicy.MaxRetries);
}
else
{
#endif
Logger.InfoFormat("{0} making request {1} to {2}. Attempting retry {3} of {4}.",
exception.GetType().Name,
requestContext.RequestName,
requestContext.Request.Endpoint.ToString(),
requestContext.Retries,
this.RetryPolicy.MaxRetries);
#if !NETSTANDARD
}
#endif
}
private void LogForError(IRequestContext requestContext, Exception exception)
{
Logger.Error(exception, "{0} making request {1} to {2}. Attempt {3}.",
exception.GetType().Name,
requestContext.RequestName,
requestContext.Request.Endpoint.ToString(),
requestContext.Retries + 1);
}
private void SetRetryHeaders(IRequestContext requestContext)
{
var request = requestContext.Request;
//The invocation id will be the same for all retry requests for the initial operation invocation.
if (!request.Headers.ContainsKey(HeaderKeys.AmzSdkInvocationId))
{
request.Headers.Add(HeaderKeys.AmzSdkInvocationId, requestContext.InvocationId.ToString());
}
//Update the amz-sdk-request header with the current retry index.
var requestPairs = $"attempt={requestContext.Retries + 1}; max={RetryPolicy.MaxRetries + 1}";
if (request.Headers.ContainsKey(HeaderKeys.AmzSdkRequest))
{
request.Headers[HeaderKeys.AmzSdkRequest] = requestPairs;
}
else
{
request.Headers.Add(HeaderKeys.AmzSdkRequest, requestPairs);
}
}
}
}
| 302 |
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 System.Net;
using System.Security.Authentication;
using System.Threading;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using AWSSDK.Runtime.Internal.Util;
namespace Amazon.Runtime
{
/// <summary>
/// A retry policy specifies all aspects of retry behavior. This includes conditions when the request should be retried,
/// checks of retry limit, preparing the request before retry and introducing delay (backoff) before retries.
/// </summary>
public abstract partial class RetryPolicy
{
/// <summary>
/// Maximum number of retries to be performed.
/// This does not count the initial request.
/// </summary>
public int MaxRetries { get; protected set; }
/// <summary>
/// The logger used to log messages.
/// </summary>
public ILogger Logger { get; set; }
/// <summary>
/// The standard set of throttling error codes
/// </summary>
public virtual ICollection<string> ThrottlingErrorCodes { get; protected set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"Throttling",
"ThrottlingException",
"ThrottledException",
"RequestThrottledException",
"TooManyRequestsException",
"ProvisionedThroughputExceededException",
"TransactionInProgressException",
"RequestLimitExceeded",
"BandwidthLimitExceeded",
"LimitExceededException",
"RequestThrottled",
"SlowDown",
"PriorRequestNotComplete"
};
/// <summary>
/// The standard set of timeout error codes to retry on.
/// </summary>
public ICollection<string> TimeoutErrorCodesToRetryOn { get; protected set; } = new HashSet<string>()
{
"RequestTimeout",
"RequestTimeoutException"
};
/// <summary>
/// List of AWS specific error codes which are returned as part of the error response.
/// These error codes will be retried.
/// </summary>
public ICollection<string> ErrorCodesToRetryOn { get; protected set; } = new HashSet<string>();
#region Transient errors
/// <summary>
/// The standard set of transient error, HTTP status codes to retry on.
/// 502 and 504 are returned by proxies. These can also be returned for
/// S3 accelerate requests which are served by CloudFront.
/// </summary>
public ICollection<HttpStatusCode> HttpStatusCodesToRetryOn { get; protected set; } = new HashSet<HttpStatusCode>
{
HttpStatusCode.InternalServerError,
HttpStatusCode.ServiceUnavailable,
HttpStatusCode.BadGateway,
HttpStatusCode.GatewayTimeout
};
/// <summary>
/// Set of web exception status codes to retry on.
/// </summary>
public ICollection<WebExceptionStatus> WebExceptionStatusesToRetryOn { get; protected set; } = new HashSet<WebExceptionStatus>
{
WebExceptionStatus.ConnectFailure,
WebExceptionStatus.ConnectionClosed,
WebExceptionStatus.KeepAliveFailure,
WebExceptionStatus.NameResolutionFailure,
WebExceptionStatus.ReceiveFailure,
WebExceptionStatus.SendFailure,
WebExceptionStatus.Timeout,
};
#endregion
/// <summary>
/// This parameter serves as the value to the CapacityManager.Container datastructure.
/// Its properties include the available capacity left for making a retry request and the maximum
/// capacity size.
/// </summary>
protected RetryCapacity RetryCapacity { get; set; }
/// <summary>
/// Checks if a retry should be performed with the given execution context and exception.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="exception">The exception thrown after issuing the request.</param>
/// <returns>Returns true if the request should be retried, else false. The exception is retried if it matches with clockskew error codes.</returns>
public bool Retry(IExecutionContext executionContext, Exception exception)
{
// Boolean that denotes retries have not exceeded maxretries and request is rewindable
bool canRetry = !RetryLimitReached(executionContext) && CanRetry(executionContext);
// If canRetry is false, we still want to evaluate the exception if its retryable or not,
// is CSM is enabled. This is necessary to set the IsLastExceptionRetryable property on
// CSM Call Attempt. For S3, with the BucketRegion mismatch exception, an overhead of 100-
// 115 ms was added(because of GetPreSignedUrl and Http HEAD requests).
if (canRetry || executionContext.RequestContext.CSMEnabled)
{
var isClockSkewError = IsClockskew(executionContext, exception);
if (isClockSkewError || RetryForException(executionContext, exception))
{
executionContext.RequestContext.IsLastExceptionRetryable = true;
// If CSM is enabled but canRetry was false, we should not retry the request.
// Return false after successfully evaluating the last exception for retryable.
if (!canRetry)
{
return false;
}
executionContext.RequestContext.LastCapacityType = IsServiceTimeoutError(exception) ?
CapacityManager.CapacityType.Timeout : CapacityManager.CapacityType.Retry;
return OnRetry(executionContext, isClockSkewError, IsThrottlingError(exception));
}
}
return false;
}
/// <summary>
/// Returns true if the request is in a state where it can be retried, else false.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <returns>Returns true if the request is in a state where it can be retried, else false.</returns>
public abstract bool CanRetry(IExecutionContext executionContext);
/// <summary>
/// Return true if the request should be retried for the given exception.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="exception">The exception thrown by the previous request.</param>
/// <returns>Return true if the request should be retried.</returns>
public abstract bool RetryForException(IExecutionContext executionContext, Exception exception);
/// <summary>
/// Checks if the retry limit is reached.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <returns>Return false if the request can be retried, based on number of retries.</returns>
public abstract bool RetryLimitReached(IExecutionContext executionContext);
/// <summary>
/// Waits before retrying a request.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public abstract void WaitBeforeRetry(IExecutionContext executionContext);
/// <summary>
/// Virtual method that gets called on a successful request response.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public virtual void NotifySuccess(IExecutionContext executionContext)
{
}
/// <summary>
/// Virtual method that gets called before a retry request is initiated. The value
/// returned is True by default(retry throttling feature is disabled).
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public virtual bool OnRetry(IExecutionContext executionContext)
{
return true;
}
/// <summary>
/// Virtual method that gets called before a retry request is initiated. The value
/// returned is True by default(retry throttling feature is disabled).
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="bypassAcquireCapacity">true to bypass any attempt to acquire capacity on a retry</param>
public virtual bool OnRetry(IExecutionContext executionContext, bool bypassAcquireCapacity)
{
return true;
}
/// <summary>
/// Virtual method that gets called before a retry request is initiated. The value
/// returned is True by default(retry throttling feature is disabled).
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="bypassAcquireCapacity">true to bypass any attempt to acquire capacity on a retry</param>
/// <param name="isThrottlingError">true if the error that will be retried is a throttling error</param>
public virtual bool OnRetry(IExecutionContext executionContext, bool bypassAcquireCapacity, bool isThrottlingError)
{
return OnRetry(executionContext, bypassAcquireCapacity);
}
/// <summary>
/// This method uses a token bucket to enforce the maximum sending rate.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="exception">If the prior request failed, this exception is expected to be
/// the exception that occurred during the prior request failure.</param>
public virtual void ObtainSendToken(IExecutionContext executionContext, Exception exception)
{
}
/// <summary>
/// Determines if an AmazonServiceException is a throttling error
/// </summary>
/// <param name="exception">The current exception to check.</param>
/// <returns>true if it is a throttling error else false.</returns>
public virtual bool IsThrottlingError(Exception exception)
{
var serviceException = exception as AmazonServiceException;
return serviceException?.Retryable?.Throttling == true ||
ThrottlingErrorCodes.Contains(serviceException?.ErrorCode);
}
/// <summary>
/// Determines if an AmazonServiceException is a transient error that
/// should be retried.
/// </summary>
/// <param name="executionContext">The current execution context</param>
/// <param name="exception">The current exception to check.</param>
/// <returns>true if the exception is a transient error else false.</returns>
public virtual bool IsTransientError(IExecutionContext executionContext, Exception exception)
{
// An IOException was thrown by the underlying http client.
if (exception is IOException)
{
#if !NETSTANDARD // ThreadAbortException is not NetStandard
// Don't retry IOExceptions that are caused by a ThreadAbortException
if (ExceptionUtils.IsInnerException<ThreadAbortException>(exception))
return false;
#endif
// Retry all other IOExceptions
return true;
}
else if (ExceptionUtils.IsInnerException<IOException>(exception))
{
return true;
}
//Check for AmazonServiceExceptions specifically
var serviceException = exception as AmazonServiceException;
if(serviceException != null)
{
//Check if the exception is marked retryable.
if (serviceException.Retryable != null)
{
return true;
}
//Check for specific HTTP status codes that are associated with transient
//service errors as long as they are not throttling errors.
if (HttpStatusCodesToRetryOn.Contains(serviceException.StatusCode) &&
!IsThrottlingError(exception))
{
return true;
}
//Check for successful responses that couldn't be unmarshalled. These should be considered
//transient errors because the payload could have been corrupted after OK was sent in the
//header.
if(serviceException.StatusCode == HttpStatusCode.OK && serviceException is AmazonUnmarshallingException)
{
return true;
}
}
//Check for WebExceptions that are considered transient
WebException webException;
if (ExceptionUtils.IsInnerException(exception, out webException))
{
if (WebExceptionStatusesToRetryOn.Contains(webException.Status))
{
return true;
}
}
if (IsTransientSslError(exception))
{
return true;
}
#if NETSTANDARD
// Version 7.35 libcurl which is the default version installed with Ubuntu 14.04
// has issues under high concurrency causing response streams being disposed
// during unmarshalling. To work around this issue will add the ObjectDisposedException
// to the list of exceptions to retry.
if (ExceptionUtils.IsInnerException<ObjectDisposedException>(exception))
return true;
//If it isn't a serviceException that we already processed for StatusCode and it
//is a HttpRequestException, then it is a network type error that did not reach the
//service and it should be retried.
if (serviceException == null && exception is System.Net.Http.HttpRequestException)
{
return true;
}
if (exception is OperationCanceledException)
{
if (!executionContext.RequestContext.CancellationToken.IsCancellationRequested)
{
//OperationCanceledException thrown by HttpClient not the CancellationToken supplied by the user.
//This exception can wrap at least IOExceptions, ObjectDisposedExceptions and should be retried
return true;
}
}
// .NET 5 introduced changes to HttpClient for timed out requests by returning a wrapped TimeoutException.
if (exception is TimeoutException)
return true;
#endif
return false;
}
private const string sslErrorZeroReturn = "SSL_ERROR_ZERO_RETURN";
public static bool IsTransientSslError(Exception exception)
{
var isAuthenticationException = false;
// Scan down the exceptions chain for a sslErrorZeroReturn keyword in the Message,
// given that the one of the parent exceptions is AuthenticationException.
// Based on https://github.com/aws/aws-sdk-net/issues/1556
while (exception != null)
{
if (exception is AuthenticationException)
{
isAuthenticationException = true;
}
if (isAuthenticationException && exception.Message.Contains(sslErrorZeroReturn))
{
return true;
}
exception = exception.InnerException;
}
return false;
}
/// <summary>
/// Determines if the exception is a known timeout error code that
/// should be retried under the timeout error category.
/// </summary>
/// <param name="exception">The current exception to check.</param>
/// <returns>true if the exception is considered a timeout else false</returns>
public virtual bool IsServiceTimeoutError(Exception exception)
{
var serviceException = exception as AmazonServiceException;
return TimeoutErrorCodesToRetryOn.Contains(serviceException?.ErrorCode);
}
#region Clock skew correction
private static HashSet<string> clockSkewErrorCodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"RequestTimeTooSkewed",
"RequestExpired",
"InvalidSignatureException",
"SignatureDoesNotMatch",
"AuthFailure",
"RequestExpired",
"RequestInTheFuture",
};
private const string clockSkewMessageFormat = "Identified clock skew: local time = {0}, local time with correction = {1}, current clock skew correction = {2}, server time = {3}, service endpoint = {4}.";
private const string clockSkewUpdatedFormat = "Setting clock skew correction: new clock skew correction = {0}, service endpoint = {1}.";
private const string clockSkewMessageParen = "(";
private const string clockSkewMessagePlusSeparator = " + ";
private const string clockSkewMessageMinusSeparator = " - ";
private static TimeSpan clockSkewMaxThreshold = TimeSpan.FromMinutes(5);
private bool IsClockskew(IExecutionContext executionContext, Exception exception)
{
var clientConfig = executionContext.RequestContext.ClientConfig;
var ase = exception as AmazonServiceException;
var isHead =
executionContext.RequestContext.Request != null &&
string.Equals(executionContext.RequestContext.Request.HttpMethod, "HEAD", StringComparison.Ordinal);
var isClockskewErrorCode =
ase != null &&
(ase.ErrorCode == null || clockSkewErrorCodes.Contains(ase.ErrorCode));
if (isHead || isClockskewErrorCode)
{
var endpoint = executionContext.RequestContext.Request.Endpoint.ToString();
var realNow = AWSConfigs.utcNowSource();
var correctedNow = CorrectClockSkew.GetCorrectedUtcNowForEndpoint(endpoint);
DateTime serverTime;
// Try getting server time from the headers
bool serverTimeDetermined = TryParseDateHeader(ase, out serverTime);
// If that fails, try to parse it from the exception message
if (!serverTimeDetermined)
serverTimeDetermined = TryParseExceptionMessage(ase, out serverTime);
if (serverTimeDetermined)
{
// using accurate server time, calculate correction if local time is off
serverTime = serverTime.ToUniversalTime();
var diff = correctedNow - serverTime;
var absDiff = diff.Ticks < 0 ? -diff : diff;
if (absDiff > clockSkewMaxThreshold)
{
var newCorrection = serverTime - realNow;
Logger.InfoFormat(clockSkewMessageFormat,
realNow, correctedNow, clientConfig.ClockOffset, serverTime, endpoint);
// Always set the correction, for informational purposes
CorrectClockSkew.SetClockCorrectionForEndpoint(endpoint, newCorrection);
var shouldRetry = AWSConfigs.CorrectForClockSkew && !AWSConfigs.ManualClockCorrection.HasValue;
// Only retry if clock skew correction is not disabled
if (shouldRetry)
{
// Set clock skew correction
Logger.InfoFormat(clockSkewUpdatedFormat, newCorrection, endpoint);
executionContext.RequestContext.IsSigned = false;
return true;
}
}
}
}
return false;
}
private static bool TryParseDateHeader(AmazonServiceException ase, out DateTime serverTime)
{
var webData = GetWebData(ase);
if (webData != null)
{
// parse server time from "Date" header, if possible
var dateValue = webData.GetHeaderValue(HeaderKeys.DateHeader);
if (!string.IsNullOrEmpty(dateValue))
{
if (DateTime.TryParseExact(
dateValue,
AWSSDKUtils.GMTDateFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out serverTime))
{
return true;
}
}
}
serverTime = DateTime.MinValue;
return false;
}
private static bool TryParseExceptionMessage(AmazonServiceException ase, out DateTime serverTime)
{
if (ase != null && !string.IsNullOrEmpty(ase.Message))
{
var message = ase.Message;
// parse server time from exception message, if possible
var parenIndex = message.IndexOf(clockSkewMessageParen, StringComparison.Ordinal);
if (parenIndex >= 0)
{
parenIndex++;
// Locate " + " or " - " separator that follows the server time string
var separatorIndex = message.IndexOf(clockSkewMessagePlusSeparator, parenIndex, StringComparison.Ordinal);
if (separatorIndex < 0)
separatorIndex = message.IndexOf(clockSkewMessageMinusSeparator, parenIndex, StringComparison.Ordinal);
// Get the server time string and parse it
if (separatorIndex > parenIndex)
{
var timestamp = message.Substring(parenIndex, separatorIndex - parenIndex);
if (DateTime.TryParseExact(
timestamp,
AWSSDKUtils.ISO8601BasicDateTimeFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out serverTime))
{
return true;
}
}
}
}
serverTime = DateTime.MinValue;
return false;
}
#endregion
private static IWebResponseData GetWebData(AmazonServiceException ase)
{
if (ase != null)
{
Exception e = ase;
do
{
var here = e as HttpErrorResponseException;
if (here != null)
return here.Response;
e = e.InnerException;
} while (e != null);
}
return null;
}
protected static bool ContainErrorMessage(Exception exception, HashSet<string> errorMessages)
{
if (exception == null)
return false;
if (errorMessages.Contains(exception.Message))
return true;
return ContainErrorMessage(exception.InnerException, errorMessages);
}
/// <summary>
/// Creates a key for storing retry capacity data.
/// Key is based on service's url (we store retry capacity per service's url variant).
/// If ClientConfig's ServiceURL override is set we use it as a key,
/// otherwise we construct key based on ClientConfig's schema, region, service, fips, dualstack parameters.
/// This value is unique key per real service's url variant.
/// </summary>
protected static string GetRetryCapacityKey(IClientConfig config)
{
return config.ServiceURL != null ? config.ServiceURL :
$"http:{config.UseHttp}//region:{config.RegionEndpoint?.SystemName}.service:{config.RegionEndpointServiceName}.fips:{config.UseFIPSEndpoint}.ipv6:{config.UseDualstackEndpoint}";
}
}
}
| 582 |
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;
using AWSSDK.Runtime.Internal.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The default implementation of the standard retry policy.
/// </summary>
public partial class StandardRetryPolicy : RetryPolicy
{
private static Random _randomJitter = new Random();
//The status code returned from a service request when an invalid endpoint is used.
private const int INVALID_ENDPOINT_EXCEPTION_STATUSCODE = 421;
protected static CapacityManager CapacityManagerInstance { get; set; } = new CapacityManager(throttleRetryCount: 100, throttleRetryCost: 5, throttleCost: 1, timeoutRetryCost: 10);
/// <summary>
/// The maximum value of exponential backoff in milliseconds, which will be used to wait
/// before retrying a request. The default is 20000 milliseconds.
/// </summary>
public int MaxBackoffInMilliseconds { get; set; } = 20000;
/// <summary>
/// Constructor for StandardRetryPolicy.
/// </summary>
/// <param name="maxRetries">The maximum number of retries before throwing
/// back a exception. This does not count the initial request.</param>
public StandardRetryPolicy(int maxRetries)
{
this.MaxRetries = maxRetries;
}
/// <summary>
/// Constructor for StandardRetryPolicy.
/// </summary>
/// <param name="config">The Client config object. This is used to
/// retrieve the maximum number of retries before throwing
/// back a exception(This does not count the initial request) and
/// the service URL for the request.</param>
public StandardRetryPolicy(IClientConfig config)
{
this.MaxRetries = config.MaxErrorRetry;
if (config.ThrottleRetries)
{
RetryCapacity = CapacityManagerInstance.GetRetryCapacity(GetRetryCapacityKey(config));
}
}
/// <summary>
/// Returns true if the request is in a state where it can be retried, else false.
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
/// <returns>Returns true if the request is in a state where it can be retried, else false.</returns>
public override bool CanRetry(IExecutionContext executionContext)
{
return executionContext.RequestContext.Request.IsRequestStreamRewindable();
}
/// <summary>
/// Return true if the request should be retried.
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
/// <param name="exception">The exception thrown by the previous request.</param>
/// <returns>Return true if the request should be retried.</returns>
public override bool RetryForException(IExecutionContext executionContext, Exception exception)
{
return RetryForExceptionSync(exception, executionContext);
}
/// <summary>
/// Virtual method that gets called when a retry request is initiated. If retry throttling is
/// enabled, the value returned is true if the required capacity is retured, false otherwise.
/// If retry throttling is disabled, true is returned.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override bool OnRetry(IExecutionContext executionContext)
{
return OnRetry(executionContext, false, false);
}
/// <summary>
/// Virtual method that gets called when a retry request is initiated. If retry throttling is
/// enabled, the value returned is true if the required capacity is retured, false otherwise.
/// If retry throttling is disabled, true is returned.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="bypassAcquireCapacity">true to bypass any attempt to acquire capacity on a retry</param>
public override bool OnRetry(IExecutionContext executionContext, bool bypassAcquireCapacity)
{
return OnRetry(executionContext, bypassAcquireCapacity, false);
}
/// <summary>
/// Virtual method that gets called when a retry request is initiated. If retry throttling is
/// enabled, the value returned is true if the required capacity is retured, false otherwise.
/// If retry throttling is disabled, true is returned.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="bypassAcquireCapacity">true to bypass any attempt to acquire capacity on a retry</param>
/// <param name="isThrottlingError">true if the error that will be retried is a throtting error</param>
public override bool OnRetry(IExecutionContext executionContext, bool bypassAcquireCapacity, bool isThrottlingError)
{
if (!bypassAcquireCapacity && executionContext.RequestContext.ClientConfig.ThrottleRetries && RetryCapacity != null)
{
return CapacityManagerInstance.TryAcquireCapacity(RetryCapacity, executionContext.RequestContext.LastCapacityType);
}
else
{
return true;
}
}
/// <summary>
/// Virtual method that gets called on a success Response. If its a retry success response, the entire
/// retry acquired capacity is released(default is 5). If its just a success response a lesser value capacity
/// is released(default is 1).
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
public override void NotifySuccess(IExecutionContext executionContext)
{
if(executionContext.RequestContext.ClientConfig.ThrottleRetries && RetryCapacity != null)
{
var requestContext = executionContext.RequestContext;
CapacityManagerInstance.ReleaseCapacity(requestContext.LastCapacityType, RetryCapacity);
}
}
/// <summary>
/// Perform the processor-bound portion of the RetryForException logic.
/// This is shared by the sync, async, and APM versions of the RetryForException method.
/// </summary>
/// <param name="exception">The exception thrown by the previous request.</param>
/// <returns>Return true if the request should be retried.</returns>
protected bool RetryForExceptionSync(Exception exception)
{
return RetryForExceptionSync(exception, null);
}
/// <summary>
/// Perform the processor-bound portion of the RetryForException logic.
/// This is shared by the sync, async, and APM versions of the RetryForException method.
/// </summary>
/// <param name="exception">The exception thrown by the previous request.</param>
/// <param name="executionContext">Request context containing the state of the request.</param>
/// <returns>Return true if the request should be retried.</returns>
protected bool RetryForExceptionSync(Exception exception, IExecutionContext executionContext)
{
// AmazonServiceException is thrown by ErrorHandler if it is this type of exception.
var serviceException = exception as AmazonServiceException;
// To try and smooth out an occasional throttling error, we'll pause and
// retry, hoping that the pause is long enough for the request to get through
// the next time. Only the error code should be used to determine if an
// error is a throttling error.
if (IsThrottlingError(exception))
{
return true;
}
// Check for transient errors, but we need to use
// an exponential back-off strategy so that we don't overload
// a server with a flood of retries. If we've surpassed our
// retry limit we handle the error response as a non-retryable
// error and go ahead and throw it back to the user as an exception.
if (IsTransientError(executionContext, exception) || IsServiceTimeoutError(exception))
{
return true;
}
//Check for Invalid Endpoint Exception indicating that the Endpoint Discovery
//endpoint used was invalid for the request. One retry attempt is allowed for this
//type of exception.
if (serviceException?.StatusCode == (HttpStatusCode)INVALID_ENDPOINT_EXCEPTION_STATUSCODE)
{
if (executionContext.RequestContext.EndpointDiscoveryRetries < 1)
{
executionContext.RequestContext.EndpointDiscoveryRetries++;
return true;
}
return false;
}
return false;
}
/// <summary>
/// Checks if the retry limit is reached.
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
/// <returns>Return false if the request can be retried, based on number of retries.</returns>
public override bool RetryLimitReached(IExecutionContext executionContext)
{
return executionContext.RequestContext.Retries >= this.MaxRetries;
}
/// <summary>
/// Waits before retrying a request. The default policy implements a exponential backoff with
/// jitter algorithm.
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
public override void WaitBeforeRetry(IExecutionContext executionContext)
{
StandardRetryPolicy.WaitBeforeRetry(executionContext.RequestContext.Retries, this.MaxBackoffInMilliseconds);
}
/// <summary>
/// Waits for an amount of time using an exponential backoff with jitter algorithm.
/// </summary>
/// <param name="retries">The request retry index. The first request is expected to be 0 while
/// the first retry will be 1.</param>
/// <param name="maxBackoffInMilliseconds">The max number of milliseconds to wait</param>
public static void WaitBeforeRetry(int retries, int maxBackoffInMilliseconds)
{
AWSSDKUtils.Sleep(CalculateRetryDelay(retries, maxBackoffInMilliseconds));
}
protected static int CalculateRetryDelay(int retries, int maxBackoffInMilliseconds)
{
double jitter;
lock (_randomJitter) {
jitter = _randomJitter.NextDouble();
}
return Convert.ToInt32(Math.Min(jitter * Math.Pow(2, retries - 1) * 1000.0, maxBackoffInMilliseconds));
}
}
}
| 251 |
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;
using System;
using System.Threading.Tasks;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The default implementation of the adaptive policy.
/// </summary>
public partial class AdaptiveRetryPolicy : StandardRetryPolicy
{
/// <summary>
/// Return true if the request should be retried.
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
/// <param name="exception">The exception thrown by the previous request.</param>
/// <returns>Return true if the request should be retried.</returns>
public override Task<bool> RetryForExceptionAsync(IExecutionContext executionContext, Exception exception)
{
return Task.FromResult(RetryForExceptionSync(exception, executionContext));
}
/// <summary>
/// Waits before retrying a request.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override Task WaitBeforeRetryAsync(IExecutionContext executionContext)
{
var delay = CalculateRetryDelay(executionContext.RequestContext.Retries, this.MaxBackoffInMilliseconds);
return Task.Delay(delay, executionContext.RequestContext.CancellationToken);
}
/// <summary>
/// This method uses a token bucket to enforce the maximum sending rate.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="exception">If the prior request failed, this exception is expected to be
/// the exception that occurred during the prior request failure.</param>
public override async Task ObtainSendTokenAsync(IExecutionContext executionContext, Exception exception)
{
if (!(await TokenBucket.TryAcquireTokenAsync(1, executionContext.RequestContext.ClientConfig.FastFailRequests,
executionContext.RequestContext.CancellationToken).ConfigureAwait(false)))
{
var whyFail = exception == null ? "The initial request cannot be attempted because capacity could not be obtained"
: "While attempting to retry a request error capacity could not be obtained";
if (executionContext.RequestContext.ClientConfig.FastFailRequests)
{
throw new AmazonClientException($"{whyFail}. The client is configured to fail fast and there is insufficent capacity to attempt the request.", exception);
}
//Else we were unable to obtain capacity after looping.
throw new AmazonClientException($"{whyFail}. There is insufficent capacity to attempt the request after attempting to obtain capacity multiple times.", exception);
}
}
}
} | 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 Amazon.Util;
using System;
using System.Threading.Tasks;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The default implementation of the legacy retry policy.
/// </summary>
public partial class DefaultRetryPolicy : RetryPolicy
{
/// <summary>
/// Return true if the request should be retried.
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
/// <param name="exception">The exception thrown by the previous request.</param>
/// <returns>Return true if the request should be retried.</returns>
public override Task<bool> RetryForExceptionAsync(IExecutionContext executionContext, Exception exception)
{
return Task.FromResult(RetryForExceptionSync(exception, executionContext));
}
/// <summary>
/// Waits before retrying a request.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override Task WaitBeforeRetryAsync(IExecutionContext executionContext)
{
var delay = CalculateRetryDelay(executionContext.RequestContext.Retries, this.MaxBackoffInMilliseconds);
return Task.Delay(delay, executionContext.RequestContext.CancellationToken);
}
}
} | 49 |
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 Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;
using System.Threading.Tasks;
namespace Amazon.Runtime
{
/// <summary>
/// A retry policy specifies all aspects of retry behavior. This includes conditions when the request should be retried,
/// checks of retry limit, preparing the request before retry and introducing delay (backoff) before retries.
/// </summary>
public abstract partial class RetryPolicy
{
/// <summary>
/// Checks if a retry should be performed with the given execution context and exception.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="exception">The exception throw after issuing the request.</param>
/// <returns>Returns true if the request should be retried, else false. The exception is retried if it matches with clockskew error codes.</returns>
public async Task<bool> RetryAsync(IExecutionContext executionContext, Exception exception)
{
bool canRetry = !RetryLimitReached(executionContext) && CanRetry(executionContext);
if (canRetry || executionContext.RequestContext.CSMEnabled)
{
var isClockSkewError = IsClockskew(executionContext, exception);
if (isClockSkewError || await RetryForExceptionAsync(executionContext, exception).ConfigureAwait(false))
{
executionContext.RequestContext.IsLastExceptionRetryable = true;
if (!canRetry)
{
return false;
}
return OnRetry(executionContext, isClockSkewError, IsThrottlingError(exception));
}
}
return false;
}
/// <summary>
/// This method uses a token bucket to enforce the maximum sending rate.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="exception">If the prior request failed, this exception is expected to be
/// the exception that occurred during the prior request failure.</param>
public virtual Task ObtainSendTokenAsync(IExecutionContext executionContext, Exception exception)
{
#if NETSTANDARD
return Task.CompletedTask;
#else
return Task.FromResult(0);
#endif
}
/// <summary>
/// Return true if the request should be retried for the given exception.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
/// <param name="exception">The exception thrown by the previous request.</param>
/// <returns>Return true if the request should be retried.</returns>
public abstract Task<bool> RetryForExceptionAsync(IExecutionContext executionContext, Exception exception);
/// <summary>
/// Waits before retrying a request.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public abstract Task WaitBeforeRetryAsync(IExecutionContext executionContext);
}
}
| 93 |
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;
using System;
using System.Threading.Tasks;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// The default implementation of the standard policy.
/// </summary>
public partial class StandardRetryPolicy : RetryPolicy
{
/// <summary>
/// Return true if the request should be retried.
/// </summary>
/// <param name="executionContext">Request context containing the state of the request.</param>
/// <param name="exception">The exception thrown by the previous request.</param>
/// <returns>Return true if the request should be retried.</returns>
public override Task<bool> RetryForExceptionAsync(IExecutionContext executionContext, Exception exception)
{
return Task.FromResult(RetryForExceptionSync(exception, executionContext));
}
/// <summary>
/// Waits before retrying a request.
/// </summary>
/// <param name="executionContext">The execution context which contains both the
/// requests and response context.</param>
public override Task WaitBeforeRetryAsync(IExecutionContext executionContext)
{
var delay = CalculateRetryDelay(executionContext.RequestContext.Retries, this.MaxBackoffInMilliseconds);
return Task.Delay(delay, executionContext.RequestContext.CancellationToken);
}
}
} | 49 |
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.Util;
using System;
using System.Threading;
namespace Amazon.Runtime.Internal
{
public class RuntimeAsyncResult : IAsyncResult, IDisposable
{
private object _lockObj;
private ManualResetEvent _waitHandle;
private bool _disposed = false;
private bool _callbackInvoked = false;
private ILogger _logger;
public RuntimeAsyncResult(AsyncCallback asyncCallback, object asyncState)
{
_lockObj = new object();
_callbackInvoked = false;
_logger = Logger.GetLogger(typeof(RuntimeAsyncResult));
this.AsyncState = asyncState;
this.IsCompleted = false;
this.AsyncCallback = asyncCallback;
this.CompletedSynchronously = false;
this._logger = Logger.GetLogger(this.GetType());
}
private AsyncCallback AsyncCallback { get; set; }
public object AsyncState { get; private set; }
public System.Threading.WaitHandle AsyncWaitHandle
{
get
{
if (this._waitHandle != null)
{
return this._waitHandle;
}
lock (this._lockObj)
{
if (this._waitHandle == null)
{
this._waitHandle = new ManualResetEvent(this.IsCompleted);
}
}
return this._waitHandle;
}
}
public bool CompletedSynchronously { get; private set; }
public bool IsCompleted { get; private set; }
public Exception Exception { get; set; }
public AmazonWebServiceResponse Response { get; set; }
internal void SignalWaitHandle()
{
this.IsCompleted = true;
if (this._waitHandle != null)
{
this._waitHandle.Set();
}
}
internal void HandleException(Exception exception)
{
this.Exception = exception;
InvokeCallback();
}
public void InvokeCallback()
{
this.SignalWaitHandle();
if (!_callbackInvoked)
{
_callbackInvoked = true;
try {
if(this.AsyncCallback != null)
this.AsyncCallback(this);
} catch (Exception e)
{
_logger.Error(e, "An unhandled exception occurred in the user callback.");
}
}
}
#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 && _waitHandle != null)
{
#if NETSTANDARD
_waitHandle.Dispose();
#else
_waitHandle.Close();
#endif
_waitHandle = null;
}
this._disposed = true;
}
}
/// <summary>
/// Disposes of all managed and unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| 143 |
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 Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Util;
using System.Collections.Generic;
using System.IO;
namespace Amazon.Runtime.SharedInterfaces
{
/// <summary>
/// Interface for an asymmetric SigV4 (SigV4a) signer
/// </summary>
public interface IAWSSigV4aProvider
{
/// <summary>
/// Protocol for the requests being signed
/// </summary>
ClientProtocol Protocol { get; }
/// <summary>
/// Calculates and signs the specified request using the asymmetric Sigv4 (Sigv4a) signing protocol.
/// The resulting signature is added to the request headers as 'Authorization'. Parameters supplied in the request, either in
/// the resource path as a query string or in the Parameters collection must not have been
/// uri encoded. If they have, use the SignRequest method to obtain a signature.
/// </summary>
/// <param name="request">
/// The request to compute the signature for. Additional headers mandated by the AWS4a protocol
/// ('host' and 'x-amz-date') will be added to the request before signing.
/// </param>
/// <param name="clientConfig">
/// Client configuration data encompassing the service call (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="credentials">
/// The AWS credentials for the account making the service call.
/// </param>
void Sign(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials);
/// <summary>
/// Calculates and signs the specified request using the asymmetric Sigv4 (Sigv4a) signing protocol.
/// The resulting signature is added to the request headers as 'Authorization'. Parameters supplied in the request, either in
/// the resource path as a query string or in the Parameters collection must not have been
/// uri encoded. If they have, use the SignRequest method to obtain a signature.
/// </summary>
/// <param name="request">
/// The request to compute the signature for. Additional headers mandated by the AWS4a protocol
/// ('host' and 'x-amz-date') will be added to the request before signing.
/// </param>
/// <param name="clientConfig">
/// Client configuration data encompassing the service call (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="credentials">
/// The AWS credentials for the account making the service call.
/// </param>
/// <returns>AWS4a Signing Result</returns>
AWS4aSigningResult SignRequest(IRequest request, IClientConfig clientConfig, RequestMetrics metrics, ImmutableCredentials credentials);
/// <summary>
/// Calculates the asymmetric Sigv4 (Sigv4a) signature for a presigned url.
/// </summary>
/// <param name="request">
/// The request to compute the signature for.
/// </param>
/// <param name="clientConfig">
/// Adding supporting data for the service call required by the signer (notably authentication
/// region, endpoint and service name).
/// </param>
/// <param name="metrics">
/// Metrics for the request
/// </param>
/// <param name="credentials">
/// The AWS credentials for the account making the service call.
/// </param>
/// <param name="service">
/// The service to sign for
/// </param>
/// <param name="overrideSigningRegion">
/// The region to sign to, if null then the region the client is configured for will be used.
/// </param>
/// <returns>AWS4a Signing Result</returns>
AWS4aSigningResult Presign4a(IRequest request,
IClientConfig clientConfig,
RequestMetrics metrics,
ImmutableCredentials credentials,
string service,
string overrideSigningRegion);
/// <summary>
/// Calculates the signature for a single chunk of a chunked SigV4a request
/// </summary>
/// <param name="chunkBody">Content of the current chunk</param>
/// <param name="previousSignature">Signature of the previous chunk</param>
/// <param name="headerSigningResult">Signing result of the request's header</param>
/// <returns>Unpadded SigV4a signature of the given chunk</returns>
string SignChunk(Stream chunkBody, string previousSignature, AWS4aSigningResult headerSigningResult);
/// <summary>
/// Signs the final chunk containing trailing headers
/// </summary>
/// <param name="trailingHeaders">Trailing header keys and values</param>
/// <param name="previousSignature">Signature of the previous chunk</param>
/// <param name="headerSigningResult">Signing result of the request's header</param>
/// <returns>Signature of the trailing header chunk</returns>
string SignTrailingHeaderChunk(IDictionary<string, string> trailingHeaders, string previousSignature, AWS4aSigningResult headerSigningResult);
}
}
| 128 |
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.Net;
namespace Amazon.Runtime.SharedInterfaces
{
/// <summary>
/// ICoreAmazonKMS is not meant to be used directly. It defines Key Management 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 AmazonKeyManagementServiceClient
/// defined in the AWSSDK.KeyManagementService assembly.
/// </summary>
public interface ICoreAmazonKMS : IDisposable
{
GenerateDataKeyResult GenerateDataKey(string keyID, Dictionary<string, string> encryptionContext, string keySpec);
byte[] Decrypt(byte[] ciphertextBlob, Dictionary<string, string> encryptionContext);
#if AWS_ASYNC_API
System.Threading.Tasks.Task<GenerateDataKeyResult> GenerateDataKeyAsync(string keyID, Dictionary<string, string> encryptionContext, string keySpec);
System.Threading.Tasks.Task<byte[]> DecryptAsync(byte[] ciphertextBlob, Dictionary<string, string> encryptionContext);
#endif
}
/// <summary>
/// The result of the GenerateDataKey and GenerateDataKeyAsync operations.
/// </summary>
public class GenerateDataKeyResult
{
/// <summary>
/// The plaintext for the data key.
/// </summary>
public byte[] KeyPlaintext { get; set; }
/// <summary>
/// The ciphertext for the data key.
/// </summary>
public byte[] KeyCiphertext { get; set; }
}
}
| 57 |
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>
/// Generate a presigned URL.
/// </summary>
/// <param name="bucketName"></param>
/// <param name="objectKey"></param>
/// <param name="expiration"></param>
/// <param name="additionalProperties"></param>
/// <returns></returns>
string GeneratePreSignedURL(string bucketName, string objectKey, DateTime expiration, IDictionary<string, object> additionalProperties);
#if AWS_APM_API
/// <summary>
/// Start a delete object.
/// </summary>
/// <param name="bucketName"></param>
/// <param name="objectKey"></param>
/// <param name="additionalProperties"></param>
/// <param name="callback"></param>
/// <param name="state"></param>
/// <returns></returns>
IAsyncResult BeginDelete(string bucketName, string objectKey, IDictionary<string, object> additionalProperties, AsyncCallback callback, object state);
/// <summary>
/// Get the results of a delete object.
/// </summary>
/// <param name="result"></param>
void EndDelete(IAsyncResult result);
/// <summary>
/// Start an upload object from stream.
/// </summary>
/// <param name="bucketName"></param>
/// <param name="objectKey"></param>
/// <param name="stream"></param>
/// <param name="additionalProperties"></param>
/// <param name="callback"></param>
/// <param name="state"></param>
/// <returns></returns>
IAsyncResult BeginUploadObjectFromStream(string bucketName, string objectKey, Stream stream, IDictionary<string, object> additionalProperties, AsyncCallback callback, object state);
/// <summary>
/// Get the results of an upload from stream.
/// </summary>
/// <param name="result"></param>
void EndUploadObjectFromStream(IAsyncResult result);
/// <summary>
/// Start an upload object from file path.
/// </summary>
/// <param name="bucketName"></param>
/// <param name="objectKey"></param>
/// <param name="filepath"></param>
/// <param name="additionalProperties"></param>
/// <param name="callback"></param>
/// <param name="state"></param>
/// <returns></returns>
IAsyncResult BeginUploadObjectFromFilePath(string bucketName, string objectKey, string filepath, IDictionary<string, object> additionalProperties, AsyncCallback callback, object state);
/// <summary>
/// Get the results of an upload from file path.
/// </summary>
/// <param name="result"></param>
void EndUploadObjectFromFilePath(IAsyncResult result);
/// <summary>
/// Start a download to a file path.
/// </summary>
/// <param name="bucketName"></param>
/// <param name="objectKey"></param>
/// <param name="filepath"></param>
/// <param name="additionalProperties"></param>
/// <param name="callback"></param>
/// <param name="state"></param>
/// <returns></returns>
IAsyncResult BeginDownloadToFilePath(string bucketName, string objectKey, string filepath, IDictionary<string, object> additionalProperties, AsyncCallback callback, object state);
/// <summary>
/// Get results of downloading an object to a file path.
/// </summary>
/// <param name="result"></param>
void EndDownloadToFilePath(IAsyncResult result);
/// <summary>
/// Start opening a stream to an object in S3.
/// </summary>
/// <param name="bucketName"></param>
/// <param name="objectKey"></param>
/// <param name="additionalProperties"></param>
/// <param name="callback"></param>
/// <param name="state"></param>
/// <returns></returns>
IAsyncResult BeginGetObjectStream(string bucketName, string objectKey, IDictionary<string, object> additionalProperties, AsyncCallback callback, object state);
/// <summary>
/// Get results of opening a stream to an object in S3.
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
Stream EndGetObjectStream(IAsyncResult result);
#endif
}
}
| 120 |
aws-sdk-net | aws | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Amazon.Runtime.SharedInterfaces
{
/// <summary>
/// ICoreAmazonSQS is not meant to use directly. It defines SQS with basic .NET types
/// and allows other services to be able to use SQS as a runtime dependency. This interface
/// is implemented by the AmazonSQSClient defined in the SQS assembly.
/// </summary>
public interface ICoreAmazonSQS
{
#if BCL
/// <summary>
/// <para>
/// This method is used internally to access the Amazon SQS service within other service assemblies.
/// Please use AmazonSQSClient to access Amazon SQS instead.
/// </para>
/// Get the attributes for the queue identified by the queue URL.
/// </summary>
/// <param name="queueUrl">The queue URL to get attributes for.</param>
/// <returns>The attributes for the queue.</returns>
Dictionary<string, string> GetAttributes(string queueUrl);
#endif
#if AWS_ASYNC_API
/// <summary>
/// Get the attributes for the queue identified by the queue URL asynchronously.
/// </summary>
/// <param name="queueUrl">The queue URL to get attributes for.</param>
/// <returns>A Task containing the result of a dictionary of attributes for the queue.</returns>
System.Threading.Tasks.Task<Dictionary<string, string>> GetAttributesAsync(string queueUrl);
#endif
#if BCL
/// <summary>
/// <para>
/// This method is used internally to access the Amazon SQS service within other service assemblies.
/// Please use AmazonSQSClient to access Amazon SQS instead.
/// </para>
/// Set the attributes on the queue identified by the queue URL.
/// </summary>
/// <param name="queueUrl">The queue URL to set the attributues.</param>
/// <param name="attributes">The attributes to set.</param>
void SetAttributes(string queueUrl, Dictionary<string, string> attributes);
#endif
#if AWS_ASYNC_API
/// <summary>
/// Set the attributes on the queue identified by the queue URL asynchronously.
/// </summary>
/// <param name="queueUrl">The queue URL to set the attributues.</param>
/// <param name="attributes">The attributes to set.</param>
/// <returns>A Task</returns>
System.Threading.Tasks.Task SetAttributesAsync(string queueUrl, Dictionary<string, string> attributes);
#endif
}
}
| 59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.