Esempio n. 1
0
 internal CachedRawResponse(HttpRawResponse rawResponse, HttpCachePolicySettings settings, string kernelCacheUrl, Guid cachedVaryId)
 {
     this._rawResponse    = rawResponse;
     this._settings       = settings;
     this._kernelCacheUrl = kernelCacheUrl;
     this._cachedVaryId   = cachedVaryId;
 }
Esempio n. 2
0
 internal CachedRawResponse(
     HttpRawResponse rawResponse,
     HttpCachePolicySettings settings,
     CachedVary cachedVary)
 {
     _rawResponse = rawResponse;
     _settings    = settings;
     _cachedVary  = cachedVary;
 }
Esempio n. 3
0
 private static bool IsSubstBlockSerializable(HttpRawResponse rawResponse)
 {
     if (rawResponse.HasSubstBlocks)
     {
         for (int i = 0; i < rawResponse.Buffers.Count; i++)
         {
             HttpSubstBlockResponseElement element = rawResponse.Buffers[i] as HttpSubstBlockResponseElement;
             if ((element != null) && !element.Callback.Method.IsStatic)
             {
                 return(false);
             }
         }
     }
     return(true);
 }
        public async Task <HttpRawResponse> SendDataAsyncRawResponse <T>(string url, T data, CancellationToken cancellationToken, string username = null, DifferentiatorPath?differentiator = null)
        {
            var json = _jsonSerializationService.Serialize(data);

            using (var content = BuildContent(json, username, differentiator))
            {
                var response = await _httpClient.PostAsync(url, content, cancellationToken);

                var rawResponse = new HttpRawResponse
                {
                    StatusCode = (int)response.StatusCode,
                    IsSuccess  = response.IsSuccessStatusCode,
                    Content    = await response.Content.ReadAsStringAsync()
                };

                return(rawResponse);
            }
        }
Esempio n. 5
0
 private static bool IsSubstBlockSerializable(HttpRawResponse rawResponse)
 {
     if (!rawResponse.HasSubstBlocks)
     {
         return(true);
     }
     for (int i = 0; i < rawResponse.Buffers.Count; i++)
     {
         HttpSubstBlockResponseElement substBlock = rawResponse.Buffers[i] as HttpSubstBlockResponseElement;
         if (substBlock == null)
         {
             continue;
         }
         if (!substBlock.Callback.Method.IsStatic)
         {
             return(false);
         }
     }
     return(true);
 }
        public void IsContentEncodingAcceptable_Should_Return_True_If_ContentEncoding_And_AcceptableEncoding_Headers_Match()
        {
            var request        = new Mock <HttpRequestBase>();
            var requestHeaders = new NameValueCollection();

            requestHeaders.Add(AcceptEncodingHeaderName, "gzip");
            request.Setup(r => r.Headers).Returns(requestHeaders);
            var httpContextMoq = new Mock <HttpContextBase>();

            httpContextMoq.Setup(ctx => ctx.Request).Returns(request.Object);
            var rawResponse = new HttpRawResponse();

            rawResponse.Headers = new NameValueCollection();
            rawResponse.Headers.Add(ContentEncodingHeaderName, "gzip");
            var ocHelper = new OutputCacheHelper(httpContextMoq.Object);


            var acceptable = ocHelper.IsContentEncodingAcceptable(null, rawResponse);

            Assert.True(acceptable);
        }
