/// <summary>
		/// Non ASP.NET requests
		/// </summary>
		/// <param name="request"></param>
		/// <param name="response"></param>
		/// <param name="operationName"></param>
		public void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName)
		{
			if (string.IsNullOrEmpty(RelativeUrl) && string.IsNullOrEmpty(AbsoluteUrl))
				throw new ArgumentNullException("RelativeUrl or AbsoluteUrl");

			if (!string.IsNullOrEmpty(AbsoluteUrl))
			{
				response.StatusCode = (int)HttpStatusCode.Redirect;
				response.AddHeader(HttpHeaders.Location, this.AbsoluteUrl);
			}
			else
			{
                var absoluteUrl = request.GetApplicationUrl();
                if (!string.IsNullOrEmpty(RelativeUrl))
                {
                    if (this.RelativeUrl.StartsWith("/"))
                        absoluteUrl = absoluteUrl.CombineWith(this.RelativeUrl);
                    else if (this.RelativeUrl.StartsWith("~/"))
                        absoluteUrl = absoluteUrl.CombineWith(this.RelativeUrl.Replace("~/", ""));
                    else
                        absoluteUrl = request.AbsoluteUri.CombineWith(this.RelativeUrl);
                }
                response.StatusCode = (int)HttpStatusCode.Redirect;
				response.AddHeader(HttpHeaders.Location, absoluteUrl);
			}

            response.EndHttpRequest(skipClose:true);
        }
 public void ResponseFilter(IHttpRequest req, IHttpResponse res, object response)
 {
     if (!string.IsNullOrEmpty(allowedOrigins))
         res.AddHeader(HttpHeaders.AllowOrigin, allowedOrigins);
     if (!string.IsNullOrEmpty(allowedMethods))
         res.AddHeader(HttpHeaders.AllowMethods, allowedMethods);
     if (!string.IsNullOrEmpty(allowedHeaders))
         res.AddHeader(HttpHeaders.AllowHeaders, allowedHeaders);
     if (allowCredentials)
         res.AddHeader(HttpHeaders.AllowCredentials, "true");
 }
Esempio n. 3
0
        /// <summary>The request filter is executed before the service.</summary>
        ///
        /// <param name="req">       The http request wrapper.</param>
        /// <param name="res">       The http response wrapper.</param>
        /// <param name="requestDto">The request DTO.</param>
        public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (applyWhere != null && !applyWhere(req, requestDto))
                return;

            if (!string.IsNullOrEmpty(allowedOrigins))
                res.AddHeader(HttpHeaders.AllowOrigin, allowedOrigins);
            if (!string.IsNullOrEmpty(allowedMethods))
                res.AddHeader(HttpHeaders.AllowMethods, allowedMethods);
            if (!string.IsNullOrEmpty(allowedHeaders))
                res.AddHeader(HttpHeaders.AllowHeaders, allowedHeaders);
            if (allowCredentials)
                res.AddHeader(HttpHeaders.AllowCredentials, "true");
        }
        public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (!string.IsNullOrEmpty(allowedOrigins))
                res.AddHeader(HttpHeaders.AllowOrigin, allowedOrigins);
            if (!string.IsNullOrEmpty(allowedMethods))
                res.AddHeader(HttpHeaders.AllowMethods, allowedMethods);
            if (!string.IsNullOrEmpty(allowedHeaders))
                res.AddHeader(HttpHeaders.AllowHeaders, allowedHeaders);
            if (allowCredentials)
                res.AddHeader(HttpHeaders.AllowCredentials, "true");

            if (AutoHandleOptionRequests && req.HttpMethod == HttpMethods.Options)
                res.EndRequest();
        }
 public static void OpenSearchDescriptionSerializer(IRequestContext reqCtx, object res, IHttpResponse stream)
 {
     stream.AddHeader("Content-Encoding",Encoding.Default.EncodingName);
     using(XmlWriter writer = XmlWriter.Create(stream.OutputStream, new XmlWriterSettings() { OmitXmlDeclaration = false, Encoding = Encoding.Default }))
     {
         new System.Xml.Serialization.XmlSerializer(res.GetType()).Serialize(writer, res);
     }
 }
        /// <summary>
		/// Non ASP.NET requests
		/// </summary>
		public override void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName)
		{
			var defaultUrl = HostContext.Config.ServiceEndpointsMetadataConfig.DefaultMetadataUri;

			if (request.PathInfo == "/")
			{
				var relativeUrl = defaultUrl.Substring(defaultUrl.IndexOf('/'));
				var absoluteUrl = request.RawUrl.TrimEnd('/') + relativeUrl;
				response.StatusCode = (int) HttpStatusCode.Redirect;
				response.AddHeader(HttpHeaders.Location, absoluteUrl);
			}
			else
			{
				response.StatusCode = (int)HttpStatusCode.Redirect;
				response.AddHeader(HttpHeaders.Location, defaultUrl);
			}
		}
Esempio n. 7
0
        void OptionsHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            response.AddHeader("DAV", "2");
            response.AddHeader("MS-Author-Via", "DAV");

            //This now gets all the events that have handler from the dav listener
            string allowString = server.GetAvailableMethods();

            //Add this information to both, Public and Allow. We currently have no way of separating these two
            response.AddHeader("Public", allowString);
            response.AddHeader("Allow", allowString);

            //Preserving the old headers as reference. These should be removed when method is mature enough
            //response.AddHeader("Public", "COPY, DELETE, GET, HEAD, MKCOL, MOVE, OPTIONS, PROPFIND, PROPPATCH, PUT");
            //response.AddHeader("Allow", "COPY, DELETE, GET, HEAD, MKCOL, MOVE, OPTIONS, PROPFIND, PROPPATCH, PUT");

            server.HttpServer.LogWriter.Write(this, LogPrio.Debug, "Sending OPTIONS response for request to " + request.UriPath);
        }
        /// <summary>
        /// Non ASP.NET requests
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="operationName"></param>
        public void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName)
        {
            if (string.IsNullOrEmpty(RelativeUrl) && string.IsNullOrEmpty(AbsoluteUrl))
                throw new ArgumentNullException("RelativeUrl or AbsoluteUrl");

            if (!string.IsNullOrEmpty(AbsoluteUrl))
            {
                response.StatusCode = (int)HttpStatusCode.Redirect;
                response.AddHeader(HttpHeaders.Location, this.AbsoluteUrl);
            }
            else
            {
                var absoluteUrl = request.AbsoluteUri.WithTrailingSlash() + this.RelativeUrl;
                response.StatusCode = (int)HttpStatusCode.Redirect;
                response.AddHeader(HttpHeaders.Location, absoluteUrl);
            }
            response.Close();
        }
Esempio n. 9
0
        public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(Value)) return;

            if (Name.Equals(HttpHeaders.ContentType, StringComparison.InvariantCultureIgnoreCase))
            {
                res.ContentType = Value;
            }
            else
            {
                    res.AddHeader(Name, Value);
            }
        }
Esempio n. 10
0
        public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session)
        {
            _log.Write(this, LogPrio.Trace, String.Format("Begin handling Rack request for {0}", request.Uri));

            var rackRequest = request.ToRackRequest();
            var rackResponse = new RackResponse(response.Body);

            //this will write to the body. We may want to set headers first, so may need some thought.
            _rack.HandleRequest(rackRequest, rackResponse);

            response.Status = (HttpStatusCode)rackResponse.Status;
            foreach (var header in rackResponse.Headers)
                if (header.Key.ToLower() != "content-length")
                    response.AddHeader(header.Key, header.Value);

            _log.Write(this, LogPrio.Trace, String.Format("Finished handling Rack request for {0}", request.Uri));

            return true;
        }
        public void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName)
        {
            var resourceName = string.Concat(_assembly.GetName().Name, ".", _filePath.Replace('/', '.'));

            response.ContentType = MimeTypes.GetMimeType(_filePath);

            using(var stream = _assembly.GetManifestResourceStream(resourceName))
            {
                if (stream == null)
                {
                    response.StatusCode = (int)HttpStatusCode.NotFound;
                    response.Close();
                }
                else
                {
                    // TODO: Figure out the best way to enable browser caching of this static content.
                    response.AddHeader(HttpHeaders.CacheControl, "max-age=" + TimeSpan.FromDays(5).TotalSeconds);
                    response.SetContentLength(stream.Length);
                    stream.CopyTo(response.OutputStream);
                    response.OutputStream.Flush();
                }
            }
        }
Esempio n. 12
0
        public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            if (StatusCode != null)
            {
                res.StatusCode = StatusCode.Value;
            }

            if (StatusDescription != null)
            {
                res.StatusDescription = StatusDescription;
            }

            if (!string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Value))
            {
                if (Name.Equals(HttpHeaders.ContentType, StringComparison.InvariantCultureIgnoreCase))
                {
                    res.ContentType = Value;
                }
                else
                {
                    res.AddHeader(Name, Value);
                }
            }
        }
