This class defines utilities and constants that can be used by all the client libraries of the SDK.
Esempio n. 1
0
        /**
         * Convert Dictionary of paremeters to Url encoded query string
         */
        internal static string GetParametersAsString(IDictionary <string, string> parameters)
        {
            StringBuilder data = new StringBuilder(512);

            foreach (string key in (IEnumerable <string>)parameters.Keys)
            {
                string value = parameters[key];
                if (value != null)
                {
                    data.Append(key);
                    data.Append('=');
                    data.Append(AWSSDKUtils.UrlEncode(value, false));
                    data.Append('&');
                }
            }
            string result = data.ToString();

            return(result.Remove(result.Length - 1));
        }
Esempio n. 2
0
        /// <summary>
        /// Returns the canonicalized resource path for the service endpoint
        /// </summary>
        /// <param name="endpoint">Endpoint URL for the request</param>
        /// <param name="resourcePath">Resource path for the request</param>
        /// <remarks>
        /// If resourcePath begins or ends with slash, the resulting canonicalized
        /// path will follow suit.
        /// </remarks>
        /// <returns>Canonicalized resource path for the endpoint</returns>
        public static string CanonicalizeResourcePath(Uri endpoint, string resourcePath)
        {
            if (endpoint != null)
            {
                var path = endpoint.AbsolutePath;
                if (string.IsNullOrEmpty(path) || string.Equals(path, Slash, StringComparison.Ordinal))
                {
                    path = string.Empty;
                }

                if (!string.IsNullOrEmpty(resourcePath) && resourcePath.StartsWith(Slash, StringComparison.Ordinal))
                {
                    resourcePath = resourcePath.Substring(1);
                }

                if (!string.IsNullOrEmpty(resourcePath))
                {
                    path = path + Slash + resourcePath;
                }

                resourcePath = path;
            }

            if (string.IsNullOrEmpty(resourcePath))
            {
                return(Slash);
            }

            // split path at / into segments
            var pathSegments = resourcePath.Split(new char[] { SlashChar }, StringSplitOptions.None);

            // url encode the segments
            var encodedSegments = pathSegments
                                  .Select(segment => AWSSDKUtils.UrlEncode(segment, false))
                                  .ToArray();

            // join the encoded segments with /
            var canonicalizedResourcePath = string.Join(Slash, encodedSegments);

            return(canonicalizedResourcePath);
        }
        public static AWSPublicIpAddressRanges Load()
        {
            int num = 0;

            while (num < 3)
            {
                try
                {
                    return(Parse(AWSSDKUtils.DownloadStringContent(IpAddressRangeEndpoint)));
                }
                catch (Exception innerException)
                {
                    num++;
                    if (num == 3)
                    {
                        throw new AmazonServiceException(string.Format(CultureInfo.InvariantCulture, "Error downloading public IP address ranges file from {0}.", IpAddressRangeEndpoint), innerException);
                    }
                }
                AWSSDKUtils.Sleep(Math.Min((int)(Math.Pow(4.0, (double)num) * 100.0), 30000));
            }
            return(null);
        }
Esempio n. 4
0
        private static List <string> GetItems(string relativeOrAbsolutePath, int tries, bool slurp)
        {
            var items = new List <string>();

            try
            {
                if (!IsIMDSEnabled)
                {
                    throw new IMDSDisabledException();
                }

                // if we are given a relative path, we assume the data we need exists under the
                // main metadata root
                var uri = relativeOrAbsolutePath.StartsWith(EC2_METADATA_SVC, StringComparison.Ordinal)
                            ? new Uri(relativeOrAbsolutePath)
                            : new Uri(EC2_METADATA_ROOT + relativeOrAbsolutePath);

                var content = AWSSDKUtils.DownloadStringContent(uri, TimeSpan.FromSeconds(5));
                using (var stream = new StringReader(content))
                {
                    if (slurp)
                    {
                        items.Add(stream.ReadToEnd());
                    }
                    else
                    {
                        string line;
                        do
                        {
                            line = stream.ReadLine();
                            if (line != null)
                            {
                                items.Add(line.Trim());
                            }
                        }while (line != null);
                    }
                }
            }
            catch (WebException wex)
            {
                var response = wex.Response as HttpWebResponse;
                if (response != null && response.StatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }

                if (tries <= 1)
                {
                    Logger.GetLogger(typeof(EC2InstanceMetadata)).Error(wex, "Unable to contact EC2 Metadata service.");
                    return(null);
                }

                PauseExponentially(tries);
                return(GetItems(relativeOrAbsolutePath, tries - 1, slurp));
            }
            catch (IMDSDisabledException)
            {
                // Keep this behavior identical to when HttpStatusCode.NotFound is returned.
                return(null);
            }

            return(items);
        }
        private static List <string> GetItems(string relativeOrAbsolutePath, int tries, bool slurp, string token)
        {
            var items = new List <string>();
            //For all meta-data queries we need to fetch an api token to use. In the event a
            //token cannot be obtained we will fallback to not using a token.
            Dictionary <string, string> headers = null;

            if (token == null)
            {
                token = FetchApiToken(DEFAULT_RETRIES);
            }

            if (!string.IsNullOrEmpty(token))
            {
                headers = new Dictionary <string, string>();
                headers.Add(HeaderKeys.XAwsEc2MetadataToken, token);
            }

            try
            {
                if (!IsIMDSEnabled)
                {
                    throw new IMDSDisabledException();
                }

                // if we are given a relative path, we assume the data we need exists under the
                // main metadata root
                var uri = relativeOrAbsolutePath.StartsWith(EC2_METADATA_SVC, StringComparison.Ordinal)
                            ? new Uri(relativeOrAbsolutePath)
                            : new Uri(EC2_METADATA_ROOT + relativeOrAbsolutePath);

                var content = AWSSDKUtils.ExecuteHttpRequest(uri, "GET", null, TimeSpan.FromSeconds(5), Proxy, headers);
                using (var stream = new StringReader(content))
                {
                    if (slurp)
                    {
                        items.Add(stream.ReadToEnd());
                    }
                    else
                    {
                        string line;
                        do
                        {
                            line = stream.ReadLine();
                            if (line != null)
                            {
                                items.Add(line.Trim());
                            }
                        }while (line != null);
                    }
                }
            }
            catch (IMDSDisabledException)
            {
                // Keep this behavior identical to when HttpStatusCode.NotFound is returned.
                return(null);
            }
            catch (Exception e)
            {
                HttpStatusCode?httpStatusCode = ExceptionUtils.DetermineHttpStatusCode(e);

                if (httpStatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }
                else if (httpStatusCode == HttpStatusCode.Unauthorized)
                {
                    ClearTokenFlag();
                    Logger.GetLogger(typeof(EC2InstanceMetadata)).Error(e, "EC2 Metadata service returned unauthorized for token based secure data flow.");
                    throw;
                }

                if (tries <= 1)
                {
                    Logger.GetLogger(typeof(EC2InstanceMetadata)).Error(e, "Unable to contact EC2 Metadata service.");
                    return(null);
                }

                PauseExponentially(DEFAULT_RETRIES - tries);
                return(GetItems(relativeOrAbsolutePath, tries - 1, slurp, token));
            }

            return(items);
        }
