public override Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return(TypeConstants.EmptyTask);
            }

            var response = this.RequestInfo ?? GetRequestInfo(httpReq);

            response.HandlerFactoryArgs = HttpHandlerFactory.DebugLastHandlerArgs;
            response.DebugString        = "";
#if NET45
            if (HttpContext.Current != null)
            {
                response.DebugString += HttpContext.Current.Request.GetType().FullName
                                        + "|" + HttpContext.Current.Response.GetType().FullName;
            }

            if (HostContext.IsAspNetHost)
            {
                var aspReq = (HttpRequestBase)httpReq.OriginalRequest;
                response.GetLeftPath                = aspReq.Url.GetLeftAuthority();
                response.Path                       = aspReq.Path;
                response.UserHostAddress            = aspReq.UserHostAddress;
                response.ApplicationPath            = aspReq.ApplicationPath;
                response.ApplicationVirtualPath     = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
                response.VirtualAbsolutePathRoot    = VirtualPathUtility.ToAbsolute("/");
                response.VirtualAppRelativePathRoot = VirtualPathUtility.ToAppRelative("/");

                if (!Env.IsMono)
                {
                    var userIdentity = aspReq.LogonUserIdentity;
                    if (userIdentity != null)
                    {
                        response.LogonUserInfo = new Dictionary <string, string> {
                            { "Name", userIdentity.Name },
                            { "AuthenticationType", userIdentity.AuthenticationType },
                            { "IsAuthenticated", userIdentity.IsAuthenticated.ToString() },
                            { "IsAnonymous", userIdentity.IsAnonymous.ToString() },
                            { "IsGuest", userIdentity.IsGuest.ToString() },
                            { "IsSystem", userIdentity.IsSystem.ToString() },
                            { "Groups", userIdentity.Groups.Map(x => x.Value).Join(", ") },
                        };
                        var winUser = userIdentity.User;
                        if (winUser != null)
                        {
                            response.LogonUserInfo["User"] = winUser.Value;
                            response.LogonUserInfo["User.AccountDomainSid"] = winUser.AccountDomainSid?.ToString() ?? "null";
                            response.LogonUserInfo["User.IsAccountSid"]     = winUser.IsAccountSid().ToString();
                        }
                    }
                }
            }
#endif

            var json = JsonSerializer.SerializeToString(response);
            httpRes.ContentType = MimeTypes.Json;
            return(httpRes.WriteAsync(json)
                   .ContinueWith(t => httpRes.EndHttpHandlerRequest(skipHeaders: true)));
        }
        public override Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return(TypeConstants.EmptyTask);
            }

            var path = httpReq.PathInfo;

            string output;

            switch (Path.GetFileNameWithoutExtension(path))
            {
            //case "mini-profiler-jquery.1.6.2":
            //case "mini-profiler-jquery.tmpl.beta1":
            case "ssr-jquip.all":
            case "ssr-includes":
                output = Includes(httpReq, httpRes, path);
                break;

            case "ssr-results":
                output = Results(httpReq, httpRes);
                break;

            default:
                output = NotFound(httpRes);
                break;
            }

            return(httpRes.WriteAsync(output));
        }
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return;
            }
            if (textContents == null && bytes == null)
            {
                return;
            }

            httpRes.ContentType = contentType;

            if (textContents != null)
            {
                httpRes.Write(textContents);
            }
            else if (bytes != null)
            {
                httpRes.OutputStream.Write(bytes, 0, bytes.Length);
            }

            httpRes.Flush();
            httpRes.EndHttpHandlerRequest(skipHeaders: true);
        }
Exemple #4
0
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return;
            }

            Action(httpReq, httpRes);
        }
        public void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return;
            }

            Action(httpReq, httpRes);
            //httpRes.EndHttpHandlerRequest(skipHeaders:true);
        }
Exemple #6
0
        public override async Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return;
            }

            await Action(httpReq, httpRes);

            httpRes.EndHttpHandlerRequest(skipHeaders: true);
        }
Exemple #7
0
        public override async Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return;
            }

            httpRes.ContentType = "text/html; charset=utf-8";
            await ProcessOperationsAsync(httpRes.OutputStream, httpReq, httpRes).ConfigAwait();

            await httpRes.EndHttpHandlerRequestAsync(skipHeaders : true);
        }