Esempio n. 13
0
        public void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName)
        {
            var fileName = request.GetPhysicalPath();

            var fi = new FileInfo(fileName);

            if (!fi.Exists)
            {
                if ((fi.Attributes & FileAttributes.Directory) != 0)
                {
                    foreach (var defaultDoc in EndpointHost.Config.DefaultDocuments)
                    {
                        var defaultFileName = Path.Combine(fi.FullName, defaultDoc);
                        var defaultFileInfo = new FileInfo(defaultFileName);
                        if (!defaultFileInfo.Exists)
                        {
                            continue;
                        }
                        response.Redirect(request.GetPathUrl() + '/' + defaultDoc);
                        return;
                    }
                }

                if (!fi.Exists)
                {
                    throw new HttpException(404, "File '" + request.PathInfo + "' not found.");
                }
            }


            var strHeader = request.Headers["If-Modified-Since"];

            try
            {
                if (strHeader != null)
                {
                    var dtIfModifiedSince = DateTime.ParseExact(strHeader, "r", null);
                    var ftime             = fi.LastWriteTime.ToUniversalTime();
                    if (ftime <= dtIfModifiedSince)
                    {
                        response.ContentType = MimeTypes.GetMimeType(fileName);
                        response.StatusCode  = 304;
                        return;
                    }
                }
            }
            catch { }

            try
            {
                var lastWT = fi.LastWriteTime.ToUniversalTime();
                response.AddHeader("Last-Modified", lastWT.ToString("r"));

                response.ContentType = MimeTypes.GetMimeType(fileName);

                if (!Env.IsMono)
                {
                    response.TransmitFile(fileName);
                }
                else
                {
                    response.WriteFile(fileName);
                }
            }
            catch (Exception)
            {
                throw new HttpException(403, "Forbidden.");
            }
        }
        /// <summary>
        /// Writes to response.
        ///
        /// Response headers are customizable by implementing IHasOptions an returning Dictionary of Http headers.
        ///
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="result">Whether or not it was implicity handled by ServiceStack's built-in handlers.</param>
        /// <param name="defaultAction">The default action.</param>
        /// <param name="defaultContentType">Default response ContentType.</param>
        /// <returns></returns>
        public static bool WriteToResponse(this IHttpResponse response, object result, Func <object, string> defaultAction, string defaultContentType)
        {
            try
            {
                if (result == null)
                {
                    return(true);
                }

                foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders)
                {
                    response.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value);
                }

                /* Mono Error: Exception: Method not found: 'System.Web.HttpResponse.get_Headers' */
                var responseOptions = result as IHasOptions;
                if (responseOptions != null)
                {
                    //Reserving options with keys in the format 'xx.xxx' (No Http headers contain a '.' so its a safe restriction)
                    const string reservedOptions = ".";

                    foreach (var responseHeaders in responseOptions.Options)
                    {
                        if (responseHeaders.Key.Contains(reservedOptions))
                        {
                            continue;
                        }

                        if (ContentType.HeaderContentType.Equals(responseHeaders.Key, StringComparison.InvariantCultureIgnoreCase))
                        {
                            response.ContentType = responseHeaders.Value;
                        }
                        else
                        {
                            Log.DebugFormat("Setting Custom HTTP Header: {0}: {1}", responseHeaders.Key, responseHeaders.Value);
                            response.AddHeader(responseHeaders.Key, responseHeaders.Value);
                        }
                    }
                }

                if (WriteToOutputStream(response.OutputStream, result))
                {
                    return(true);
                }

                var responseText = result as string;
                if (responseText != null)
                {
                    WriteTextToResponse(response, responseText, defaultContentType);
                    return(true);
                }

                if (defaultAction == null)
                {
                    throw new ArgumentNullException("defaultAction", string.Format(
                                                        "As result '{0}' is not a supported responseType, a defaultAction must be supplied",
                                                        result.GetType().Name));
                }

                WriteTextToResponse(response, defaultAction(result), defaultContentType);
                return(false);
            }
            catch (Exception ex)
            {
                var errorMessage = string.Format("Error occured while Processing Request: {0}", ex.Message);
                Log.Error(errorMessage, ex);

                var operationName = result != null
                                        ? result.GetType().Name.Replace("Response", "")
                                        : "OperationName";

                response.WriteErrorToResponse(defaultContentType, operationName, errorMessage, ex);
                return(true);
            }
            finally
            {
                //Both seem to throw an exception??
                //Do not use response.Close(); does not have the same effect
                //response.End();
            }
        }
        /// <summary>
        /// Writes to response.
        /// Response headers are customizable by implementing IHasOptions an returning Dictionary of Http headers.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="result">Whether or not it was implicity handled by ServiceStack's built-in handlers.</param>
        /// <param name="defaultAction">The default action.</param>
        /// <param name="serializerCtx">The serialization context.</param>
        /// <param name="bodyPrefix">Add prefix to response body if any</param>
        /// <param name="bodySuffix">Add suffix to response body if any</param>
        /// <returns></returns>
        public static bool WriteToResponse(this IHttpResponse response, IHttpRequest request, object result, ResponseSerializerDelegate defaultAction, IRequestContext serializerCtx, byte[] bodyPrefix, byte[] bodySuffix)
        {
            var defaultContentType = serializerCtx.ResponseContentType;
            AckCodeType ack = AckCodeType.Success;
            bool completed = true;
            try
            {
                if (result == null)
                {
                    response.EndRequestWithNoContent();
                    return true;
                }

                ApplyGlobalResponseHeaders(response);

                /* Mono Error: Exception: Method not found: 'System.Web.HttpResponse.get_Headers' */
                var responseOptions = result as IHasOptions;
                if (responseOptions != null)
                {
                    //Reserving options with keys in the format 'xx.xxx' (No Http headers contain a '.' so its a safe restriction)
                    const string reservedOptions = ".";

                    foreach (var responseHeaders in responseOptions.Options)
                    {
                        if (responseHeaders.Key.Contains(reservedOptions)) continue;

                        Log.Debug(string.Format("Setting Custom HTTP Header: {0}: {1}", responseHeaders.Key, responseHeaders.Value),
                            new Dictionary<string, string>() 
                            {
                                {"ErrorCode", "FXD300061"}
                            });
                        response.AddHeader(responseHeaders.Key, responseHeaders.Value);
                    }
                }

                var disposableResult = result as IDisposable;

                //ContentType='text/html' is the default for a HttpResponse
                //Do not override if another has been set
                if (response.ContentType == null || response.ContentType == ContentType.Html)
                {
                    response.ContentType = defaultContentType;
                }
                if (bodyPrefix != null && response.ContentType.IndexOf(ContentType.Json, StringComparison.InvariantCultureIgnoreCase) >= 0)
                {
                    response.ContentType = ContentType.JavaScript;
                }

                if (EndpointHost.Config.AppendUtf8CharsetOnContentTypes.Contains(response.ContentType))
                {
                    response.ContentType += ContentType.Utf8Suffix;
                }

                var responseText = result as string;
                if (responseText != null)
                {
                    if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length);
                    WriteTextToResponse(response, responseText, defaultContentType);
                    if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length);
                    return true;
                }

                var commonResponseDto = result as IHasResponseStatus;
                if (commonResponseDto != null)
                {
                    // defensive programming
                    if (commonResponseDto.ResponseStatus == null)
                    {
                        commonResponseDto.ResponseStatus = new ResponseStatusType();
                    }
                    commonResponseDto.ResponseStatus.Timestamp = DateTime.Now;
                    // TODO add version

                    // post ack check, in case developer forget to set ack according to error status 
                    bool hasError = false;
                    if (commonResponseDto.ResponseStatus.Ack == AckCodeType.Success && commonResponseDto.ResponseStatus.Errors.Count > 0)
                    {
                        foreach (ErrorDataType error in commonResponseDto.ResponseStatus.Errors)
                        {
                            if (error.SeverityCode == SeverityCodeType.Error)
                            {
                                hasError = true;
                                break;
                            }
                        }
                        if (hasError)
                        {
                            commonResponseDto.ResponseStatus.Ack = AckCodeType.Failure;
                        }
                    }

                    ack = commonResponseDto.ResponseStatus.Ack;

                    AddRequestInfoToResponseStatus(serializerCtx.Get<IHttpRequest>(), commonResponseDto);
                }

                // Defensive programming, in normal case, we should not see GenericErrorResponseType here
                // In case any exception, we set http status code to trigger SOA C# client side WebServiceException
                var genericErrorResponseDto = result as GenericErrorResponseType;
                if (genericErrorResponseDto != null)
                {
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    ack = AckCodeType.Failure;
                }

                if (defaultAction == null)
                {
                    throw new ArgumentNullException("defaultAction", String.Format(
                    "As result '{0}' is not a supported responseType, a defaultAction must be supplied",
                    (result != null ? result.GetType().Name : "")));
                }

                if (EndpointHost.Config.ServiceManager.MetadataMap[request.ServicePath].UseChunkedTransferEncoding)
                {
                    response.AddHeader(ServiceUtils.ResponseStatusHttpHeaderKey, ack.ToString());
                    response.UseChunkedTransferEncoding();
                }

                if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length);
                if (result != null)
                {
                    try
                    {
                        defaultAction(serializerCtx, result, response);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                       //response.SerializationTimeInMillis = serializeTransaction.Transaction.DurationInMillis;
                    }
                }
                if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length);
                
                // Record response size
                response.ExecutionResult.ResponseSize = response.OutputStream.Length;

                if (disposableResult != null) disposableResult.Dispose();

                return false;
            }
            catch (Exception originalEx)
            {
                ack = AckCodeType.Failure;

                bool usedChunkedTransferEncoding = response.UsedChunkedTransferEncoding();
                var errorMessage = string.Format("Error occured while {0}: [{1}] {2}",
                    usedChunkedTransferEncoding ? "using chunked transfer encoding" : "processing request", originalEx.GetType().Name, originalEx.Message);
                Log.Error(errorMessage, originalEx, new Dictionary<string, string>(){ { "ErrorCode", "FXD300010" } });

                //TM: It would be good to handle 'remote end dropped connection' problems here. Arguably they should at least be suppressible via configuration

                //DB: Using standard ServiceStack configuration method

                if (!EndpointHost.Config.WriteErrorsToResponse)
                {
                    completed = false;
                    throw;
                }

                if (response.IsClosed)
                    return true;
                
                if (usedChunkedTransferEncoding)
                    return true;

                try
                {
                    response.WriteErrorToResponse(serializerCtx.Get<IHttpRequest>(), defaultContentType, originalEx);
                    return true;
                }
                catch (Exception writeErrorEx)
                {
                    //Exception in writing to response should not hide the original exception
                    Log.Error("Failed to write error to response: " + writeErrorEx.Message, writeErrorEx, new Dictionary<string, string>(){ { "ErrorCode", "FXD300010" } });
                    completed = false;
                    throw originalEx;
                }
            }
            finally
            {
                if (!response.UsedChunkedTransferEncoding())
                    response.AddHeader(ServiceUtils.ResponseStatusHttpHeaderKey, ack.ToString());

                if (completed)
                    response.LogRequest(request);

                response.EndRequest(true);
            }
        }
        private static void addNeverCache(IHttpResponse response)
        {
            response.AddHeader(@"Last-modified", new DateTime(2005, 1, 1).ToUniversalTime().ToString(@"r"));

            response.AddHeader(@"Cache-Control", @"no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
            response.AddHeader(@"Pragma", @"no-cache");
        }
        /// <summary>
        /// Create a WWW-Authenticate header
        /// </summary>
        public void CreateChallenge(IHttpRequest request, IHttpResponse response)
        {
            var nonce = _nonceService.CreateNonce();

            var challenge = new StringBuilder();
            challenge.AppendFormat(@"Digest realm=""{0}"", ", _realmRepository.GetRealm(request));
            challenge.AppendFormat(@"nonce=""{0}"", ", nonce);
            challenge.Append(@"qop=""auth"", ");
            challenge.Append("algorithm=MD5");


            /* RFC 2617 3.3
                Because the client is required to return the value of the opaque
               directive given to it by the server for the duration of a session,
               the opaque data may be used to transport authentication session state
               information. (Note that any such use can also be accomplished more
               easily and safely by including the state in the nonce.) For example,
               a server could be responsible for authenticating content that
               actually sits on another server. It would achieve this by having the
               first 401 response include a domain directive whose value includes a
               URI on the second server, and an opaque directive whose value            
               contains the state information. The client will retry the request, at
               which time the server might respond with a 301/302 redirection,
               pointing to the URI on the second server. The client will follow the
               redirection, and pass an Authorization header , including the
               <opaque> data.
            */
            // , opaque=""" + Guid.NewGuid().ToString().Replace("-", string.Empty) + "\""


            /* Disable the stale mechanism
             * We should really generate the responses directly in these classes.
            challenge.Append(", stale=");
            challenge.Append((bool)options[0] ? "true" : "false");
            challenge.Append("false");
             * */


            response.AddHeader("WWW-Authenticate", challenge.ToString());
            response.StatusCode = 401;
        }
Esempio n. 18
0
        public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session)
        {
            var uri = request.Uri;

            // Check the request path to see if it's for us.
            if (!uri.AbsolutePath.StartsWith(DlnaResourceAccessUtils.RESOURCE_ACCESS_PATH))
            {
                return(false);
            }

            // Grab the media item given in the request.
            Guid mediaItemGuid;

            if (!DlnaResourceAccessUtils.ParseMediaItem(uri, out mediaItemGuid))
            {
                throw new BadRequestException(string.Format("Illegal request syntax. Correct syntax is '{0}'", DlnaResourceAccessUtils.SYNTAX));
            }

            try
            {
                // Attempt to grab the media item from the database.
                var item = MediaLibraryHelper.GetMediaItem(mediaItemGuid);
                if (item == null)
                {
                    throw new BadRequestException(string.Format("Media item '{0}' not found.", mediaItemGuid));
                }

                // Grab the mimetype from the media item and set the Content Type header.
                var mimeType = MediaLibraryHelper.GetOrGuessMimeType(item);
                if (mimeType == null)
                {
                    throw new InternalServerException("Media item has bad mime type, re-import media item");
                }
                response.ContentType = mimeType;

                // Grab the resource path for the media item.
                var resourcePathStr =
                    item.Aspects[ProviderResourceAspect.ASPECT_ID].GetAttributeValue(
                        ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH);
                var resourcePath = ResourcePath.Deserialize(resourcePathStr.ToString());

                var ra = GetResourceAccessor(resourcePath);
                using (var resourceStream = ra.OpenRead())
                {
                    // HTTP/1.1 RFC2616 section 14.25 'If-Modified-Since'
                    if (!string.IsNullOrEmpty(request.Headers["If-Modified-Since"]))
                    {
                        DateTime lastRequest = DateTime.Parse(request.Headers["If-Modified-Since"]);
                        if (lastRequest.CompareTo(ra.LastChanged) <= 0)
                        {
                            response.Status = HttpStatusCode.NotModified;
                        }
                    }

                    // HTTP/1.1 RFC2616 section 14.29 'Last-Modified'
                    response.AddHeader("Last-Modified", ra.LastChanged.ToUniversalTime().ToString("r"));

                    // DLNA Requirement: [7.4.26.1-6]
                    // Since the DLNA spec allows contentFeatures.dlna.org with any request, we'll put it in.
                    if (!string.IsNullOrEmpty(request.Headers["getcontentFeatures.dlna.org"]))
                    {
                        if (request.Headers["getcontentFeatures.dlna.org"] != "1")
                        {
                            // DLNA Requirement [7.4.26.5]
                            throw new BadRequestException("Illegal value for getcontentFeatures.dlna.org");
                        }
                    }
                    var dlnaString = DlnaProtocolInfoFactory.GetProfileInfo(item).ToString();
                    response.AddHeader("contentFeatures.dlna.org", dlnaString);

                    // DLNA Requirement: [7.4.55-57]
                    // TODO: Bad implementation of requirement
                    if (!string.IsNullOrEmpty(request.Headers["transferMode.dlna.org"]))
                    {
                        if (request.Headers["transferMode.dlna.org"] == "Streaming")
                        {
                            response.AddHeader("transferMode.dlna.org", "Streaming");
                        }
                        if (request.Headers["transferMode.dlna.org"] == "Interactive")
                        {
                            response.AddHeader("transferMode.dlna.org", "Interactive");
                        }
                        if (request.Headers["transferMode.dlna.org"] == "Background")
                        {
                            response.AddHeader("transferMode.dlna.org", "Background");
                        }
                    }

                    string        byteRangesSpecifier = request.Headers["Range"];
                    IList <Range> ranges      = ParseRanges(byteRangesSpecifier, resourceStream.Length);
                    bool          onlyHeaders = request.Method == Method.Header || response.Status == HttpStatusCode.NotModified;
                    if (ranges != null && ranges.Count == 1)
                    {
                        // We only support one range
                        SendRange(response, resourceStream, ranges[0], onlyHeaders);
                    }
                    else
                    {
                        SendWholeFile(response, resourceStream, onlyHeaders);
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                throw new InternalServerException(string.Format("Failed to proccess media item '{0}'", mediaItemGuid), ex);
            }

            return(true);
        }
Esempio n. 19
0
		/// <summary>
        /// Method that process the url
        /// </summary>
        /// <param name="request">Information sent by the browser about the request</param>
        /// <param name="response">Information that is being sent back to the client.</param>
        /// <param name="session">Session used to </param>
        /// <returns>true if this module handled the request.</returns>
        public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session)
		{
			if(!CanHandle(request))
				return false;

			string path = request.Uri.AbsolutePath;
			string contentType;
			Stream resourceStream = GetResourceStream(path, out contentType);
			if(resourceStream == null)
				return false;

			response.ContentType = contentType;
            DateTime modified = DateTime.MinValue.ToUniversalTime();
			if (!string.IsNullOrEmpty(request.Headers["if-Modified-Since"]))
			{
                DateTime since = DateTime.Parse(request.Headers["if-Modified-Since"]).ToUniversalTime();
                if (modified > since)
                    response.Status = HttpStatusCode.NotModified;
			}

			response.AddHeader("Last-modified", modified.ToString("r"));
			response.ContentLength = resourceStream.Length;
			response.SendHeaders();

			if (request.Method != "Headers" && response.Status != HttpStatusCode.NotModified)
			{
				byte[] buffer = new byte[8192];
				int bytesRead = resourceStream.Read(buffer, 0, 8192);
				while (bytesRead > 0)
				{
					response.SendBody(buffer, 0, bytesRead);
					bytesRead = resourceStream.Read(buffer, 0, 8192);
				}
			}

			return true;
		}
 public static void RedirectToUrl(this IHttpResponse httpRes, string url, HttpStatusCode redirectStatusCode = HttpStatusCode.Redirect)
 {
     httpRes.StatusCode = (int)redirectStatusCode;
     httpRes.AddHeader(HttpHeaders.Location, url);
     httpRes.EndRequest();
 }
 /// <summary>
 /// Create a WWW-Authenticate header
 /// </summary>
 public void CreateChallenge(IHttpRequest httpRequest, IHttpResponse response)
 {
     response.AddHeader("WWW-Authenticate", "Basic realm=\"" + _realm + "\"");
     response.StatusCode = 401;
 }
Esempio n. 22
0
        public void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName)
        {
            var fileName = request.GetPhysicalPath();

            var fi = new FileInfo(fileName);

            if (!fi.Exists)
            {
                if ((fi.Attributes & FileAttributes.Directory) != 0)
                {
                    foreach (var defaultDoc in EndpointHost.Config.DefaultDocuments)
                    {
                        var defaultFileName = Path.Combine(fi.FullName, defaultDoc);
                        if (!File.Exists(defaultFileName))
                        {
                            continue;
                        }
                        response.Redirect(request.GetPathUrl() + '/' + defaultDoc);
                        return;
                    }
                }

                if (!fi.Exists)
                {
                    throw new HttpException(404, "File '" + request.PathInfo + "' not found.");
                }
            }

            TimeSpan maxAge;

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

            if (request.HasNotModifiedSince(fi.LastWriteTime))
            {
                response.ContentType = MimeTypes.GetMimeType(fileName);
                response.StatusCode  = 304;
                return;
            }

            try
            {
                response.AddHeaderLastModified(fi.LastWriteTime);
                response.ContentType = MimeTypes.GetMimeType(fileName);

                if (fileName.EqualsIgnoreCase(this.DefaultFilePath))
                {
                    if (fi.LastWriteTime > this.DefaultFileModified)
                    {
                        SetDefaultFile(this.DefaultFilePath);                         //reload
                    }
                    response.OutputStream.Write(this.DefaultFileContents, 0, this.DefaultFileContents.Length);
                    return;
                }

                if (!Env.IsMono)
                {
                    response.TransmitFile(fileName);
                }
                else
                {
                    response.WriteFile(fileName);
                }
            }
            catch (Exception)
            {
                throw new HttpException(403, "Forbidden.");
            }
        }