Esempio n. 6
0
        /// <summary>
        /// Returns the canonicalized resource path for the service endpoint
        /// </summary>
        /// <param name="endpoint">Endpoint URL for the request</param>
        /// <param name="resourcePath">Resource path for the request</param>
        /// <param name="detectPreEncode">If true pre URL encode path segments if necessary.
        /// S3 is currently the only service that does not expect pre URL encoded segments.</param>
        /// <param name="pathResources">Dictionary of key/value parameters containing the values for the ResourcePath key replacements</param>
        /// <param name="marshallerVersion">The version of the marshaller that constructed the request object.</param>
        /// <remarks>
        /// If resourcePath begins or ends with slash, the resulting canonicalized
        /// path will follow suit.
        /// </remarks>
        /// <returns>Canonicalized resource path for the endpoint</returns>
        public static string CanonicalizeResourcePath(Uri endpoint, string resourcePath, bool detectPreEncode, IDictionary <string, string> pathResources, int marshallerVersion)
        {
            if (endpoint != null)
            {
                var path = endpoint.AbsolutePath;
                if (string.IsNullOrEmpty(path) || string.Equals(path, Slash, StringComparison.Ordinal))
                {
                    path = string.Empty;
                }

                if (!string.IsNullOrEmpty(resourcePath) && resourcePath.StartsWith(Slash, StringComparison.Ordinal))
                {
                    resourcePath = resourcePath.Substring(1);
                }

                if (!string.IsNullOrEmpty(resourcePath))
                {
                    path = path + Slash + resourcePath;
                }

                resourcePath = path;
            }

            if (string.IsNullOrEmpty(resourcePath))
            {
                return(Slash);
            }



            IEnumerable <string> encodedSegments;

            if (marshallerVersion >= 2)
            {
                encodedSegments = AWSSDKUtils.SplitResourcePathIntoSegments(resourcePath, pathResources);
            }
            else
            {
                //split path at / into segments
                encodedSegments = resourcePath.Split(new char[] { SlashChar }, StringSplitOptions.None);
            }

            var pathWasPreEncoded = false;

            if (detectPreEncode)
            {
                if (endpoint == null)
                {
                    throw new ArgumentNullException(nameof(endpoint), "A non-null endpoint is necessary to decide whether or not to pre URL encode.");
                }

                // S3 is a special case.  For S3 skip the pre encode.
                // For everything else URL pre encode the resource path segments.
                if (!S3Uri.IsS3Uri(endpoint))
                {
                    if (marshallerVersion >= 2)
                    {
                        encodedSegments = encodedSegments.Select(segment => UrlEncode(segment, true).Replace(Slash, EncodedSlash));
                    }
                    else
                    {
                        encodedSegments = encodedSegments.Select(segment => ProtectEncodedSlashUrlEncode(segment, true));
                    }

                    pathWasPreEncoded = true;
                }
            }

            var canonicalizedResourcePath = string.Empty;

            if (marshallerVersion >= 2)
            {
                canonicalizedResourcePath = AWSSDKUtils.JoinResourcePathSegments(encodedSegments, false);
            }
            else
            {
                // Encode for canonicalization
                encodedSegments = encodedSegments.Select(segment => UrlEncode(segment, false));

                // join the encoded segments with /
                canonicalizedResourcePath = string.Join(Slash, encodedSegments.ToArray());
            }

            // Get the logger each time (it's cached) because we shouldn't store it in a static variable.
            Logger.GetLogger(typeof(AWSSDKUtils)).DebugFormat("{0} encoded {1}{2} for canonicalization: {3}",
                                                              pathWasPreEncoded ? "Double" : "Single",
                                                              resourcePath,
                                                              endpoint == null ? "" : " with endpoint " + endpoint.AbsoluteUri,
                                                              canonicalizedResourcePath);

            return(canonicalizedResourcePath);
        }
 internal TypeMapping(TypeMappingElement mapping)
     : this(mapping.Type, mapping.TargetTable)
 {
     AWSSDKUtils.FillDictionary(mapping.PropertyConfigs.Items, p => p.Name, p => new PropertyConfig(p), PropertyConfigs);
 }