Exemple #8
0
        public override Task ProcessRequestAsync(IRequest req, IResponse res, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(req, res))
            {
                return(TypeConstants.EmptyTask);
            }

            res.ApplyGlobalResponseHeaders();

            var serverEvents = req.TryResolve <IServerEvents>();

            serverEvents.RemoveExpiredSubscriptions();

            var feature = HostContext.GetPlugin <ServerEventsFeature>();

            if (feature.OnHeartbeatInit != null)
            {
                feature.OnHeartbeatInit(req);
            }

            if (req.Response.IsClosed)
            {
                return(TypeConstants.EmptyTask);
            }

            var subscriptionId = req.QueryString["id"];
            var subscription   = serverEvents.GetSubscriptionInfo(subscriptionId);

            if (subscription == null)
            {
                res.StatusCode        = 404;
                res.StatusDescription = ErrorMessages.SubscriptionNotExistsFmt.Fmt(subscriptionId);
                res.EndHttpHandlerRequest(skipHeaders: true);
                return(TypeConstants.EmptyTask);
            }

            if (!feature.CanAccessSubscription(req, subscription))
            {
                res.StatusCode        = 403;
                res.StatusDescription = "Invalid User Address";
                res.EndHttpHandlerRequest(skipHeaders: true);
                return(TypeConstants.EmptyTask);
            }

            if (!serverEvents.Pulse(subscriptionId))
            {
                res.StatusCode        = 404;
                res.StatusDescription = "Subscription {0} does not exist".Fmt(subscriptionId);
            }
            res.EndHttpHandlerRequest(skipHeaders: true);
            return(TypeConstants.EmptyTask);
        }
        public override Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return(TypeConstants.EmptyTask);
            }

            if (!AssertAccess(httpReq, httpRes, httpReq.QueryString["op"]))
            {
                return(TypeConstants.EmptyTask);
            }


            if (httpReq.QueryString["xsd"] != null)
            {
#if !NETSTANDARD2_0
                var operationTypes = HostContext.Metadata.GetAllSoapOperationTypes();
                var xsdNo          = Convert.ToInt32(httpReq.QueryString["xsd"]);
                var schemaSet      = XsdUtils.GetXmlSchemaSet(operationTypes);
                var schemas        = schemaSet.Schemas();
                var i = 0;
                if (xsdNo >= schemas.Count)
                {
                    throw new ArgumentOutOfRangeException("xsd");
                }

                httpRes.ContentType = "text/xml";
                foreach (XmlSchema schema in schemaSet.Schemas())
                {
                    if (xsdNo != i++)
                    {
                        continue;
                    }
                    schema.Write(httpRes.OutputStream);
                    break;
                }
#endif
            }
            else
            {
                using (var sw = new StreamWriter(httpRes.OutputStream))
                {
                    var writer = new HtmlTextWriter(sw);
                    httpRes.ContentType = "text/html; charset=utf-8";
                    ProcessOperations(writer, httpReq, httpRes);
                }
            }

            httpRes.EndHttpHandlerRequest(skipHeaders: true);

            return(TypeConstants.EmptyTask);
        }
Exemple #10
0
        /// <summary>
        /// This is called by the hosting environment via CatchAll usually for content pages.
        /// </summary>
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes);
            if (httpRes.IsClosed)
            {
                return;
            }

            httpRes.ContentType = MimeTypes.Html;

            ResolveAndExecuteRazorPage(httpReq, httpRes, null);
            httpRes.EndRequest(skipHeaders: true);
        }
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return;
            }

            using (var sw = new StreamWriter(httpRes.OutputStream))
            {
                var writer = new HtmlTextWriter(sw);
                httpRes.ContentType = "text/html";
                ProcessOperations(writer, httpReq, httpRes);
            }
        }