Esempio n. 23
0
 /// <summary>Executes the failed authentication action.</summary>
 ///
 /// <param name="session">The session.</param>
 /// <param name="httpReq">The HTTP request.</param>
 /// <param name="httpRes">The HTTP resource.</param>
 public virtual void OnFailedAuthentication(IAuthSession session, IHttpRequest httpReq, IHttpResponse httpRes)
 {
     httpRes.StatusCode = (int)HttpStatusCode.Unauthorized;
     httpRes.AddHeader(HttpHeaders.WwwAuthenticate, "{0} realm=\"{1}\"".Fmt(this.Provider, this.AuthRealm));
     httpRes.EndRequest();
 }
Esempio n. 24
0
        /// <summary>
        /// Method that process the Uri.
        /// </summary>
        /// <param name="request">Information sent by the browser about the request</param>
        /// <param name="response">Information that is being sent back to the client.</param>
        /// <param name="session">Session used to </param>
        /// <exception cref="InternalServerException">Failed to find file extension</exception>
        /// <exception cref="ForbiddenException">File type is forbidden.</exception>
        public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session)
        {
            if (!CanHandle(request.Uri))
            {
                return(false);
            }

            try
            {
                string path      = GetPath(request.Uri);
                string extension = GetFileExtension(path);
                if (extension == null)
                {
                    throw new InternalServerException("Failed to find file extension");
                }

                if (MimeTypes.ContainsKey(extension))
                {
                    response.ContentType = MimeTypes[extension];
                }
                else
                {
                    throw new ForbiddenException("Forbidden file type: " + extension);
                }

                using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    if (!string.IsNullOrEmpty(request.Headers["if-Modified-Since"]))
                    {
                        DateTime lastRequest = DateTime.Parse(request.Headers["if-Modified-Since"]);
                        if (lastRequest.CompareTo(File.GetLastWriteTime(path)) <= 0)
                        {
                            response.Status = HttpStatusCode.NotModified;
                        }
                    }

                    // Fixed by Albert, Team MediaPortal: ToUniversalTime
                    if (_useLastModifiedHeader)
                    {
                        response.AddHeader("Last-modified", File.GetLastWriteTime(path).ToUniversalTime().ToString("r"));
                    }
                    response.ContentLength = stream.Length;
                    response.SendHeaders();

                    if (request.Method != "Headers" && response.Status != HttpStatusCode.NotModified)
                    {
                        byte[] buffer    = new byte[8192];
                        int    bytesRead = stream.Read(buffer, 0, 8192);
                        while (bytesRead > 0)
                        {
                            response.SendBody(buffer, 0, bytesRead);
                            bytesRead = stream.Read(buffer, 0, 8192);
                        }
                    }
                }
            }
            catch (FileNotFoundException err)
            {
                throw new InternalServerException("Failed to process file.", err);
            }

            return(true);
        }