Esempio n. 7
0
        public void CreateOutputCacheEntry_Should_Create_Equal_OutputCacheEntry()
        {
            var buffers = new ArrayList();

            buffers.Add(CreateHttpFileResponseElementTypeInstance());
            buffers.Add(CreateHttpSubstBlockResponseElementTypeInstance());
            buffers.Add(CreateHttpResponseBufferElementTypeInstance());

            var rawResponse = new HttpRawResponse()
            {
                Headers           = DefaultRawResponseHeaders,
                StatusCode        = DefaultRawResponseStatusCode,
                StatusDescription = DefaultRawResponseStatusDescription,
                Buffers           = buffers
            };

            var rawCacheResponse = new CachedRawResponse()
            {
                CachedVaryId   = DefaultVaryId,
                CachePolicy    = new HttpCachePolicySettings(),
                KernelCacheUrl = DefaultKernelCacheUrl,
                RawResponse    = rawResponse
            };

            var converter  = new Converter();
            var cacheEntry = converter.CreateOutputCacheEntry(rawCacheResponse, DefaultDepKey, DefaultFileDep);

            Assert.Equal(rawCacheResponse.CachedVaryId, cacheEntry.CachedVaryId);
            Assert.Equal(rawCacheResponse.CachePolicy, cacheEntry.Settings);
            Assert.Equal(rawCacheResponse.KernelCacheUrl, cacheEntry.KernelCacheUrl);
            Assert.Equal(DefaultDepKey, cacheEntry.DependenciesKey);
            Assert.Equal(DefaultFileDep, cacheEntry.Dependencies);
            Assert.Equal(rawCacheResponse.RawResponse.StatusCode, cacheEntry.StatusCode);
            Assert.Equal(rawCacheResponse.RawResponse.StatusDescription, cacheEntry.StatusDescription);
            Assert.Equal(rawCacheResponse.RawResponse.Headers, cacheEntry.HeaderElements);
            Assert.Collection(cacheEntry.ResponseBuffers, VerifyOutputCacheFileResponseElement,
                              VerifySubstitutionResponseElement, VerifyMemoryResponseElement);
        }
Esempio n. 8
0
        public void SetHasParameter(bool hasParameter, ActuatorStaticDataCollection staticDataController = null)
        {
            if (staticDataController != null)
            {
                ActuatorStaticDataController = new FiddlerActuatorStaticDataCollectionController(staticDataController);
            }
            IsHasParameter = hasParameter;

            if (IsRawReplace)
            {
                if (HttpRawResponse != null)
                {
                    HttpRawResponse.SetUseParameterInfo(IsHasParameter, ActuatorStaticDataController.actuatorStaticDataCollection);
                }
            }
            else
            {
                if (BodyModific != null && BodyModific.ModificMode != ContentModificMode.NoChange)
                {
                    BodyModific.SetUseParameterInfo(IsHasParameter, ActuatorStaticDataController.actuatorStaticDataCollection);
                }
            }
        }