Exemple #12
0
        public override Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return(TypeConstants.EmptyTask);
            }

            httpRes.ContentType = "text/html; charset=utf-8";
            ProcessOperations(httpRes.OutputStream, httpReq, httpRes);

            httpRes.EndHttpHandlerRequest(skipHeaders: true);

            return(TypeConstants.EmptyTask);
        }
        public override async Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return;
            }

            if (!AssertAccess(httpReq, httpRes, httpReq.QueryString["op"]))
            {
                return;
            }


            if (httpReq.QueryString["xsd"] != null)
            {
#if !NETCORE
                var operationTypes = HostContext.Metadata.GetAllSoapOperationTypes();
                var xsdNo          = Convert.ToInt32(httpReq.QueryString["xsd"]);
                var schemaSet      = XsdUtils.GetXmlSchemaSet(operationTypes);
                var schemas        = schemaSet.Schemas();
                var i = 0;
                if (xsdNo >= schemas.Count)
                {
                    throw new ArgumentOutOfRangeException("xsd");
                }

                httpRes.ContentType = "text/xml";
                foreach (XmlSchema schema in schemaSet.Schemas())
                {
                    if (xsdNo != i++)
                    {
                        continue;
                    }
                    schema.Write(httpRes.AllowSyncIO().OutputStream);
                    break;
                }
#endif
            }
            else
            {
                httpRes.ContentType = "text/html; charset=utf-8";
                await ProcessOperationsAsync(httpRes.OutputStream, httpReq, httpRes).ConfigAwait();
            }

            await httpRes.EndHttpHandlerRequestAsync(skipHeaders : true).ConfigAwait();
        }
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return;
            }

            if (!AssertAccess(httpReq, httpRes, httpReq.QueryString["op"]))
            {
                return;
            }

            var operationTypes = HostContext.Metadata.GetAllTypes();

            if (httpReq.QueryString["xsd"] != null)
            {
                var xsdNo     = Convert.ToInt32(httpReq.QueryString["xsd"]);
                var schemaSet = XsdUtils.GetXmlSchemaSet(operationTypes);
                var schemas   = schemaSet.Schemas();
                var i         = 0;
                if (xsdNo >= schemas.Count)
                {
                    throw new ArgumentOutOfRangeException("xsd");
                }
                httpRes.ContentType = "text/xml";
                foreach (XmlSchema schema in schemaSet.Schemas())
                {
                    if (xsdNo != i++)
                    {
                        continue;
                    }
                    schema.Write(httpRes.OutputStream);
                    break;
                }
                return;
            }

            using (var sw = new StreamWriter(httpRes.OutputStream))
            {
                var writer = new HtmlTextWriter(sw);
                httpRes.ContentType = "text/html";
                ProcessOperations(writer, httpReq, httpRes);
            }
        }
Exemple #15
0
        /// <summary>
        /// This is called by the hosting environment via CatchAll usually for content pages.
        /// </summary>
        public override Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes);
            if (httpRes.IsClosed)
            {
                return(TypeConstants.EmptyTask);
            }

            httpRes.ContentType = MimeTypes.Html;

            var contentPage = ResolveContentPage(httpReq);

            using (ExecuteRazorPage(httpReq, httpRes.OutputStream, null, contentPage))
            {
                httpRes.EndRequest(skipHeaders: true);
            }

            return(TypeConstants.EmptyTask);
        }
Exemple #16
0
        public override async Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return;
            }

            Filter?.Invoke(httpReq);

            httpRes.ContentType = MimeTypes.Html;
            if (RazorFormat == null)
            {
                RazorFormat = RazorFormat.Instance;
            }

            var contentPage = RazorPage ?? RazorFormat.GetContentPage(PathInfo);

            if (contentPage == null)
            {
                httpRes.StatusCode = (int)HttpStatusCode.NotFound;
                httpRes.EndHttpHandlerRequest();
                return;
            }

            var model = Model;

            if (model == null)
            {
                httpReq.Items.TryGetValue("Model", out model);
            }
            if (model == null)
            {
                var modelType = RazorPage?.ModelType;
                model = modelType == null || modelType == typeof(DynamicRequestObject)
                    ? null
                    : await DeserializeHttpRequestAsync(modelType, httpReq, httpReq.ContentType);
            }

            using (RazorFormat.ProcessRazorPage(httpReq, contentPage, model, httpRes))
            {
                httpRes.EndHttpHandlerRequest(skipHeaders: true);
            }
        }
Exemple #17
0
        public override async Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            if (Action == null)
            {
                throw new Exception("Action was not supplied to ActionHandler");
            }

            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return;
            }

            if (httpReq.OperationName == null)
            {
                httpReq.OperationName = RequestName;
            }

            var response = await Action(httpReq, httpRes);

            await httpRes.WriteToResponse(httpReq, response);
        }