Esempio n. 25
0
        public bool Process(IHttpRequest aRequest, IHttpResponse aResponse, IHttpSession aSession)
        {
            if (mServices.Count < 1)
            {
                return(false);
            }

            var url_parts = aRequest.Uri.AbsolutePath.Split('/');

            if (url_parts.Length < 2)
            {
                return(false);
            }

            // Check Service
            var service  = url_parts[1];
            var services = mServices.Where(item => item.Key.Equals(service));

            if (services.Count() < 1)
            {
                return(false);
            }

            var    proxy_url = new StringBuilder();
            string proxy_server;
            string proxy_service = service;

            // Verificar se existe sessão
            string sessionID = null;

            if (aRequest.Headers["Cookie"] != null)
            {
                sessionID = aRequest.Headers["Cookie"].Substring(aRequest.Headers["Cookie"].IndexOf("__tiny_sessid=") + 14, 36);
            }

            if (sessionID != null)
            {
                // Se houver sessão, procura por servidor associado
                var sessions = mSessions.Where(i => i[0].Equals(sessionID) && i[1].Equals(service));
                if (sessions.Count() > 0)
                {
                    // há servidor associado, encaminha
                    proxy_server = sessions.ElementAt(0)[2];
                }
                else
                {
                    // não há servidor associado, associa o proximo servidor e encaminha
                    mNextServer[service] = (mNextServer[service] + 1) % services.Count();
                    int nextService = mNextServer[service];
                    proxy_server = services.ElementAt(nextService).Value;
                    mSessions.Add(new string[] { sessionID, service, proxy_server });
                }
            }
            else
            {
                // não há sessão, encaminha para o próximo servidor
                mNextServer[service] = (mNextServer[service] + 1) % services.Count();
                int nextService = mNextServer[service];
                proxy_server = services.ElementAt(nextService).Value;
            }

            proxy_url.AppendFormat("http://{0}", proxy_server);
            var uri       = aRequest.Uri.AbsolutePath;
            var proxy_uri = uri.Substring(uri.IndexOf(proxy_service) + proxy_service.Length);

            proxy_url.Append(proxy_uri);

            WebClient client = new WebClient();

            byte[] bytes    = null;
            var    response = "";

            ForwardCookie(client, aRequest);
            proxy_url.Append(GetQueryString(aRequest));

            if (aRequest.Method == Method.Post)
            {
                try
                {
                    bytes = client.UploadValues(proxy_url.ToString(), GetFormValues(aRequest));
                }
                catch (Exception e)
                {
                    return(false);
                }
            }
            else
            {
                try
                {
                    bytes = client.DownloadData(proxy_url.ToString());
                }
                catch (Exception e)
                {
                    return(false);
                }
            }

            BackwardCookie(client, aResponse);

            // Se houver nova sessão, guardar para mais tarde enviar para o servidor certo
            if (client.ResponseHeaders["Set-Cookie"] != null)
            {
                string setSessionID = client.ResponseHeaders["Set-Cookie"].Substring(client.ResponseHeaders["Set-Cookie"].IndexOf("__tiny_sessid=") + 14, 36);
                mSessions.Add(new string[] { setSessionID, proxy_service, proxy_server });
            }

            // Pass Content-Type
            aResponse.AddHeader("Content-Type", client.ResponseHeaders["Content-Type"]);

            if (client.ResponseHeaders["Content-Type"] == "text/html;charset=UTF-8")
            {
                var writer = new StreamWriter(aResponse.Body);
                response = System.Text.Encoding.Default.GetString(bytes);
                var offset = 0;

                // action=
                foreach (Match match in Regex.Matches(response, @"\baction="))
                {
                    response = response.Insert(match.Index + 8 + (offset * (proxy_service.Length + 1)), String.Concat("/", proxy_service));
                    offset++;
                }

                // src=
                offset = 0;
                foreach (Match match in Regex.Matches(response, @"\bsrc="))
                {
                    response = response.Insert(match.Index + 5 + (offset * (proxy_service.Length + 1)), String.Concat("/", proxy_service));
                    offset++;
                }

                // href=
                offset = 0;
                foreach (Match match in Regex.Matches(response, @"\bhref="))
                {
                    response = response.Insert(match.Index + 6 + (offset * (proxy_service.Length + 1)), String.Concat("/", proxy_service));
                    offset++;
                }

                writer.Write(response);
                writer.Flush();
                return(true);
            }

            var writerContent = new StreamWriter(aResponse.Body, client.Encoding);

            writerContent.Write(client.Encoding.GetString(bytes));
            writerContent.Flush();
            return(true);
        }