Esempio n. 9
0
        private static CachedRawResponse Convert(OutputCacheEntry oce)
        {
            ArrayList headers = null;

            if (oce.HeaderElements != null && oce.HeaderElements.Count > 0)
            {
                headers = new ArrayList(oce.HeaderElements.Count);
                for (int i = 0; i < oce.HeaderElements.Count; i++)
                {
                    HttpResponseHeader h = new HttpResponseHeader(oce.HeaderElements[i].Name, oce.HeaderElements[i].Value);
                    headers.Add(h);
                }
            }

            ArrayList buffers = null;

            if (oce.ResponseElements != null && oce.ResponseElements.Count > 0)
            {
                buffers = new ArrayList(oce.ResponseElements.Count);
                for (int i = 0; i < oce.ResponseElements.Count; i++)
                {
                    ResponseElement      re   = oce.ResponseElements[i];
                    IHttpResponseElement elem = null;
                    if (re is FileResponseElement)
                    {
                        HttpContext       context     = HttpContext.Current;
                        HttpWorkerRequest wr          = (context != null) ? context.WorkerRequest : null;
                        bool supportsLongTransmitFile = (wr != null && wr.SupportsLongTransmitFile);
                        bool isImpersonating          = ((context != null && context.IsClientImpersonationConfigured) || HttpRuntime.IsOnUNCShareInternal);
                        FileResponseElement fre       = (FileResponseElement)re;

                        // DevDiv #21203: Need to verify permission to access the requested file since handled by native code.
                        HttpRuntime.CheckFilePermission(fre.Path);

                        elem = new HttpFileResponseElement(fre.Path, fre.Offset, fre.Length, isImpersonating, supportsLongTransmitFile);
                    }
                    else if (re is MemoryResponseElement)
                    {
                        MemoryResponseElement mre = (MemoryResponseElement)re;
                        int size = System.Convert.ToInt32(mre.Length);
                        elem = new HttpResponseBufferElement(mre.Buffer, size);
                    }
                    else if (re is SubstitutionResponseElement)
                    {
                        SubstitutionResponseElement sre = (SubstitutionResponseElement)re;
                        elem = new HttpSubstBlockResponseElement(sre.Callback);
                    }
                    else
                    {
                        throw new NotSupportedException();
                    }
                    buffers.Add(elem);
                }
            }
            else
            {
                buffers = new ArrayList();
            }

            HttpRawResponse   rawResponse       = new HttpRawResponse(oce.StatusCode, oce.StatusDescription, headers, buffers, false /*hasSubstBlocks*/);
            CachedRawResponse cachedRawResponse = new CachedRawResponse(rawResponse, oce.Settings, oce.KernelCacheUrl, oce.CachedVaryId);

            return(cachedRawResponse);
        }
        internal void OnLeave(object source, EventArgs eventArgs)
        {
            HttpApplication application = (HttpApplication)source;
            HttpContext     context     = application.Context;
            HttpRequest     request     = context.Request;
            HttpResponse    response    = context.Response;
            HttpCachePolicy cache       = null;
            bool            flag        = false;

            if (response.HasCachePolicy)
            {
                cache = response.Cache;
                if (((cache.IsModified() && (response.Cookies.Count <= 0)) && (response.StatusCode == 200)) && (((request.HttpVerb == HttpVerb.GET) || (request.HttpVerb == HttpVerb.POST)) && response.IsBuffered()))
                {
                    bool flag3 = false;
                    if ((cache.GetCacheability() == HttpCacheability.Public) && context.RequestRequiresAuthorization())
                    {
                        cache.SetCacheability(HttpCacheability.Private);
                        flag3 = true;
                    }
                    if (((((cache.GetCacheability() == HttpCacheability.Public) || (cache.GetCacheability() == HttpCacheability.ServerAndPrivate)) || ((cache.GetCacheability() == HttpCacheability.Server) || flag3)) && (!cache.GetNoServerCaching() && (cache.HasExpirationPolicy() || cache.HasValidationPolicy()))) && ((!cache.VaryByHeaders.GetVaryByUnspecifiedParameters() && (cache.VaryByParams.AcceptsParams() || ((request.HttpVerb != HttpVerb.POST) && !request.HasQueryString))) && (!cache.VaryByContentEncodings.IsModified() || cache.VaryByContentEncodings.IsCacheableEncoding(context.Response.GetHttpHeaderContentEncoding()))))
                    {
                        flag = true;
                    }
                }
            }
            if (flag)
            {
                CachedVary vary;
                string     str;
                string[]   varyByParams;
                this.RecordCacheMiss();
                HttpCachePolicySettings currentSettings = cache.GetCurrentSettings(response);
                string[] varyByContentEncodings         = currentSettings.VaryByContentEncodings;
                string[] varyByHeaders = currentSettings.VaryByHeaders;
                if (currentSettings.IgnoreParams)
                {
                    varyByParams = null;
                }
                else
                {
                    varyByParams = currentSettings.VaryByParams;
                }
                if (this._key == null)
                {
                    this._key = this.CreateOutputCachedItemKey(context, null);
                }
                if (((varyByContentEncodings == null) && (varyByHeaders == null)) && ((varyByParams == null) && (currentSettings.VaryByCustom == null)))
                {
                    str  = this._key;
                    vary = null;
                }
                else
                {
                    int num;
                    int length;
                    if (varyByHeaders != null)
                    {
                        num    = 0;
                        length = varyByHeaders.Length;
                        while (num < length)
                        {
                            varyByHeaders[num] = "HTTP_" + CultureInfo.InvariantCulture.TextInfo.ToUpper(varyByHeaders[num].Replace('-', '_'));
                            num++;
                        }
                    }
                    bool varyByAllParams = false;
                    if (varyByParams != null)
                    {
                        varyByAllParams = (varyByParams.Length == 1) && (varyByParams[0] == "*");
                        if (varyByAllParams)
                        {
                            varyByParams = null;
                        }
                        else
                        {
                            num    = 0;
                            length = varyByParams.Length;
                            while (num < length)
                            {
                                varyByParams[num] = CultureInfo.InvariantCulture.TextInfo.ToLower(varyByParams[num]);
                                num++;
                            }
                        }
                    }
                    vary = new CachedVary(varyByContentEncodings, varyByHeaders, varyByParams, varyByAllParams, currentSettings.VaryByCustom);
                    str  = this.CreateOutputCachedItemKey(context, vary);
                    if (str == null)
                    {
                        return;
                    }
                    if (!response.IsBuffered())
                    {
                        return;
                    }
                }
                DateTime noAbsoluteExpiration = Cache.NoAbsoluteExpiration;
                TimeSpan noSlidingExpiration  = Cache.NoSlidingExpiration;
                if (currentSettings.SlidingExpiration)
                {
                    noSlidingExpiration = currentSettings.SlidingDelta;
                }
                else if (currentSettings.IsMaxAgeSet)
                {
                    DateTime time2 = (currentSettings.UtcTimestampCreated != DateTime.MinValue) ? currentSettings.UtcTimestampCreated : context.UtcTimestamp;
                    noAbsoluteExpiration = time2 + currentSettings.MaxAge;
                }
                else if (currentSettings.IsExpiresSet)
                {
                    noAbsoluteExpiration = currentSettings.UtcExpires;
                }
                if (noAbsoluteExpiration > DateTime.UtcNow)
                {
                    HttpRawResponse   snapshot       = response.GetSnapshot();
                    string            kernelCacheUrl = response.SetupKernelCaching(null);
                    Guid              cachedVaryId   = (vary != null) ? vary.CachedVaryId : Guid.Empty;
                    CachedRawResponse rawResponse    = new CachedRawResponse(snapshot, currentSettings, kernelCacheUrl, cachedVaryId);
                    CacheDependency   dependencies   = response.CreateCacheDependencyForResponse();
                    try
                    {
                        OutputCache.InsertResponse(this._key, vary, str, rawResponse, dependencies, noAbsoluteExpiration, noSlidingExpiration);
                    }
                    catch
                    {
                        if (dependencies != null)
                        {
                            dependencies.Dispose();
                        }
                        throw;
                    }
                }
                this._key = null;
            }
        }
        internal void OnEnter(object source, EventArgs eventArgs)
        {
            this._key = null;
            this._recordedCacheMiss = false;
            if (OutputCache.InUse)
            {
                string[]        strArray2   = null;
                string[]        strArray3   = null;
                HttpApplication application = (HttpApplication)source;
                HttpContext     context     = application.Context;
                context.GetFilePathData();
                HttpRequest  request  = context.Request;
                HttpResponse response = context.Response;
                switch (request.HttpVerb)
                {
                case HttpVerb.GET:
                case HttpVerb.HEAD:
                case HttpVerb.POST:
                {
                    string str;
                    this._key = str = this.CreateOutputCachedItemKey(context, null);
                    object obj2 = OutputCache.Get(str);
                    if (obj2 != null)
                    {
                        int        num;
                        int        length;
                        CachedVary cachedVary = obj2 as CachedVary;
                        if (cachedVary != null)
                        {
                            str = this.CreateOutputCachedItemKey(context, cachedVary);
                            if (str == null)
                            {
                                return;
                            }
                            if (cachedVary._contentEncodings == null)
                            {
                                obj2 = OutputCache.Get(str);
                            }
                            else
                            {
                                obj2 = null;
                                bool   flag3 = true;
                                string knownRequestHeader = context.WorkerRequest.GetKnownRequestHeader(0x16);
                                if (knownRequestHeader != null)
                                {
                                    string[] contentEncodings = cachedVary._contentEncodings;
                                    int      startIndex       = 0;
                                    bool     flag4            = false;
                                    while (!flag4)
                                    {
                                        flag4 = true;
                                        int index = GetAcceptableEncoding(contentEncodings, startIndex, knownRequestHeader);
                                        if (index > -1)
                                        {
                                            flag3 = false;
                                            obj2  = OutputCache.Get(str + contentEncodings[index]);
                                            if (obj2 == null)
                                            {
                                                startIndex = index + 1;
                                                if (startIndex < contentEncodings.Length)
                                                {
                                                    flag4 = false;
                                                }
                                            }
                                        }
                                        else if (index == -2)
                                        {
                                            flag3 = false;
                                        }
                                    }
                                }
                                if ((obj2 == null) && flag3)
                                {
                                    obj2 = OutputCache.Get(str);
                                }
                            }
                            if ((obj2 == null) || (((CachedRawResponse)obj2)._cachedVaryId != cachedVary.CachedVaryId))
                            {
                                if (obj2 != null)
                                {
                                    OutputCache.Remove(str, context);
                                }
                                return;
                            }
                        }
                        CachedRawResponse       response2 = (CachedRawResponse)obj2;
                        HttpCachePolicySettings settings  = response2._settings;
                        if ((cachedVary == null) && !settings.IgnoreParams)
                        {
                            if (request.HttpVerb == HttpVerb.POST)
                            {
                                this.RecordCacheMiss();
                                return;
                            }
                            if (request.HasQueryString)
                            {
                                this.RecordCacheMiss();
                                return;
                            }
                        }
                        if (settings.IgnoreRangeRequests)
                        {
                            string str8 = request.Headers["Range"];
                            if (StringUtil.StringStartsWithIgnoreCase(str8, "bytes"))
                            {
                                return;
                            }
                        }
                        if (!settings.HasValidationPolicy())
                        {
                            string str4 = request.Headers["Cache-Control"];
                            if (str4 != null)
                            {
                                strArray2 = str4.Split(s_fieldSeparators);
                                for (num = 0; num < strArray2.Length; num++)
                                {
                                    string str6 = strArray2[num];
                                    switch (str6)
                                    {
                                    case "no-cache":
                                    case "no-store":
                                        this.RecordCacheMiss();
                                        return;
                                    }
                                    if (StringUtil.StringStartsWith(str6, "max-age="))
                                    {
                                        int num4;
                                        try
                                        {
                                            num4 = Convert.ToInt32(str6.Substring(8), CultureInfo.InvariantCulture);
                                        }
                                        catch
                                        {
                                            num4 = -1;
                                        }
                                        if (num4 >= 0)
                                        {
                                            int num6 = (int)((context.UtcTimestamp.Ticks - settings.UtcTimestampCreated.Ticks) / 0x989680L);
                                            if (num6 >= num4)
                                            {
                                                this.RecordCacheMiss();
                                                return;
                                            }
                                        }
                                    }
                                    else if (StringUtil.StringStartsWith(str6, "min-fresh="))
                                    {
                                        int num5;
                                        try
                                        {
                                            num5 = Convert.ToInt32(str6.Substring(10), CultureInfo.InvariantCulture);
                                        }
                                        catch
                                        {
                                            num5 = -1;
                                        }
                                        if (((num5 >= 0) && settings.IsExpiresSet) && !settings.SlidingExpiration)
                                        {
                                            int num7 = (int)((settings.UtcExpires.Ticks - context.UtcTimestamp.Ticks) / 0x989680L);
                                            if (num7 < num5)
                                            {
                                                this.RecordCacheMiss();
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                            string str5 = request.Headers["Pragma"];
                            if (str5 != null)
                            {
                                strArray3 = str5.Split(s_fieldSeparators);
                                for (num = 0; num < strArray3.Length; num++)
                                {
                                    if (strArray3[num] == "no-cache")
                                    {
                                        this.RecordCacheMiss();
                                        return;
                                    }
                                }
                            }
                        }
                        else if (settings.ValidationCallbackInfo != null)
                        {
                            HttpValidationStatus valid             = HttpValidationStatus.Valid;
                            HttpValidationStatus ignoreThisRequest = valid;
                            num    = 0;
                            length = settings.ValidationCallbackInfo.Length;
                            while (num < length)
                            {
                                ValidationCallbackInfo info = settings.ValidationCallbackInfo[num];
                                try
                                {
                                    info.handler(context, info.data, ref valid);
                                }
                                catch (Exception exception)
                                {
                                    valid = HttpValidationStatus.Invalid;
                                    HttpApplicationFactory.RaiseError(exception);
                                }
                                switch (valid)
                                {
                                case HttpValidationStatus.Invalid:
                                    OutputCache.Remove(str, context);
                                    this.RecordCacheMiss();
                                    return;

                                case HttpValidationStatus.IgnoreThisRequest:
                                    ignoreThisRequest = HttpValidationStatus.IgnoreThisRequest;
                                    break;

                                case HttpValidationStatus.Valid:
                                    break;

                                default:
                                    valid = ignoreThisRequest;
                                    break;
                                }
                                num++;
                            }
                            if (ignoreThisRequest == HttpValidationStatus.IgnoreThisRequest)
                            {
                                this.RecordCacheMiss();
                                return;
                            }
                        }
                        HttpRawResponse rawResponse = response2._rawResponse;
                        if ((cachedVary == null) || (cachedVary._contentEncodings == null))
                        {
                            string    acceptEncoding  = request.Headers["Accept-Encoding"];
                            string    contentEncoding = null;
                            ArrayList headers         = rawResponse.Headers;
                            if (headers != null)
                            {
                                foreach (HttpResponseHeader header in headers)
                                {
                                    if (header.Name == "Content-Encoding")
                                    {
                                        contentEncoding = header.Value;
                                        break;
                                    }
                                }
                            }
                            if (!IsAcceptableEncoding(contentEncoding, acceptEncoding))
                            {
                                this.RecordCacheMiss();
                                return;
                            }
                        }
                        int num3 = -1;
                        if (!rawResponse.HasSubstBlocks)
                        {
                            string ifModifiedSince = request.IfModifiedSince;
                            if (ifModifiedSince != null)
                            {
                                num3 = 0;
                                try
                                {
                                    DateTime time = HttpDate.UtcParse(ifModifiedSince);
                                    if ((settings.IsLastModifiedSet && (settings.UtcLastModified <= time)) && (time <= context.UtcTimestamp))
                                    {
                                        num3 = 1;
                                    }
                                }
                                catch
                                {
                                }
                            }
                            if (num3 != 0)
                            {
                                string ifNoneMatch = request.IfNoneMatch;
                                if (ifNoneMatch != null)
                                {
                                    num3 = 0;
                                    string[] strArray = ifNoneMatch.Split(s_fieldSeparators);
                                    num    = 0;
                                    length = strArray.Length;
                                    while (num < length)
                                    {
                                        if ((num == 0) && strArray[num].Equals("*"))
                                        {
                                            num3 = 1;
                                            break;
                                        }
                                        if (strArray[num].Equals(settings.ETag))
                                        {
                                            num3 = 1;
                                            break;
                                        }
                                        num++;
                                    }
                                }
                            }
                        }
                        if (num3 == 1)
                        {
                            response.ClearAll();
                            response.StatusCode = 0x130;
                        }
                        else
                        {
                            bool sendBody = request.HttpVerb != HttpVerb.HEAD;
                            response.UseSnapshot(rawResponse, sendBody);
                        }
                        response.Cache.ResetFromHttpCachePolicySettings(settings, context.UtcTimestamp);
                        string originalCacheUrl = response2._kernelCacheUrl;
                        if (originalCacheUrl != null)
                        {
                            response.SetupKernelCaching(originalCacheUrl);
                        }
                        PerfCounters.IncrementCounter(AppPerfCounter.OUTPUT_CACHE_RATIO_BASE);
                        PerfCounters.IncrementCounter(AppPerfCounter.OUTPUT_CACHE_HITS);
                        this._key = null;
                        this._recordedCacheMiss = false;
                        application.CompleteRequest();
                        return;
                    }
                    return;
                }
                }
            }
        }