Exemple #18
0
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes);
            if (httpRes.IsClosed)
            {
                return;
            }

            httpRes.ContentType = MimeTypes.Html;
            if (RazorFormat == null)
            {
                RazorFormat = RazorFormat.Instance;
            }

            var contentPage = RazorPage ?? RazorFormat.FindByPathInfo(PathInfo);

            if (contentPage == null)
            {
                httpRes.StatusCode = (int)HttpStatusCode.NotFound;
                httpRes.EndHttpHandlerRequest();
                return;
            }

            var model = Model;

            if (model == null)
            {
                httpReq.Items.TryGetValue("Model", out model);
            }
            if (model == null)
            {
                var modelType = RazorPage != null ? RazorPage.ModelType : null;
                model = modelType == null || modelType == typeof(DynamicRequestObject)
                    ? null
                    : DeserializeHttpRequest(modelType, httpReq, httpReq.ContentType);
            }

            RazorFormat.ProcessRazorPage(httpReq, contentPage, model, httpRes);
        }
Exemple #19
0
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes);
            if (httpRes.IsClosed)
            {
                return;
            }

            if (MarkdownFormat == null)
            {
                MarkdownFormat = MarkdownFormat.Instance;
            }

            var contentPage = MarkdownPage ?? MarkdownFormat.FindByPathInfo(PathInfo);

            if (contentPage == null)
            {
                httpRes.StatusCode = (int)HttpStatusCode.NotFound;
                httpRes.EndHttpHandlerRequest();
                return;
            }

            MarkdownFormat.ReloadModifiedPageAndTemplates(contentPage);

            if (httpReq.DidReturn304NotModified(contentPage.GetLastModified(), httpRes))
            {
                return;
            }

            var model = Model;

            if (model == null)
            {
                httpReq.Items.TryGetValue("Model", out model);
            }

            MarkdownFormat.ProcessMarkdownPage(httpReq, contentPage, model, httpRes.OutputStream);
        }
Exemple #20
0
        public override Task ProcessRequestAsync(IRequest req, IResponse res, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(req, res))
            {
                return(TypeConstants.EmptyTask);
            }

            var feature = HostContext.GetPlugin <ServerEventsFeature>();

            var session = req.GetSession();

            if (feature.LimitToAuthenticatedUsers && !session.IsAuthenticated)
            {
                session.ReturnFailedAuthentication(req);
                return(TypeConstants.EmptyTask);
            }

            res.ContentType = MimeTypes.ServerSentEvents;
            res.AddHeader(HttpHeaders.CacheControl, "no-cache");
            res.ApplyGlobalResponseHeaders();
            res.UseBufferedStream = false;
            res.KeepAlive         = true;

            if (feature.OnInit != null)
            {
                feature.OnInit(req);
            }

            res.Flush();

            var serverEvents = req.TryResolve <IServerEvents>();
            var userAuthId   = session != null ? session.UserAuthId : null;
            var anonUserId   = serverEvents.GetNextSequence("anonUser");
            var userId       = userAuthId ?? ("-" + anonUserId);
            var displayName  = session.GetSafeDisplayName()
                               ?? "user" + anonUserId;

            var now            = DateTime.UtcNow;
            var subscriptionId = SessionExtensions.CreateRandomSessionId();

            //Handle both ?channel=A,B,C or ?channels=A,B,C
            var channels = new List <string>();
            var channel  = req.QueryString["channel"];

            if (!string.IsNullOrEmpty(channel))
            {
                channels.AddRange(channel.Split(','));
            }
            channel = req.QueryString["channels"];
            if (!string.IsNullOrEmpty(channel))
            {
                channels.AddRange(channel.Split(','));
            }

            if (channels.Count == 0)
            {
                channels = EventSubscription.UnknownChannel.ToList();
            }

            var subscription = new EventSubscription(res)
            {
                CreatedAt       = now,
                LastPulseAt     = now,
                Channels        = channels.ToArray(),
                SubscriptionId  = subscriptionId,
                UserId          = userId,
                UserName        = session != null ? session.UserName : null,
                DisplayName     = displayName,
                SessionId       = req.GetSessionId(),
                IsAuthenticated = session != null && session.IsAuthenticated,
                UserAddress     = req.UserHostAddress,
                OnPublish       = feature.OnPublish,
                //OnError = feature.OnError,
                Meta =
                {
                    { "userId",                           userId                                                                 },
                    { "displayName",                      displayName                                                            },
                    { "channels",                         string.Join(",", channels)                                             },
                    { AuthMetadataProvider.ProfileUrlKey, session.GetProfileUrl() ?? AuthMetadataProvider.DefaultNoProfileImgUrl },
                }
            };

            if (feature.OnCreated != null)
            {
                feature.OnCreated(subscription, req);
            }

            if (req.Response.IsClosed)
            {
                return(TypeConstants.EmptyTask); //Allow short-circuiting in OnCreated callback
            }
            var heartbeatUrl = feature.HeartbeatPath != null
                ? req.ResolveAbsoluteUrl("~/".CombineWith(feature.HeartbeatPath)).AddQueryParam("id", subscriptionId)
                : null;

            var unRegisterUrl = feature.UnRegisterPath != null
                ? req.ResolveAbsoluteUrl("~/".CombineWith(feature.UnRegisterPath)).AddQueryParam("id", subscriptionId)
                : null;

            heartbeatUrl  = AddSessionParamsIfAny(heartbeatUrl, req);
            unRegisterUrl = AddSessionParamsIfAny(unRegisterUrl, req);

            subscription.ConnectArgs = new Dictionary <string, string>(subscription.Meta)
            {
                { "id", subscriptionId },
                { "unRegisterUrl", unRegisterUrl },
                { "heartbeatUrl", heartbeatUrl },
                { "updateSubscriberUrl", req.ResolveAbsoluteUrl("~/event-subscribers/" + subscriptionId) },
                { "heartbeatIntervalMs", ((long)feature.HeartbeatInterval.TotalMilliseconds).ToString(CultureInfo.InvariantCulture) },
                { "idleTimeoutMs", ((long)feature.IdleTimeout.TotalMilliseconds).ToString(CultureInfo.InvariantCulture) }
            };

            if (feature.OnConnect != null)
            {
                feature.OnConnect(subscription, subscription.ConnectArgs);
            }

            serverEvents.Register(subscription, subscription.ConnectArgs);

            var tcs = new TaskCompletionSource <bool>();

            subscription.OnDispose = _ =>
            {
                try
                {
                    res.EndHttpHandlerRequest(skipHeaders: true);
                }
                catch { }
                tcs.SetResult(true);
            };

            return(tcs.Task);
        }