Esempio n. 26
0
 /// <summary>
 /// Add a header field and content to the response.
 /// </summary>
 /// <param name="key">string containing the header field
 /// name</param>
 /// <param name="value">string containing the header field
 /// value</param>
 public void AddHeader(string key, string value)
 {
     _httpResponse.AddHeader(key, value);
 }
Esempio n. 27
0
 /// <inheritdoc/>
 public override void Execute(IHttpRequest request, IHttpResponse response,
   object data) {
   if (!string.IsNullOrWhiteSpace(Name)) {
     response.AddHeader(Name, Value ?? string.Empty);
   }
 }
Esempio n. 28
0
        protected override bool HandleRequest(
            IHttpRequest request,
            IHttpResponse response
            )
        {
            string PathtoFileOnDisk = (
                PathToDirectoryOnDisk +
                request.UriPath.Substring(
                    PathToDirectoryOnServer.Length
                    )
                );

            if (PathtoFileOnDisk.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
            {
                throw new Exception("Path contains invalid characters!");
            }
            else if (File.Exists(PathtoFileOnDisk) == false)
            {
                throw new Exception("File does not exist on disk!");
            }

            response.ContentType = ContentTypeFromExtension(
                Path.GetExtension(PathtoFileOnDisk)
                );

            FileInfo info = new FileInfo(PathtoFileOnDisk);

            response.ContentLength = info.Length;
            Stream stream = new FileStream(
                PathtoFileOnDisk,
                FileMode.Open,
                FileAccess.Read,
                FileShare.Read,
                4096,
                FileOptions.SequentialScan
                );

            string ETag = BitConverter.ToString(
                SHA512.Create().ComputeHash(stream)
                ).Replace("-", "").ToLower();

            if (
                request.Headers["If-None-Match"] != null &&
                (
                    new List <string>(
                        request.Headers["If-None-Match"].Split(',')
                        )
                ).Contains(ETag)
                )
            {
                response.Status = HttpStatusCode.NotModified;
                return(true);
            }

            response.AddHeader("ETag", ETag);
            stream.Position = 0;

            response.Body = stream;
            response.AddHeader("Cache-Control", CacheControl);

            if (SendCookies == false)
            {
                response.Cookies.Clear();
            }

            return(true);
        }
Esempio n. 29
0
        /// <summary>
        /// Method that process the Uri.
        /// </summary>
        /// <param name="request">Information sent by the browser about the request</param>
        /// <param name="response">Information that is being sent back to the client.</param>
        /// <param name="session">Session used to </param>
        /// <exception cref="InternalServerException">Failed to find file extension</exception>
        /// <exception cref="ForbiddenException">File type is forbidden.</exception>
        public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session)
        {
            if (!CanHandle(request.Uri))
                return false;

            try
            {
                string path = GetPath(request.Uri);
                string extension = GetFileExtension(path);
                if (extension == null)
                    throw new InternalServerException("Failed to find file extension");

                if (MimeTypes.ContainsKey(extension))
                    response.ContentType = MimeTypes[extension];
                else
                    throw new ForbiddenException("Forbidden file type: " + extension);

                using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    if (!string.IsNullOrEmpty(request.Headers["if-Modified-Since"]))
                    {
                        DateTime since = DateTime.Parse(request.Headers["if-Modified-Since"]).ToUniversalTime();
                        DateTime modified = File.GetLastWriteTime(path).ToUniversalTime();

                        // Truncate the subsecond portion of the time stamp (if present)
                        modified = new DateTime(modified.Year, modified.Month, modified.Day, modified.Hour,
                            modified.Minute, modified.Second, DateTimeKind.Utc);

                        if (modified > since)
                            response.Status = HttpStatusCode.NotModified;
                    }

                    // Fixed by Albert, Team MediaPortal: ToUniversalTime
                    if (_useLastModifiedHeader)
                        response.AddHeader("Last-modified", File.GetLastWriteTime(path).ToUniversalTime().ToString("r"));
                    response.ContentLength = stream.Length;
                    response.SendHeaders();

                    if (request.Method != "Headers" && response.Status != HttpStatusCode.NotModified)
                    {
                        byte[] buffer = new byte[8192];
                        int bytesRead = stream.Read(buffer, 0, 8192);
                        while (bytesRead > 0)
                        {
                            response.SendBody(buffer, 0, bytesRead);
                            bytesRead = stream.Read(buffer, 0, 8192);
                        }
                    }
                }
            }
            catch (FileNotFoundException err)
            {
                throw new InternalServerException("Failed to process file.", err);
            }

            return true;
        }
Esempio n. 30
0
 public virtual void OnFailedAuthentication(IAuthSession session, IHttpRequest httpReq, IHttpResponse httpRes)
 {
     httpRes.StatusCode = (int)HttpStatusCode.Unauthorized;
     httpRes.AddHeader(HttpHeaders.WwwAuthenticate, "{0} realm=\"{1}\"".Fmt(this.Provider, this.AuthRealm));
     httpRes.Close();
 }
Esempio n. 31
0
        internal bool AuthenticateRequest(IHttpRequest request, IHttpResponse response, out string username)
        {
            username = String.Empty;
            bool authSuccess = true;

            if (Authentication != AuthenticationType.None)
            {
                authSuccess = false;

                string[] authHeaderValues = request.Headers.GetValues("Authorization");
                string authHeader = (authHeaderValues != null && authHeaderValues.Length > 0) ?
                    authHeader = authHeaderValues[0] :
                    authHeader = String.Empty;

                switch (Authentication)
                {
                    case AuthenticationType.Basic:
                        if (authHeader.StartsWith("Basic"))
                        {
                            string basicStr = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader.Substring(6)));
                            int colonPos = basicStr.LastIndexOf(':');
                            if (colonPos > -1)
                            {
                                username = basicStr.Substring(0, colonPos);
                                string password = basicStr.Substring(colonPos + 1);

                                if (OnBasicAuthenticate != null)
                                    authSuccess = OnBasicAuthenticate(username, password);
                            }
                        }
                        break;
                    case AuthenticationType.Digest:
                        authHeader = authHeader.Trim();
                        if (authHeader.StartsWith("Digest"))
                        {
                            Dictionary<string, string> digestives = new Dictionary<string, string>();
                            digestives = GetHeaderParts(authHeader);

                            if (digestives["uri"] != HttpUtility.UrlPathEncode(request.UriPath))
                            {
                                response.Status = HttpStatusCode.BadRequest;
                                return false;
                            }

                            string passwd = null;
                            PasswordFormat format;
                            if (OnDigestAuthenticate != null)
                            {
                                if (!OnDigestAuthenticate(digestives["username"], out format, out passwd))
                                {
                                    authSuccess = false; //failed to find password
                                    break;
                                }
                            }
                            else
                            {
                                //no password request handler
                                response.Status = HttpStatusCode.InternalServerError;
                                return false;
                            }

                            string ha1 = null;
                            username = digestives["username"];
                            //For some unknown horrible reason, windows vista client gives username in format DOMAIN\USER, but
                            //calculates the MD5 hash with format DOMAIN\USER. To prevent it from failing well need to convert
                            //the username to proper format. For more info
                            //see: http://www.webdavsystem.com/server/documentation/authentication/digest_vista_xp_2003
                            if (request.Headers["User-Agent"] != null && request.Headers["User-Agent"].StartsWith("Microsoft-WebDAV-MiniRedir/6") && username.Contains("\\\\"))
                            {
                                string[] usernameParts = username.Split('\\');
                                username = usernameParts[0] + "\\" + usernameParts[2];
                            }

                            if (format == PasswordFormat.Plain)
                                ha1 = MD5HashString(username + ":" + digestives["realm"] + ":" + passwd);
                            else
                                ha1 = passwd;

                            string ha2 = null;
                            if (digestives["qop"] != null && digestives["qop"] == "auth-int")
                            {
                                string entityHash = MD5HashString(request.Body.ToString());
                                ha2 = MD5HashString(request.Method + ":" + digestives["uri"] + ":" + entityHash);
                            }
                            else
                                ha2 = MD5HashString(request.Method + ":" + digestives["uri"]);

                            string myResponse = null;
                            if (digestives["qop"] != null && (digestives["qop"] == "auth-int" || digestives["qop"] == "auth"))
                                myResponse = MD5HashString(
                                    ha1 + ":" +
                                    digestives["nonce"] + ":" +
                                    digestives["nc"] + ":" +
                                    digestives["cnonce"] + ":" +
                                    digestives["qop"] + ":" +
                                    ha2);
                            else
                                myResponse = MD5HashString(ha1 + ":" + digestives["nonce"] + ":" + ha2);

                            if (myResponse == digestives["response"] &&
                                IsValidNonce(digestives["nonce"]))
                                authSuccess = true;
                            else
                                authSuccess = false;
                            break;

                        }
                        authSuccess = false;
                        break;
                }
            }

            if (authSuccess)
            {
                return true;
            }
            else
            {
                byte[] responseData = Encoding.UTF8.GetBytes("401 Access Denied");
                response.Status = HttpStatusCode.Unauthorized;
                response.Reason = "Access Denied";
                response.ContentLength = responseData.Length;
                response.Body.Write(responseData, 0, responseData.Length);

                if (Authentication == AuthenticationType.Digest)
                {
                    string realm = request.Uri.Host;
                    string nonce = GenerateNonce();

                    //qop indicates that the server is merely looking for the client to authenticate
                    //may ask for message integrity as well (qop=auth-int)
                    string qop = "auth";

                    //advices if the client on whether it's appropriate to prompt the user for the password again or use a cached value
                    bool stale = false; //send stale=true when it needs the client to rechallenge the user.

                    //construct the digest header value
                    string digest = "Digest realm=\"" + realm + "\",";
                    digest += " stale=" + stale.ToString() + ",";
                    digest += " nonce=\"" + nonce + "\",";
                    digest += " qop=\"" + qop + "\", algorithm=\"MD5\"";
                    response.AddHeader("WWW-Authenticate", digest);
                }
                else
                {
                    response.AddHeader("WWW-Authenticate", "Basic Realm=\"\"");
                }

                return false;
            }
        }
