private static string GetHttpRequestHeader(HttpHeaders headers, string headerName)
        {
            if (!headers.Contains(headerName))
                return string.Empty;

            return headers.GetValues(headerName)
                            .SingleOrDefault();
        }
        protected internal override IFullHttpRequest NewHandshakeRequest()
        {
            Uri wsUrl = Uri;

            // Get 16 bit nonce and base 64 encode it
            byte[] nonce = WebSocketUtil.RandomBytes(16);
            string key   = WebSocketUtil.Base64String(nonce);

            string acceptSeed = key + MagicGuid;

            byte[] sha1 = WebSocketUtil.Sha1(Encoding.ASCII.GetBytes(acceptSeed));
            _expectedChallengeResponseString = new AsciiString(WebSocketUtil.Base64String(sha1));

#if DEBUG
            if (Logger.DebugEnabled)
            {
                Logger.WebSocketVersion07ClientHandshakeKey(key, _expectedChallengeResponseString);
            }
#endif

            // Format request
            var request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, UpgradeUrl(wsUrl),
                                                     Unpooled.Empty);
            HttpHeaders headers = request.Headers;

            if (CustomHeaders is object)
            {
                _ = headers.Add(CustomHeaders);
                if (!headers.Contains(HttpHeaderNames.Host))
                {
                    // Only add HOST header if customHeaders did not contain it.
                    //
                    // See https://github.com/netty/netty/issues/10101
                    _ = headers.Set(HttpHeaderNames.Host, WebsocketHostValue(wsUrl));
                }
            }
            else
            {
                _ = headers.Set(HttpHeaderNames.Host, WebsocketHostValue(wsUrl));
            }

            _ = headers.Set(HttpHeaderNames.Upgrade, HttpHeaderValues.Websocket)
                .Set(HttpHeaderNames.Connection, HttpHeaderValues.Upgrade)
                .Set(HttpHeaderNames.SecWebsocketKey, key);

            if (!headers.Contains(HttpHeaderNames.SecWebsocketOrigin))
            {
                _ = headers.Set(HttpHeaderNames.SecWebsocketOrigin, WebsocketOriginValue(wsUrl));
            }

            string expectedSubprotocol = ExpectedSubprotocol;
            if (!string.IsNullOrEmpty(expectedSubprotocol))
            {
                _ = headers.Set(HttpHeaderNames.SecWebsocketProtocol, expectedSubprotocol);
            }

            _ = headers.Set(HttpHeaderNames.SecWebsocketVersion, Version.ToString());

            return(request);
        }
Esempio n. 3
0
        private void UpdateRateLimits(HttpHeaders headers)
        {
            if (!headers.Contains(RateLimitHeader))
            {
                return;
            }
            if (!headers.Contains(RateLimitRemainingHeader))
            {
                return;
            }

            var limit     = headers.GetValues(RateLimitHeader).First();
            var remaining = headers.GetValues(RateLimitRemainingHeader).First();

            lock (RateLimitsLock)
            {
                var now = DateTimeOffset.Now;

                if (RateLimits?.LastUpdated >= now)
                {
                    return;
                }

                RateLimits = new RateLimits(int.Parse(limit), int.Parse(remaining), now);
            }
        }