Exemple #21
0
        public override void ProcessRequest(IRequest request, IResponse response, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(request, response);
            if (response.IsClosed)
            {
                return;
            }

            response.EndHttpHandlerRequest(skipClose: true, afterHeaders: r =>
            {
                var node = this.VirtualNode ?? request.GetVirtualNode();
                var file = node as IVirtualFile;
                if (file == null)
                {
                    var dir = node as IVirtualDirectory;
                    if (dir != null)
                    {
                        file = dir.GetDefaultDocument();
                        if (file != null && HostContext.Config.RedirectToDefaultDocuments)
                        {
                            r.Redirect(request.GetPathUrl() + '/' + file.Name);
                            return;
                        }
                    }

                    if (file == null)
                    {
                        var fileName         = request.PathInfo;
                        var originalFileName = fileName;

                        if (Env.IsMono)
                        {
                            //Create a case-insensitive file index of all host files
                            if (allFiles == null)
                            {
                                allFiles = CreateFileIndex(HostContext.VirtualPathProvider.RootDirectory.RealPath);
                            }
                            if (allDirs == null)
                            {
                                allDirs = CreateDirIndex(HostContext.VirtualPathProvider.RootDirectory.RealPath);
                            }

                            if (allFiles.TryGetValue(fileName.ToLower(), out fileName))
                            {
                                file = HostContext.VirtualPathProvider.GetFile(fileName);
                            }
                        }

                        if (file == null)
                        {
                            var msg = ErrorMessages.FileNotExistsFmt.Fmt(request.PathInfo);
                            log.WarnFormat("{0} in path: {1}", msg, originalFileName);
                            response.StatusCode        = 404;
                            response.StatusDescription = msg;
                            return;
                        }
                    }
                }

                file.Refresh(); //refresh FileInfo, DateModified, Length

                TimeSpan maxAge;
                if (r.ContentType != null && HostContext.Config.AddMaxAgeForStaticMimeTypes.TryGetValue(r.ContentType, out maxAge))
                {
                    r.AddHeader(HttpHeaders.CacheControl, "max-age=" + maxAge.TotalSeconds);
                }

                if (request.HasNotModifiedSince(file.LastModified))
                {
                    r.ContentType = MimeTypes.GetMimeType(file.Name);
                    r.StatusCode  = 304;
                    return;
                }

                try
                {
                    r.AddHeaderLastModified(file.LastModified);
                    r.ContentType = MimeTypes.GetMimeType(file.Name);

                    if (ResponseFilter != null)
                    {
                        ResponseFilter(request, r, file);

                        if (r.IsClosed)
                        {
                            return;
                        }
                    }

                    if (file.VirtualPath.EqualsIgnoreCase(DefaultFilePath))
                    {
                        if (file.LastModified > DefaultFileModified)
                        {
                            SetDefaultFile(DefaultFilePath, file.ReadAllBytes(), file.LastModified); //reload
                        }
                        r.OutputStream.Write(DefaultFileContents, 0, DefaultFileContents.Length);
                        r.Close();
                        return;
                    }

                    if (HostContext.Config.AllowPartialResponses)
                    {
                        r.AddHeader(HttpHeaders.AcceptRanges, "bytes");
                    }
                    long contentLength = file.Length;
                    long rangeStart, rangeEnd;
                    var rangeHeader = request.Headers[HttpHeaders.Range];
                    if (HostContext.Config.AllowPartialResponses && rangeHeader != null)
                    {
                        rangeHeader.ExtractHttpRanges(contentLength, out rangeStart, out rangeEnd);

                        if (rangeEnd > contentLength - 1)
                        {
                            rangeEnd = contentLength - 1;
                        }

                        r.AddHttpRangeResponseHeaders(rangeStart: rangeStart, rangeEnd: rangeEnd, contentLength: contentLength);
                    }
                    else
                    {
                        rangeStart = 0;
                        rangeEnd   = contentLength - 1;
                        r.SetContentLength(contentLength); //throws with ASP.NET webdev server non-IIS pipelined mode
                    }
                    var outputStream = r.OutputStream;
                    using (var fs = file.OpenRead())
                    {
                        if (rangeStart != 0 || rangeEnd != file.Length - 1)
                        {
                            fs.WritePartialTo(outputStream, rangeStart, rangeEnd);
                        }
                        else
                        {
                            fs.CopyTo(outputStream, BufferSize);
                            outputStream.Flush();
                        }
                    }
                }
                catch (System.Net.HttpListenerException ex)
                {
                    if (ex.ErrorCode == 1229)
                    {
                        return;
                    }
                    //Error: 1229 is "An operation was attempted on a nonexistent network connection"
                    //This exception occures when http stream is terminated by web browser because user
                    //seek video forward and new http request will be sent by browser
                    //with attribute in header "Range: bytes=newSeekPosition-"
                    throw;
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("Static file {0} forbidden: {1}", request.PathInfo, ex.Message);
                    throw new HttpException(403, "Forbidden.");
                }
            });
        }
        public override async Task ProcessRequestAsync(IRequest request, IResponse response, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(request, response);
            if (response.IsClosed)
            {
                return;
            }

            await response.EndHttpHandlerRequestAsync(afterHeaders : async r =>
            {
                var node = this.VirtualNode ?? request.GetVirtualNode();
                var file = node as IVirtualFile;
                if (file == null)
                {
                    if (node is IVirtualDirectory dir)
                    {
                        file = dir.GetDefaultDocument(HostContext.AppHost.Config.DefaultDocuments);
                        if (file != null && HostContext.Config.RedirectToDefaultDocuments)
                        {
                            r.Redirect(request.GetPathUrl() + '/' + file.Name);
                            return;
                        }
                    }

                    if (file == null)
                    {
                        var fileName         = request.PathInfo;
                        var originalFileName = fileName;

                        if (Env.IsMono)
                        {
                            //Create a case-insensitive file index of all host files
                            if (allFiles == null)
                            {
                                allFiles = CreateFileIndex(HostContext.VirtualFileSources.RootDirectory.RealPath);
                            }
                            if (allDirs == null)
                            {
                                allDirs = CreateDirIndex(HostContext.VirtualFileSources.RootDirectory.RealPath);
                            }

                            if (allFiles.TryGetValue(fileName.ToLower(), out fileName))
                            {
                                file = HostContext.VirtualFileSources.GetFile(fileName);
                            }
                        }

                        if (file == null)
                        {
                            var msg = ErrorMessages.FileNotExistsFmt.Fmt(request.PathInfo.SafeInput());
                            log.Warn($"{msg} in path: {originalFileName}");
                            response.StatusCode        = 404;
                            response.StatusDescription = msg;
                            return;
                        }
                    }
                }

                file.Refresh(); //refresh FileInfo, DateModified, Length

                TimeSpan maxAge;
                if (r.ContentType != null && HostContext.Config.AddMaxAgeForStaticMimeTypes.TryGetValue(r.ContentType, out maxAge))
                {
                    r.AddHeader(HttpHeaders.CacheControl, "max-age=" + maxAge.TotalSeconds);
                }

                if (request.HasNotModifiedSince(file.LastModified))
                {
                    r.ContentType       = MimeTypes.GetMimeType(file.Name);
                    r.StatusCode        = (int)HttpStatusCode.NotModified;
                    r.StatusDescription = HttpStatusCode.NotModified.ToString();
                    return;
                }

                try
                {
                    var encoding       = request.GetCompressionType();
                    var shouldCompress = encoding != null && HostContext.AppHost.ShouldCompressFile(file);
                    r.AddHeaderLastModified(file.LastModified);
                    r.ContentType = MimeTypes.GetMimeType(file.Name);

                    if (ResponseFilter != null)
                    {
                        ResponseFilter(request, r, file);

                        if (r.IsClosed)
                        {
                            return;
                        }
                    }

                    if (!HostContext.DebugMode && file.VirtualPath.EqualsIgnoreCase(DefaultFilePath))
                    {
                        if (file.LastModified > DefaultFileModified)
                        {
                            SetDefaultFile(DefaultFilePath, file.ReadAllBytes(), file.LastModified); //reload
                        }
                        if (!shouldCompress)
                        {
                            await r.OutputStream.WriteAsync(DefaultFileContents);
                            await r.OutputStream.FlushAsync();
                        }
                        else
                        {
                            byte[] zipBytes = null;
                            if (encoding == CompressionTypes.GZip)
                            {
                                zipBytes = DefaultFileContentsGzip ??
                                           (DefaultFileContentsGzip = DefaultFileContents.CompressBytes(encoding));
                            }
                            else if (encoding == CompressionTypes.Deflate)
                            {
                                zipBytes = DefaultFileContentsDeflate ??
                                           (DefaultFileContentsDeflate = DefaultFileContents.CompressBytes(encoding));
                            }
                            else
                            {
                                zipBytes = DefaultFileContents.CompressBytes(encoding);
                            }
                            r.AddHeader(HttpHeaders.ContentEncoding, encoding);
                            r.SetContentLength(zipBytes.Length);
                            await r.OutputStream.WriteAsync(zipBytes);
                            await r.OutputStream.FlushAsync();
                        }

                        r.Close();
                        return;
                    }

                    if (HostContext.Config.AllowPartialResponses)
                    {
                        r.AddHeader(HttpHeaders.AcceptRanges, "bytes");
                    }
                    long contentLength = file.Length;
                    long rangeStart, rangeEnd;
                    var rangeHeader = request.Headers[HttpHeaders.Range];
                    if (HostContext.Config.AllowPartialResponses && rangeHeader != null)
                    {
                        rangeHeader.ExtractHttpRanges(contentLength, out rangeStart, out rangeEnd);

                        if (rangeEnd > contentLength - 1)
                        {
                            rangeEnd = contentLength - 1;
                        }

                        r.AddHttpRangeResponseHeaders(rangeStart: rangeStart, rangeEnd: rangeEnd, contentLength: contentLength);
                    }
                    else
                    {
                        rangeStart = 0;
                        rangeEnd   = contentLength - 1;
                    }
                    var outputStream = r.OutputStream;
                    using (var fs = file.OpenRead())
                    {
                        if (rangeStart != 0 || rangeEnd != file.Length - 1)
                        {
                            await fs.WritePartialToAsync(outputStream, rangeStart, rangeEnd);
                        }
                        else
                        {
                            if (!shouldCompress)
                            {
                                r.SetContentLength(contentLength);
                                await fs.CopyToAsync(outputStream, BufferSize);
                                outputStream.Flush();
                            }
                            else
                            {
                                r.AddHeader(HttpHeaders.ContentEncoding, encoding);
                                outputStream = outputStream.CompressStream(encoding);
                                await fs.CopyToAsync(outputStream);
                                await outputStream.FlushAsync();
                                outputStream.Close();
                            }
                        }
                    }
                }
#if !NETSTANDARD2_0
                catch (System.Net.HttpListenerException ex)
                {
                    if (ex.ErrorCode == 1229)
                    {
                        return;
                    }
                    //Error: 1229 is "An operation was attempted on a nonexistent network connection"
                    //This exception occures when http stream is terminated by web browser because user
                    //seek video forward and new http request will be sent by browser
                    //with attribute in header "Range: bytes=newSeekPosition-"
                    throw;
                }
#endif
                catch (Exception ex)
                {
                    log.ErrorFormat($"Static file {request.PathInfo} forbidden: {ex.Message}");
                    throw new HttpException(403, "Forbidden.");
                }
            });
        }