Esempio n. 32
0
        private static void addLimitHeader(IHttpResponse response, ThrottlingConfiguration configuration)
        {
            string numberOfRequestsAllowedInPeriod = configuration.FormattedRequests;

            response.AddHeader("X-Rate-Limit-Limit", numberOfRequestsAllowedInPeriod);
        }
Esempio n. 33
0
        static void listener_RequestReceived(object sender, RequestEventArgs e)
        {
            IHttpClientContext context  = (IHttpClientContext)sender;
            IHttpRequest       request  = e.Request;
            IHttpResponse      response = request.CreateResponse(context);
            StreamWriter       writer   = new StreamWriter(response.Body);

            response.AddHeader("Content-type", "text/plain");
            response.AddHeader("Access-Control-Allow-Methods", "*");
            response.AddHeader("Access-Control-Allow-Origin", "*");

            string endpoint = (request.UriParts.Length > 0? request.UriParts[0] : "");
            int    to       = 0;

            int.TryParse((request.UriParts.Length > 1 ? request.UriParts[1] : ""), out to);
            string      id       = "";
            AsyncSerial toSerial = null;

            if (to != 0)
            {
                if (request.QueryString.Contains("baud") || request.QueryString.Contains("parity") || request.QueryString.Contains("dataBits") ||
                    request.QueryString.Contains("stopBits") || request.QueryString.Contains("newLine"))
                {
                    // TODO
                    toSerial = bus.Connect(to);
                }
                else
                {
                    toSerial = bus.Connect(to);
                }
            }

            switch (endpoint)
            {
            case "":
                writer.Write("SerialServe is running! Check out the documentation on GitHub.");
                writer.Flush();
                response.Send();
                break;

            case "list":
                writer.Write("[" + string.Join(",", bus.Ports) + "]");
                writer.Flush();
                response.Send();
                break;

            case "write":
                try
                {
                    toSerial.Write(request.QueryString["toWrite"].ToString());
                    writer.Write("{\"success\":true}");
                    writer.Flush();
                    response.Send();
                }
                catch
                {
                    response.Status = System.Net.HttpStatusCode.BadRequest;
                    writer.Write("{\"error\":\"Could not write to the requested port.\"}");
                    writer.Flush();
                    response.Send();
                }
                break;

            case "enable":
            case "disable":
                try
                {
                    if (endpoint == "enable")
                    {
                        toSerial.DtsEnable();
                    }
                    else
                    {
                        toSerial.DtsDisable();
                    }
                    writer.Write("{\"success\":true}");
                    writer.Flush();
                    response.Send();
                }
                catch
                {
                    response.Status = System.Net.HttpStatusCode.BadRequest;
                    writer.Write("{\"error\":\"Could not change the state of the requested port.\"}");
                    writer.Flush();
                    response.Send();
                }
                break;

            case "read":
                if (!longpollConnections.ContainsKey(to))
                {
                    longpollConnections[to] = new AssociativeArray <string, List <IHttpResponse> >();
                }

                if (!longpollConnections[to].ContainsKey(id))
                {
                    longpollConnections[to][id] = new List <IHttpResponse>();
                }

                longpollConnections[to][id].Add(response);
                break;

            default:
                response.Status = System.Net.HttpStatusCode.NotFound;
                writer.Write("Not found!");
                writer.Flush();
                response.Send();
                break;
            }
        }
 public static void ReturnAuthRequired(this IHttpResponse httpRes, AuthenticationHeaderType AuthType, string authRealm)
 {
     httpRes.StatusCode = (int)HttpStatusCode.Unauthorized;
     httpRes.AddHeader(HttpHeaders.WwwAuthenticate, string.Format("{0} realm=\"{1}\"", AuthType.ToString(), authRealm));
     httpRes.Close();
 }
Esempio n. 35
0
	    private void AddFilenameToResponses(IHttpRequest req, IHttpResponse res, object dto)
	    {
	        string filenameExtension = null;
	        switch (req.ResponseContentType)
	        {
	            case ExcelContentTypeHandler.ContentType:
	                filenameExtension = "xlsx";
	                break;
	            case PlainTextContentTypeHandler.ApplicationContentType:
	            case PlainTextContentTypeHandler.ContentType:
	                filenameExtension = "txt";
	                break;
	        }
	        if (filenameExtension != null)
	        {
	            res.AddHeader(HttpHeaders.ContentDisposition, string.Format("attachment;filename={0}.{1}", req.OperationName, filenameExtension));
	        }
	    }
Esempio n. 36
0
        void ProxyCapCallback(IHttpClientContext client, IHttpRequest request, IHttpResponse response, Uri remoteHandler)
        {
            const int BUFFER_SIZE = 2048;
            int numBytes;
            byte[] buffer = new byte[BUFFER_SIZE];

            // Proxy the request
            HttpWebRequest remoteRequest = (HttpWebRequest)HttpWebRequest.Create(remoteHandler);

            remoteRequest.Method = request.Method;
            remoteRequest.Headers.Add(request.Headers);

            // TODO: Support for using our own client certificate during the proxy

            if (request.Body.Length > 0)
            {
                // Copy the request stream
                using (Stream writeStream = remoteRequest.GetRequestStream())
                {
                    while ((numBytes = request.Body.Read(buffer, 0, BUFFER_SIZE)) > 0)
                        writeStream.Write(buffer, 0, numBytes);
                }
            }

            // Proxy the response
            HttpWebResponse remoteResponse = (HttpWebResponse)remoteRequest.GetResponse();

            response.Status = remoteResponse.StatusCode;
            response.Reason = remoteResponse.StatusDescription;

            for (int i = 0; i < remoteResponse.Headers.Count; i++)
                response.AddHeader(remoteResponse.Headers.GetKey(i), remoteResponse.Headers[i]);

            // Copy the response stream
            using (Stream readStream = remoteResponse.GetResponseStream())
            {
                while ((numBytes = readStream.Read(buffer, 0, BUFFER_SIZE)) > 0)
                    response.Body.Write(buffer, 0, numBytes);
            }

            response.Send();
        }