Esempio n. 4
0
        static bool IsPreflightRequest(IHttpRequest request)
        {
            HttpHeaders headers = request.Headers;

            return(request.Method.Equals(HttpMethod.Options) &&
                   headers.Contains(HttpHeaderNames.Origin) &&
                   headers.Contains(HttpHeaderNames.AccessControlRequestMethod));
        }
        private static TablePaginationToken GetPaginationToken(HttpHeaders headers)
        {
            if (headers.Contains(TableConstants.NextPartitionKey) && headers.Contains(TableConstants.NextRowKey))
            {
                return(new TablePaginationToken(headers));
            }

            return(default);
Esempio n. 6
0
        /// <summary>
        /// Determine whether paging parameters have been specified.
        /// </summary>
        /// <param name="headers">Request headers.</param>
        /// <exception cref="ArgumentNullException">Parameter is null.</exception>
        /// <returns>True if paging parameters have been found; false otherwise.</returns>
        internal static bool HasPagingHeaders(HttpHeaders headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            return(headers.Contains(RequestHeader.navigationPage.ToDescription()) || headers.Contains(RequestHeader.navigationPageSize.ToDescription()));
        }
Esempio n. 7
0
        /// <summary>
        /// Determine whether a method override has been specified.
        /// </summary>
        /// <param name="headers">Request headers.</param>
        /// <exception cref="ArgumentNullException">Parameter is null.</exception>
        /// <returns>True if method override header found; false otherwise.</returns>
        internal static bool HasMethodOverrideHeader(HttpHeaders headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            bool hasMethodOverride    = headers.Contains(RequestHeader.methodOverride.ToDescription());
            bool hasMethodOverrideSif = headers.Contains(RequestHeader.methodOverrideSif.ToDescription());

            return(hasMethodOverride || hasMethodOverrideSif);
        }
Esempio n. 8
0
        private static string DetermineResponseIdByAllHeader(HttpHeaders allHeader)
        {
            if (allHeader.Contains(BunqHeaders.HEADER_RESPONSE_ID_UPPER_CASE))
            {
                return(allHeader.GetValues(BunqHeaders.HEADER_RESPONSE_ID_UPPER_CASE).First());
            }

            if (allHeader.Contains(BunqHeaders.HEADER_RESPONSE_ID_LOWER_CASE))
            {
                return(allHeader.GetValues(BunqHeaders.HEADER_RESPONSE_ID_LOWER_CASE).First());
            }

            return(BunqHeaders.ERROR_COULD_NOT_DETERMINE_RESPONSE_ID_HEADER);
        }
Esempio n. 9
0
        private static TEntity UpdateData <TEntity>(SQLiteHelper sqlite, TEntity entity, HttpHeaders httpHeader = null) where TEntity : IEntity
        {
            var userId = 0;

            if (httpHeader != null && httpHeader.Contains("User"))
            {
                foreach (var use in httpHeader.GetValues("User"))
                {
                    int.TryParse(use, out userId);
                    if (userId > 0)
                    {
                        break;
                    }
                }
            }
            if (entity.Version > 0)
            {
                entity.Version    = entity.Version + 1;
                entity.UpdateBy   = userId > 0 ? userId : entity.UpdateBy;
                entity.UpdateDate = DateTime.Now;
                _Update(sqlite, entity);
            }
            else
            {
                entity.Id         = sqlite.MaxId(SQLiteHelper.ToHump(typeof(TEntity).Name)) + 1;
                entity.Version    = 1;
                entity.InsertBy   = userId > 0 ? userId : entity.InsertBy;
                entity.InsertDate = DateTime.Now;
                entity.IsLive     = true;
                _Insert(sqlite, entity);
            }
            return(entity);
        }
Esempio n. 10
0
        public GetUserResponse GetUser(HttpHeaders header)
        {
            var reply = new GetUserResponse();

            if (!header.Contains("UserId"))
            {
                reply.FailureReason = GetUserResponse.Reason.NoUserInHeader;
            }
            else if (!Guid.TryParse(header.GetValues("UserId").FirstOrDefault(), out Guid userId))
            {
                reply.FailureReason = GetUserResponse.Reason.InvalidUserId;
            }
            else
            {
                var user = _accountProvider.GetUser(userId);
                if (user == null)
                {
                    reply.User = new User {
                        UserId = userId
                    };
                    reply.FailureReason = GetUserResponse.Reason.NotFound;
                }
                else
                {
                    reply.User = user;
                }
            }

            return(reply);
        }
Esempio n. 11
0
        public static void ShouldContainHeader(this HttpHeaders header, string key, string correctValue)
        {
            Assert.True(header.Contains(key), $"Header '{key}' not found");
            var headerValue = header.GetValues(key).FirstOrDefault()?.Trim();

            Assert.True(headerValue == correctValue, $"Header '{key}' has value '{headerValue}' instead of {correctValue}");
        }
Esempio n. 12
0
 /// <summary>
 /// Removes a header
 /// </summary>
 /// <param name="headers">The headers collection</param>
 /// <param name="name">Name of the header</param>
 /// <remarks>If the header does not exist, this does nothing</remarks>
 public static void SafeRemove(this HttpHeaders headers, string name)
 {
     if (headers.Contains(name))
     {
         headers.Remove(name);
     }
 }
        /// <summary>
        /// Reads possible tokens from two sources, this.tokens and from <paramref name="t"/>.
        /// Writes to <paramref name="headers"/>.
        ///
        /// Searches for following keys:
        /// <list type="bullet">
        ///     <item>"System.Net.Http.Headers.HttpHeaders" as IEnumerable{KeyValuePair{string, IEnumerable{string}}}</item>
        /// </list>
        ///
        /// Appends "User-Agent" is one is not set.
        /// </summary>
        /// <param name="uri">Uri to use as token query criteria</param>
        /// <param name="t">(optional)</param>
        /// <param name="headers"></param>
        protected virtual void ReadTokenToHeaders(string uri, IOption t, HttpHeaders headers)
        {
            // Headers
            IEnumerable <KeyValuePair <string, IEnumerable <string> > >[] headers_array;

            // Read from local token
            if (this.token.TryGetAllTokens(uri, TOKEN_HEADERS, out headers_array))
            {
                foreach (var _headers in headers_array)
                {
                    foreach (KeyValuePair <string, IEnumerable <string> > header in _headers)
                    {
                        headers.Add(header.Key, header.Value);
                    }
                }
            }
            // Read from parameter token
            if (t.TryGetAllTokens(uri, TOKEN_HEADERS, out headers_array))
            {
                foreach (var _headers in headers_array)
                {
                    foreach (KeyValuePair <string, IEnumerable <string> > header in _headers)
                    {
                        headers.Add(header.Key, header.Value);
                    }
                }
            }

            // Add User-Agent
            if (!headers.Contains("User-Agent"))
            {
                headers.Add("User-Agent", "Lexical.FileSystem");
            }
        }
        private static Func<KeyValuePair<string, string>, bool> HaveOneMatchingItemWithin(HttpHeaders headers)
        {
            return item =>
                {
                    if (!headers.Contains(item.Key))
                    {
                        return false;
                    }

                    var expectedValues = Regex.Split(item.Value, @",\s*");
                    var actualValues = headers.GetValues(item.Key);

                    return headers.Contains(item.Key)
                           && expectedValues.OrderBy(i => i).SequenceEqual(actualValues.OrderBy(i => i));
                };
        }
Esempio n. 15
0
 public static void AddIfNotExists(this HttpHeaders headers, string key, string value)
 {
     if (headers.Contains(key))
     {
         return;
     }
     headers.Add(key, value);
 }
Esempio n. 16
0
 public static string GetHeaderSingleValueOrDefault(this HttpHeaders headers, string name)
 {
     if (headers.Contains(name))
     {
         return(RestUtility.GetFirstHeaderValue(headers.GetValues(name)));
     }
     return(string.Empty);
 }
Esempio n. 17
0
        public static string GetHeaderValue(this HttpHeaders headers, string key, string separator)
        {
            if (!headers.Contains(key))
            {
                return(null);
            }

            return(string.Join(separator, headers.GetValues(key)));
        }
Esempio n. 18
0
        private static string GetHttpRequestHeader(HttpHeaders headers, string headerName)
        {
            if (!headers.Contains(headerName))
            {
                return(string.Empty);
            }

            return(headers.GetValues(headerName).SingleOrDefault());
        }
Esempio n. 19
0
        private static string MaybeGetHeader(HttpHeaders headers, string name)
        {
            if ((headers == null) || (!headers.Contains(name)))
            {
                return(null);
            }

            return(headers.GetValues(name).First());
        }
Esempio n. 20
0
        public void Set(string key, string value)
        {
            if (_headers.Contains(key))
            {
                _headers.Remove(key);
            }

            _headers.Add(key, value);
        }
 /// <summary>
 /// Get architecture metadata from a HttpHeaders object
 /// </summary>
 /// <param name="headers"></param>
 /// <returns></returns>
 public static ArchitectureMetadata GetArchitectureMetadata(HttpHeaders headers)
 {
     if (headers.Contains(HttpConstants.ArchitectureMetadataName))
     {
         var values = headers.GetValues(HttpConstants.ArchitectureMetadataName);
         return(ArchitectureMetadata.FromString(values.FirstOrDefault()));
     }
     return(null);
 }
        public static void SetAuthToken(this HttpHeaders headers, string value)
        {
            if (headers.Contains(AuthTokenHeader))
            {
                headers.Remove(AuthTokenHeader);
            }

            headers.Add(AuthTokenHeader, value);
        }
Esempio n. 23
0
 private void ContainingHeader(HttpHeaders headers, string name, bool isContentHeader = false)
 {
     if (!headers.Contains(name))
     {
         this.ThrowNewHttpResponseMessageAssertionException(
             isContentHeader ? "content headers" : "headers",
             string.Format("to contain {0}", name),
             "none was found");
     }
 }
Esempio n. 24
0
        public static string GetHeaderValue(this HttpHeaders headers, string headerName)
        {
            string str = string.Empty;

            if (headers != null && headers.Contains(headerName))
            {
                str = headers.GetValues(headerName).FirstOrDefault <string>();
            }
            return(str);
        }
Esempio n. 25
0
 private void SetContentHeader(HttpHeaders headers)
 {
     foreach (var header in clientSetting.DefaultContentHeaders)
     {
         if (headers.Contains(header.Key))
         {
             headers.Remove(header.Key);
         }
         headers.Add(header.Key, header.Value);
     }
 }
Esempio n. 26
0
 /// <summary>
 /// If the values list is null or empty, return empty string,
 /// otherwise return the first value.
 /// </summary>
 /// <param name="values">List of values</param>
 /// <returns>A single value</returns>
 internal static string GetHeaderSingleValueOrDefault(this HttpHeaders headers, string name)
 {
     if (headers.Contains(name))
     {
         return(CommonUtils.GetSingleValueOrDefault(headers.GetValues(name)));
     }
     else
     {
         return(string.Empty);
     }
 }
        private static void AddApiVersionHeader(HttpHeaders headers, string headerName, IReadOnlyList <ApiVersion> versions)
        {
            Contract.Requires(headers != null);
            Contract.Requires(!IsNullOrEmpty(headerName));
            Contract.Requires(versions != null);

            if (versions.Count > 0 && !headers.Contains(headerName))
            {
                headers.Add(headerName, Join(ValueSeparator, versions.Select(v => v.ToString())));
            }
        }
Esempio n. 28
0
        private void SetHeaders(HttpHeaders headers, IEnumerable <KeyValuePair <string, List <string> > > toAdd)
        {
            foreach (var header in toAdd)
            {
                if (headers.Contains(header.Key))
                {
                    headers.Remove(header.Key);
                }

                headers.Add(header.Key, header.Value);
            }
        }
        public static string GetValueSafe(this HttpHeaders headers, string name)
        {
            string value = default(string);

            if (headers?.Contains(name) ?? false)
            {
                value = headers.GetValues(name).First();
                value = StringUtilities.EnforceMaxLength(value, InjectionGuardConstants.QuickPulseResponseHeaderMaxLength);
            }

            return(value);
        }
 private static bool IsRequiredHeaderMissing(string headerName, HttpHeaders requestHeaders, List <string> requiredHeaders)
 {
     try
     {
         return(requiredHeaders.Contains(headerName) && !requestHeaders.Contains(headerName));
     }
     catch (Exception)
     {
         // ref: https://github.com/dotnet/runtime/issues/21000
         return(false);
     }
 }
        private bool ShouldRetry(
            int numRetries,
            bool error,
            HttpStatusCode?statusCode,
            HttpHeaders headers)
        {
            // Do not retry if we are out of retries.
            if (numRetries >= this.maxNetworkRetries)
            {
                return(false);
            }

            // Retry on connection error.
            if (error == true)
            {
                return(true);
            }

            // The API may ask us not to retry (eg; if doing so would be a no-op)
            // or advise us to retry (eg; in cases of lock timeouts); we defer to that.
            if (headers != null && headers.Contains("Stripe-Should-Retry"))
            {
                var value = headers.GetValues("Stripe-Should-Retry").First();

                switch (value)
                {
                case "true":
                    return(true);

                case "false":
                    return(false);
                }
            }

            // Retry on conflict errors.
            if (statusCode == HttpStatusCode.Conflict)
            {
                return(true);
            }

            // Retry on 500, 503, and other internal errors.
            //
            // Note that we expect the Stripe-Should-Retry header to be false
            // in most cases when a 500 is returned, since our idempotency framework
            // would typically replay it anyway.
            if (statusCode.HasValue && ((int)statusCode.Value >= 500))
            {
                return(true);
            }

            return(false);
        }
Esempio n. 32
0
        protected override RavenJObject GetFilteredMetadataFromHeaders(HttpHeaders headers)
        {
            var result = base.GetFilteredMetadataFromHeaders(headers);

            if (headers.Contains(Constants.RavenLastModified))
            {
                // this is required to resolve conflicts based on last modification date

                result.Add(Constants.RavenLastModified, headers.GetValues(Constants.RavenLastModified).First());
            }

            return(result);
        }
		protected override RavenJObject GetFilteredMetadataFromHeaders(HttpHeaders headers)
		{
			var result = base.GetFilteredMetadataFromHeaders(headers);

			if (headers.Contains(Constants.RavenLastModified))
			{
				// this is required to resolve conflicts based on last modification date

				result.Add(Constants.RavenLastModified, headers.GetValues(Constants.RavenLastModified).First());
			}

			return result;
		}
Esempio n. 34
0
        /// <summary>
        /// Determine whether a method override has been specified.
        /// </summary>
        /// <param name="headers">Request headers.</param>
        /// <exception cref="ArgumentNullException">Parameter is null.</exception>
        /// <returns>True if method override header found; false otherwise.</returns>
        internal static bool HasMethodOverrideHeader(HttpHeaders headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            bool hasMethodOverride = headers.Contains(RequestHeader.methodOverride.ToDescription());
            bool hasMethodOverrideSif = headers.Contains(RequestHeader.methodOverrideSif.ToDescription());

            return (hasMethodOverride || hasMethodOverrideSif);
        }
Esempio n. 35
0
        /// <summary>
        /// Determine whether paging parameters have been specified.
        /// </summary>
        /// <param name="headers">Request headers.</param>
        /// <exception cref="ArgumentNullException">Parameter is null.</exception>
        /// <returns>True if paging parameters have been found; false otherwise.</returns>
        internal static bool HasPagingHeaders(HttpHeaders headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            return headers.Contains(RequestHeader.navigationPage.ToDescription()) || headers.Contains(RequestHeader.navigationPageSize.ToDescription());
        }