Exemple #23
0
        protected Message ExecuteMessage(Message message, RequestAttributes requestAttributes, IRequest httpReq, IResponse httpRes)
        {
            var soapFeature = requestAttributes.ToSoapFeature();

            appHost.AssertFeatures(soapFeature);

            if (httpReq == null)
            {
                httpReq = HostContext.GetCurrentRequest();
            }

            if (httpRes == null && httpReq != null)
            {
                httpRes = httpReq.Response;
            }

            if (httpReq == null)
            {
                throw new ArgumentNullException(nameof(httpReq));
            }

            if (httpRes == null)
            {
                throw new ArgumentNullException(nameof(httpRes));
            }

            httpReq.UseBufferedStream = true;
            var requestMsg = message ?? GetRequestMessageFromStream(httpReq.InputStream);

            var soapAction = httpReq.GetHeader(HttpHeaders.SOAPAction)
                             ?? GetAction(requestMsg);

            if (soapAction != null)
            {
                httpReq.OperationName = soapAction.Trim('"');
            }

            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return(PrepareEmptyResponse(message, httpReq));
            }

            string requestXml  = GetRequestXml(requestMsg);
            var    requestType = GetRequestType(requestMsg, requestXml);

            httpReq.OperationName = requestType.GetOperationName();
            if (!HostContext.Metadata.CanAccess(requestAttributes, soapFeature.ToFormat(), requestType.GetOperationName()))
            {
                throw HostContext.UnauthorizedAccess(requestAttributes);
            }

            try
            {
                var useXmlSerializerRequest = requestType.HasAttribute <XmlSerializerFormatAttribute>();

                var request = appHost.ApplyRequestConvertersAsync(httpReq,
                                                                  useXmlSerializerRequest
                        ? XmlSerializableSerializer.Instance.DeserializeFromString(requestXml, requestType)
                        : Serialization.DataContractSerializer.Instance.DeserializeFromString(requestXml, requestType)
                                                                  ).Result;

                httpReq.Dto = request;

                if (request is IRequiresSoapMessage requiresSoapMessage)
                {
                    requiresSoapMessage.Message = requestMsg;
                }

                httpReq.SetItem(Keywords.SoapMessage, requestMsg);

                httpRes.ContentType = GetSoapContentType(httpReq.ContentType);

                var hasRequestFilters = HostContext.AppHost.GlobalRequestFiltersArray.Length > 0 ||
                                        HostContext.AppHost.GlobalRequestFiltersAsyncArray.Length > 0 ||
                                        FilterAttributeCache.GetRequestFilterAttributes(request.GetType()).Any();

                if (hasRequestFilters)
                {
                    HostContext.ApplyRequestFiltersAsync(httpReq, httpRes, request).Wait();
                    if (httpRes.IsClosed)
                    {
                        return(EmptyResponse(requestMsg, requestType));
                    }
                }

                httpReq.RequestAttributes |= requestAttributes;
                var response = ExecuteService(request, httpReq);

                if (response is Task taskResponse)
                {
                    response = taskResponse.GetResult();
                }

                response = appHost.ApplyResponseConvertersAsync(httpReq, response).Result;

                appHost.ApplyResponseFiltersAsync(httpReq, httpRes, response).Wait();
                if (httpRes.IsClosed)
                {
                    return(EmptyResponse(requestMsg, requestType));
                }

                var httpResult = response as IHttpResult;
                if (httpResult != null)
                {
                    response = httpResult.Response;
                }

                var noMsgAction = requestMsg.Headers.Action == null;
                var responseMsg = CreateResponseMessage(response, requestMsg.Version, requestType, noMsgAction);

                if (httpResult != null)
                {
                    SetErrorStatusIfAny(httpReq.Response, responseMsg, httpResult.Status);
                }

                return(responseMsg);
            }
            catch (Exception ex)
            {
                if (httpReq.Dto != null)
                {
                    HostContext.RaiseServiceException(httpReq, httpReq.Dto, ex).Wait();
                }
                else
                {
                    HostContext.RaiseUncaughtException(httpReq, httpRes, httpReq.OperationName, ex).Wait();
                }

                throw new SerializationException("3) Error trying to deserialize requestType: "
                                                 + requestType
                                                 + ", xml body: " + requestXml, ex);
            }
        }