Esempio n. 37
0
        public bool Process(IHttpRequest aRequest, IHttpResponse aResponse, IHttpSession aSession)
        {
            var webClient = new WebClient();

            byte[] result      = null;
            var    serviceName = GetServiceName(aRequest);
            var    index       = _registeredServices.IndexOf(new Service(serviceName));
            var    service     = index > -1 ? _registeredServices[index] : _registeredServices[0];

            //check for cookie
            var parsedCookie = service.CookieHandler.ParseCookie(aRequest.Cookies);

            if (parsedCookie.OriginalCookie != null)
            {
                webClient.Headers.Add("Cookie", parsedCookie.OriginalCookie);
            }
            var server = parsedCookie.ServerId != null?service.GetServer(int.Parse(parsedCookie.ServerId)) : service.GetServer();

            if (server == null)
            {
                Host.Logger.WriteLine("service provider not found!");
                return(false);
            }
            Host.Logger.WriteLine(string.Format("service provider found on: {0}", server.GetUrl()));
            var url = string.Format("http://{0}{1}", server.GetUrl(),
                                    service.Name == DefaultService ? aRequest.UriPath : ProcessPath(aRequest));

            try
            {
                result = aRequest.Method == Method.Post
                    ? webClient.UploadValues(url, GetNameValueCollection(aRequest.Form))
                    : webClient.DownloadData(url);
            }
            catch (WebException e)
            {
                Host.Logger.WriteLine("Exception Message :" + e.Message);
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                    Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                }
            }
            if (result != null && result.Length > 0)
            {
                // Send data to corresponding service
                var data  = Encoding.UTF8.GetString(result, 0, result.Length);
                var parse = false;
                foreach (var key in webClient.ResponseHeaders.AllKeys)
                {
                    aResponse.AddHeader(key, webClient.ResponseHeaders[key]);
                    if (key == "Content-Type")
                    {
                        if (webClient.ResponseHeaders[key].Contains("html") ||
                            webClient.ResponseHeaders[key].Contains("text"))
                        {
                            //|| webClient.ResponseHeaders [key].Contains ("javascript")
                            parse = true;
                        }
                    }
                }

                aResponse.AddHeader("Set-Cookie",
                                    service.CookieHandler.EncodeSetCookie(server.Id, webClient.ResponseHeaders["Set-Cookie"]));

                if (parse && service.Name != DefaultService)
                {
                    data   = data.Replace("href=\"/", "href=\"/" + service.Name + "/");
                    data   = data.Replace("action=\"/", "action=\"/" + service.Name + "/");
                    data   = data.Replace("src=\"/", "src=\"/" + service.Name + "/");
                    data   = data.Replace("url(\"/", "url(\"/" + service.Name + "/");
                    result = Encoding.UTF8.GetBytes(data);
                    aResponse.AddHeader("Content-Length", result.Length.ToString());
                }

                aResponse.Body.Write(result, 0, result.Length);
                aResponse.Body.Flush();
                aResponse.Send();
            }
            else
            {
                aResponse.Status = HttpStatusCode.NotFound;
                aResponse.Send();
            }

            //			webClient.DownloadDataCompleted += HandleDownloadDataCompleted;
            //			webClient.DownloadDataAsync (aRequest.Uri);

            return(true);
        }
        /// <summary>
        /// Writes to response.
        /// Response headers are customizable by implementing IHasOptions an returning Dictionary of Http headers.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="result">Whether or not it was implicity handled by ServiceStack's built-in handlers.</param>
        /// <param name="defaultAction">The default action.</param>
        /// <param name="serializerCtx">The serialization context.</param>
        /// <param name="bodyPrefix">Add prefix to response body if any</param>
        /// <param name="bodySuffix">Add suffix to response body if any</param>
        /// <returns></returns>
        public static bool WriteToResponse(this IHttpResponse response, object result, ResponseSerializerDelegate defaultAction, IRequestContext serializerCtx, byte[] bodyPrefix, byte[] bodySuffix)
        {
            using (Profiler.Current.Step("Writing to Response"))
            {
                var defaultContentType = serializerCtx.ResponseContentType;
                try
                {
                    if (result == null)
                    {
                        return(true);
                    }

                    foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders)
                    {
                        response.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value);
                    }

                    var httpResult = result as IHttpResult;
                    if (httpResult != null)
                    {
                        response.StatusCode        = (int)httpResult.StatusCode;
                        response.StatusDescription = httpResult.StatusDescription ?? httpResult.StatusCode.ToString();
                        if (string.IsNullOrEmpty(httpResult.ContentType))
                        {
                            httpResult.ContentType = defaultContentType;
                        }
                        response.ContentType = httpResult.ContentType;
                    }

                    /* Mono Error: Exception: Method not found: 'System.Web.HttpResponse.get_Headers' */
                    var responseOptions = result as IHasOptions;
                    if (responseOptions != null)
                    {
                        //Reserving options with keys in the format 'xx.xxx' (No Http headers contain a '.' so its a safe restriction)
                        const string reservedOptions = ".";

                        foreach (var responseHeaders in responseOptions.Options)
                        {
                            if (responseHeaders.Key.Contains(reservedOptions))
                            {
                                continue;
                            }

                            Log.DebugFormat("Setting Custom HTTP Header: {0}: {1}", responseHeaders.Key, responseHeaders.Value);
                            response.AddHeader(responseHeaders.Key, responseHeaders.Value);
                        }
                    }

                    if (WriteToOutputStream(response, result, bodyPrefix, bodySuffix))
                    {
                        response.Flush();                         //required for Compression
                        return(true);
                    }

                    if (httpResult != null)
                    {
                        result = httpResult.Response;
                    }

                    //ContentType='text/html' is the default for a HttpResponse
                    //Do not override if another has been set
                    if (response.ContentType == null || response.ContentType == ContentType.Html)
                    {
                        response.ContentType = defaultContentType;
                    }
                    if (bodyPrefix != null && response.ContentType.IndexOf(ContentType.Json) >= 0)
                    {
                        response.ContentType = ContentType.JavaScript;
                    }

                    if (EndpointHost.Config.AppendUtf8CharsetOnContentTypes.Contains(response.ContentType))
                    {
                        response.ContentType += ContentType.Utf8Suffix;
                    }

                    var responseText = result as string;
                    if (responseText != null)
                    {
                        if (bodyPrefix != null)
                        {
                            response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length);
                        }
                        WriteTextToResponse(response, responseText, defaultContentType);
                        if (bodySuffix != null)
                        {
                            response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length);
                        }
                        return(true);
                    }

                    if (defaultAction == null)
                    {
                        throw new ArgumentNullException("defaultAction", string.Format(
                                                            "As result '{0}' is not a supported responseType, a defaultAction must be supplied",
                                                            (result != null ? result.GetType().Name : "")));
                    }

                    if (bodyPrefix != null)
                    {
                        response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length);
                    }
                    if (result != null)
                    {
                        defaultAction(serializerCtx, result, response);
                    }
                    if (bodySuffix != null)
                    {
                        response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length);
                    }

                    return(false);
                }
                catch (Exception originalEx)
                {
                    //TM: It would be good to handle 'remote end dropped connection' problems here. Arguably they should at least be suppressible via configuration

                    //DB: Using standard ServiceStack configuration method
                    if (!EndpointHost.Config.WriteErrorsToResponse)
                    {
                        throw;
                    }

                    var errorMessage = string.Format(
                        "Error occured while Processing Request: [{0}] {1}", originalEx.GetType().Name, originalEx.Message);

                    Log.Error(errorMessage, originalEx);

                    var operationName = result != null
                                                            ? result.GetType().Name.Replace("Response", "")
                                                            : "OperationName";

                    try
                    {
                        if (!response.IsClosed)
                        {
                            response.WriteErrorToResponse(defaultContentType, operationName, errorMessage, originalEx);
                        }
                    }
                    catch (Exception writeErrorEx)
                    {
                        //Exception in writing to response should not hide the original exception
                        Log.Info("Failed to write error to response: {0}", writeErrorEx);
                        throw originalEx;
                    }
                    return(true);
                }
                finally
                {
                    response.Close();
                }
            }
        }
Esempio n. 39
0
        public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session)
        {
            if (request.UriParts.Length > 0 && request.UriParts[0] == "query")
            {
                cmanager.ProcessSession (request, session, response);

                var bodyWriter = new StreamWriter (response.Body);

                try
                {
                    var result = cmanager.SendAndReceive<QueryServerResultMessage> (new QueryServerMessage(), session);

                    JsonTextWriter writer = new JsonTextWriter (bodyWriter);
                    serializer.Serialize (writer, result);

                    #if !DEBUG
                    response.ContentType = "application/json";
                    #endif

                    response.AddHeader ("X-JSON", "true");
                }
                catch (Exception ex)
                {
                    bodyWriter.Write ("<pre>");
                    bodyWriter.Write (ex);
                    bodyWriter.Write ("</pre>");
                }

                bodyWriter.Flush();
                response.Send();

                return true;
            }

            return false;
        }
 public static void Redirect(this IHttpResponse httpRes, string url)
 {
     httpRes.AddHeader(HttpHeaders.Location, url);
     httpRes.Close();
 }
Esempio n. 41
0
        public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session)
        {
            try
            {
                if (!CanHandle(request.Uri))
                {
                    return false;
                }

                response.Encoding = Encoding.UTF8;

                var command = Path.GetFileName(request.Uri.AbsolutePath);

                Func handler;
                if (OBBContext.Current.IsMaster)
                {
                    if (!masterHandlers.TryGetValue(command, out handler))
                    {
                        response.Status = HttpStatusCode.NotFound;
                        return false;
                    }
                }
                else
                {
                    if (!slaveHandlers.TryGetValue(command, out handler))
                    {
                        response.Status = HttpStatusCode.NotFound;
                        return false;
                    }
                }

                response.AddHeader("Cache-Control", "no-cache");
                response.AddHeader("Pragma", "no-cache");
                response.AddHeader("Expires", "0");

                if (!handler(request, response))
                    return false;

                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return false;
            }
        }
Esempio n. 42
0
 public static void AddGlobalResponseHeaders(IHttpResponse httpRes)
 {
     foreach (var globalResponseHeader in Config.GlobalResponseHeaders)
     {
         httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value);
     }
 }
Esempio n. 43
0
		/// <summary>
		/// Will request authentication.
		/// </summary>
		/// <remarks>
		/// Sends respond to client, nothing else can be done with the response after this.
		/// </remarks>
		/// <param name="mod"></param>
		/// <param name="request"></param>
		/// <param name="response"></param>
		protected virtual void RequestAuthentication(AuthenticationModule mod, IHttpRequest request, IHttpResponse response)
		{
			string theResponse = mod.CreateResponse(GetRealm(request));
			response.AddHeader("www-authenticate", theResponse);
			response.Reason = "Authentication required.";
			response.Status = HttpStatusCode.Unauthorized;
		}
Esempio n. 44
0
        /// <summary>
        /// Method that process the url
        /// </summary>
        /// <param name="request">Information sent by the browser about the request</param>
        /// <param name="response">Information that is being sent back to the client.</param>
        /// <param name="session">Session used to </param>
        public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session)
        {
            if (!CanHandle(request.Uri))
                return false;

            try
            {
                string path = GetPath(request.Uri);
                string extension = GetFileExtension(path);

                // Directory names can be "C:\MyDirectory.ext", file names can be "C:\MyFileWithoutExt",
                // so the safest way to see if one of it exists, is by asking the windows file system.
                bool directory_exists = Directory.Exists(path);
                bool file_exists = File.Exists(path);

                if (!directory_exists && !file_exists)
                {
                    if (!path.EndsWith("favicon.ico"))
                        Aurora.Framework.MainConsole.Instance.Output("Failed to find " + path);
                    return false;
                    throw new NotFoundException("Failed to proccess request: " + path);
                }

                if (directory_exists)
                {
                    bool indexFound = false;

                    // Look for default index files
                    if (_defaultIndexFiles.Count > 0)
                    {
                        foreach (string index in _defaultIndexFiles)
                        {
                            // TODO: Does path always end with '/'?
                            if (File.Exists(path + index))
                            {
                                path = path + index;
                                extension = GetFileExtension(path);
                                indexFound = true;
                                break;
                            }
                        }
                    }

                    if (!indexFound)
                    {
                        // List directory
                        if (!_allowDirectoryListing)
                        {
                            throw new ForbiddenException("Directory listing not allowed");
                        }

                        string output = GetDirectoryListing(path, request.Uri);

                        response.ContentType = "text/html";
                        response.ContentLength = output.Length;
                        response.SendHeaders();

                        response.SendBody(System.Text.Encoding.Default.GetBytes(output));

                        return true;
                    }
                }

                if (extension == null && file_exists) extension = "default";

                if (!MimeTypes.ContainsKey(extension))
                {
                    if (_serveUnknownTypes)
                    {
                        extension = "default";
                    }
                    else throw new ForbiddenException("Forbidden file type: " + extension);
                }

                // Cgi file
                if (MimeTypes[extension].Equals("wwwserver/stdcgi"))
                {
                    if (!_cgiApplications.ContainsKey(extension))
                        throw new ForbiddenException("Unknown cgi file type: " + extension);

                    if (!File.Exists(_cgiApplications[extension]))
                        throw new InternalServerException("Cgi executable not found: " + _cgiApplications[extension]);

                    string output = CGI.Execute(_cgiApplications[extension], path, request);

                    response.ContentType = "text/html";

                    GetCgiHeaders(ref output, response);

                    response.ContentLength = output.Length;
                    response.SendHeaders();
                    response.SendBody(Encoding.Default.GetBytes(output));
                }
                else // other files
                {
                    response.ContentType = MimeTypes[extension];

                    using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        if (!string.IsNullOrEmpty(request.Headers["if-Modified-Since"]))
                        {
                            DateTime lastRequest = DateTime.Parse(request.Headers["if-Modified-Since"]);
                            if (lastRequest.CompareTo(File.GetLastWriteTime(path)) <= 0)
                                response.Status = HttpStatusCode.NotModified;
                        }

                        if (_useLastModifiedHeader)
                            response.AddHeader("Last-modified", File.GetLastWriteTime(path).ToString("r"));
                        response.ContentLength = stream.Length;
                        response.SendHeaders();

                        if (request.Method != "Headers" && response.Status != HttpStatusCode.NotModified)
                        {
                            byte[] buffer = new byte[8192];
                            int bytesRead = stream.Read(buffer, 0, 8192);
                            while (bytesRead > 0)
                            {
                                response.SendBody(buffer, 0, bytesRead);
                                bytesRead = stream.Read(buffer, 0, 8192);
                            }
                        }
                    }
                }
            }
            catch (InternalServerException err)
            {
                throw err;
            }
            catch (ForbiddenException err)
            {
                throw err;
            }
            catch (NotFoundException err)
            {
                throw err;
            }
            catch (FileNotFoundException err)
            {
                throw new NotFoundException("Failed to proccess file: " + request.Uri.LocalPath, err);
            }
            catch (Exception err)
            {
                throw new InternalServerException("Internal server error [FileModule]", err);
            }

            return true;
        }
Esempio n. 45
0
        public static void HandleFailedAuth(IAuthProvider authProvider,
            IAuthSession session, IHttpRequest httpReq, IHttpResponse httpRes)
        {
            var baseAuthProvider = authProvider as AuthProvider;
            if (baseAuthProvider != null)
            {
                baseAuthProvider.OnFailedAuthentication(session, httpReq, httpRes);
                return;
            }

            httpRes.StatusCode = (int)HttpStatusCode.Unauthorized;
            httpRes.AddHeader(HttpHeaders.WwwAuthenticate, "{0} realm=\"{1}\""
                .Fmt(authProvider.Provider, authProvider.AuthRealm));

            httpRes.Close();
        }
Esempio n. 46
0
        /// <summary>
        /// Gets the headers sent by the cgi program
        /// </summary>
        private void GetCgiHeaders(ref string cgiOutput, IHttpResponse response)
        {
            // TODO: Make this more robust (are we really stripping headers???)
            int index = cgiOutput.IndexOf("\r\n\r\n");

            if (index != -1)
            {
                string header = cgiOutput.Substring(0, index + 2);
                cgiOutput = cgiOutput.Substring(index + 2);

                int end = header.IndexOf("\r\n");

                while (end != -1)
                {
                    string line = header.Substring(0, end);
                    header = header.Substring(end + 2);

                    int colonIndex = line.IndexOf(":");
                    if (colonIndex <= 1)
                        break;

                    string val = line.Substring(colonIndex + 1).Trim();
                    string name = line.Substring(0, colonIndex).Trim();

                    response.AddHeader(name, val);

                    end = header.IndexOf("\r\n");
                }
            }

            // Remove unwanted linebreaks
            cgiOutput = cgiOutput.Trim();
        }
Esempio n. 47
0
        /// <summary>
        /// Method that process the url
        /// </summary>
        /// <param name="request">Information sent by the browser about the request</param>
        /// <param name="response">Information that is being sent back to the client.</param>
        /// <param name="session">Session used to </param>
        public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session)
        {
            if (!CanHandle(request.Uri))
                return false;

            try
            {
                string path = GetPath(request.Uri);
                string extension = GetFileExtension(path);
                if (extension == null)
                    throw new InternalServerException("Failed to find file extension");

                if (MimeTypes.ContainsKey(extension))
                    response.ContentType = MimeTypes[extension];
                else
                    throw new ForbiddenException("Forbidden file type: " + extension);

				using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
				{	
					if (!string.IsNullOrEmpty(request.Headers["if-Modified-Since"]))
					{
						DateTime lastRequest = DateTime.Parse(request.Headers["if-Modified-Since"]);
						if (lastRequest.CompareTo(File.GetLastWriteTime(path)) <= 0)
							response.Status = HttpStatusCode.NotModified;
					}

                    if (_useLastModifiedHeader)
					    response.AddHeader("Last-modified", File.GetLastWriteTime(path).ToString("r"));
					response.ContentLength = stream.Length;
					response.SendHeaders();

					if (request.Method != "Headers" && response.Status != HttpStatusCode.NotModified)
					{
						byte[] buffer = new byte[8192];
						int bytesRead = stream.Read(buffer, 0, 8192);
						while (bytesRead > 0)
						{
							response.SendBody(buffer, 0, bytesRead);
							bytesRead = stream.Read(buffer, 0, 8192);
						}
					}
				}
            }
            catch (FileNotFoundException err)
            {
                throw new InternalServerException("Failed to proccess file.", err);
            }

            return true;
        }
Esempio n. 48
0
 public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
 {
     res.AddHeader("Cache-Control", "max-age=2419200");             // cache static content for approx. 1 month
 }