Ejemplo n.º 1
0
        private void SetHeaders(HttpListenerContext context, string localPath, string utcFileDateString)
        {
            var fileExtension = Path.GetExtension(localPath);

            if (MimeTypes.ContainsKey(fileExtension))
            {
                context.Response.ContentType = MimeTypes[fileExtension];
            }

            context.Response.AddHeader(Headers.CacheControl,
                                       DefaultHeaders.ContainsKey(Headers.CacheControl)
                    ? DefaultHeaders[Headers.CacheControl]
                    : "private");

            context.Response.AddHeader(Headers.Pragma,
                                       DefaultHeaders.ContainsKey(Headers.Pragma)
                    ? DefaultHeaders[Headers.Pragma]
                    : string.Empty);

            context.Response.AddHeader(Headers.Expires,
                                       DefaultHeaders.ContainsKey(Headers.Expires)
                    ? DefaultHeaders[Headers.Expires]
                    : string.Empty);

            context.Response.AddHeader(Headers.LastModified, utcFileDateString);
            context.Response.AddHeader(Headers.AcceptRanges, "bytes");
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Find mime type of file in url
        /// </summary>
        /// <param name="path">path to use</param>
        /// <returns></returns>
        internal static string DetectImageMime(string path)
        {
            // ReSharper disable StringIndexOfIsCultureSpecific.1
            if (string.IsNullOrWhiteSpace(path) || path.IndexOf(".") < 1)
            {
                return("");
            }

            // keep only the part before question mark and hash
            var pathOnly = Regex.Match(path, @"([^\?#])+");

            if (pathOnly.Length == 0)
            {
                return("");
            }

            path = pathOnly.Value;

            // find extension
            var ext = System.IO.Path.GetExtension(path);

            if (string.IsNullOrWhiteSpace(ext))
            {
                return("");
            }
            ext = ext
                  .Replace(".", "")
                  .ToLowerInvariant();

            // resolve to mime type
            return(MimeTypes.ContainsKey(ext) ? MimeTypes[ext] : DefaultImageType + ext);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets the MIME type.
        /// </summary>
        /// <returns>The MIME type.</returns>
        /// <param name="requestedFile">Requested file.</param>
        public string GetMimeType(string requestedFile)
        {
            int    lastDot   = requestedFile.LastIndexOf(".");
            String extension = null;

            if (lastDot >= 0)
            {
                extension = requestedFile.Substring(lastDot + 1);
            }

            String mime = null;

            if (extension != null && MimeTypes.ContainsKey(extension))
            {
                mime = MimeTypes [extension];
            }
            if (mime == null)
            {
                return(DefaultMime);
            }
            else
            {
                return(mime);
            }
        }
Ejemplo n.º 4
0
 private async Task Parse()
 {
     EntityTag   = GenerateEntityTag();
     ContentType = MimeTypes.ContainsKey(File.Extension)
         ? MimeTypes.Get(File.Extension)
         : "application/octet-stream";
     await ParseRanges();
 }
Ejemplo n.º 5
0
        public static string MimeType(string extension, string fallback = null)
        {
            if (fallback == null)
            {
                fallback = "application/octet-stream";
            }

            if (MimeTypes.ContainsKey(extension))
            {
                fallback = MimeTypes[extension];
            }

            return(fallback);
        }
Ejemplo n.º 6
0
        public string GetContentType(string localFileSpec)
        {
            string contentType = string.Empty;
            string ext         = GetFileExtension(localFileSpec);

            if (MimeTypes.ContainsKey(ext))
            {
                contentType = MimeTypes[ext];
            }
            else
            {
                contentType = MimeTypes[TEXT_EXTENSION];
            }
            return(contentType);
        }
Ejemplo n.º 7
0
        public static string GetType(string extension, string defaultValue = null)
        {
            string mimeType;

            if (defaultValue == null)
            {
                mimeType = "application/octet-stream";
            }
            else
            {
                mimeType = defaultValue;
            }

            if (MimeTypes.ContainsKey(extension))
            {
                mimeType = MimeTypes[extension];
            }

            return(mimeType);
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// 返回特定文件扩展名的Content-Type,如果未找到任何对应关系,则返回默认值
 /// </summary>
 /// <param name="fileExtension"></param>
 /// <returns></returns>
 public string GetMimeFromExtension(string fileExtension)
 {
     fileExtension = (fileExtension ?? string.Empty).ToLower();
     return(MimeTypes.ContainsKey(fileExtension) ? MimeTypes[fileExtension] : DefaultMime);
 }
Ejemplo n.º 10
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);
        }
Ejemplo n.º 11
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)
        {
            string state = request.QueryString["state"].Value;
            string code  = request.QueryString["code"].Value;

            if (code != null && code.Length > 9 && request.Uri.LocalPath == "/")
            {
                response.Redirect("/drive?code=" + code);
                return(false);
            }

            try
            {
                switch (request.Uri.LocalPath)
                {
                case "/drive_callback":
                    if (true)
                    {
                        byte[] body = Encoding.UTF8.GetBytes(code);
                        response.Body.Write(body, 0, body.Length);
                        response.Send();
                    }
                    break;

                case "/drive":
                    #region

                    if (true)
                    {
                        string url  = "";
                        string json = "{}";
                        if (state == null)
                        {
                            state = "thinhtu";
                        }
                        if (code == null)
                        {
                            code = "thinhtu";
                        }

                        try
                        {
                            IAuthenticator authenticator = Utils.GetCredentials(code, state);
                            // Store the authenticator and the authorized service in session
                            session["authenticator"] = authenticator;
                            DriveService sv = Utils.BuildService(authenticator);
                            session["service"] = sv;
                        }
                        catch (CodeExchangeException)
                        {
                            if (session["service"] == null || session["authenticator"] == null)
                            {
                                url = Utils.GetAuthorizationUrl("", state);
                                response.Redirect(url);
                                return(false);
                            }
                        }
                        catch (NoRefreshTokenException e)
                        {
                            url = e.AuthorizationUrl;
                            response.Redirect(url);
                            return(false);
                        }

                        response.Redirect("/user");
                        return(false);

                        //////DriveState driveState = new DriveState();

                        //////if (!string.IsNullOrEmpty(state))
                        //////{
                        //////    driveState = Newtonsoft.Json.JsonConvert.DeserializeObject<DriveState>(state);
                        //////}

                        //////if (driveState.action == "open")
                        //////{
                        //////    //return OpenWith(driveState);
                        //////    json = Newtonsoft.Json.JsonConvert.SerializeObject(new { FileIds = driveState.ids });
                        //////}
                        //////else
                        //////{
                        //////    //return CreateNew(driveState);
                        //////    json = Newtonsoft.Json.JsonConvert.SerializeObject(new { FileIds = new string[] { "" } });
                        //////}

                        //////response.ContentType = "application/json; charset=UTF-8";
                        //////byte[] body = Encoding.UTF8.GetBytes(json);
                        //////response.Body.Write(body, 0, body.Length);
                        //////response.Send();
                    }

                    #endregion
                    break;

                case "/user":
                    #region
                    if (true)
                    {
                        IAuthenticator authenticator = session["authenticator"] as IAuthenticator;
                        Userinfo       userInfo      = Utils.GetUserInfo(authenticator);
                        string         json          = Newtonsoft.Json.JsonConvert.SerializeObject(new { email = userInfo.Email, link = userInfo.Link, picture = userInfo.Picture });

                        response.ContentType = "application/json; charset=UTF-8";
                        byte[] body = Encoding.UTF8.GetBytes(json);
                        response.Body.Write(body, 0, body.Length);
                        response.Send();
                    }
                    #endregion
                    break;

                case "/about":
                    #region
                    if (true)
                    {
                        DriveService service = session["service"] as DriveService;
                        if (service == null)
                        {
                            // redirect user to authentication
                            byte[] body = Encoding.UTF8.GetBytes("Redirect user to authentication");
                            response.Body.Write(body, 0, body.Length);
                            response.Send();
                        }
                        else
                        {
                            Google.Apis.Drive.v2.Data.About about = service.About.Get().Fetch();
                            string json = Newtonsoft.Json.JsonConvert.SerializeObject(new { quotaBytesTotal = about.QuotaBytesTotal, quotaBytesUsed = about.QuotaBytesUsed });

                            response.ContentType = "application/json; charset=UTF-8";
                            byte[] body = Encoding.UTF8.GetBytes(json);
                            response.Body.Write(body, 0, body.Length);
                            response.Send();
                        }
                    }
                    #endregion
                    break;

                case "/favicon.ico":
                    byte[] body1 = Encoding.UTF8.GetBytes(string.Empty);
                    response.Body.Write(body1, 0, body1.Length);
                    response.Send();
                    break;

                default:
                    #region

                    if (request.Uri.LocalPath.EndsWith("/"))
                    {
                        string   pathLocal = GetPath(request.Uri);
                        string[] folders   = Directory.GetDirectories(pathLocal);

                        string subPath = pathLocal.Replace(this._basePath, string.Empty).Trim();
                        if (subPath.Length > 0)
                        {
                            subPath = subPath.Replace("\\", "/");
                        }


                        string file_index = string.Format("{0}{1}{2}", this._basePath, subPath, "index.html").Replace("/", "\\");
                        if (File.Exists(file_index) && !request.Uri.ToString().Contains("?file"))
                        {
                            string htm  = File.ReadAllText(file_index);
                            byte[] body = Encoding.UTF8.GetBytes(htm);
                            response.Body.Write(body, 0, body.Length);
                            response.Send();
                        }
                        else
                        {
                            StringBuilder biHome = new StringBuilder();
                            string[]      files  = Directory.GetFiles(pathLocal)
                                                   //.Where(x =>
                                                   //    x.ToLower().EndsWith(".txt") ||
                                                   //    x.ToLower().EndsWith(".md") ||
                                                   //    x.ToLower().EndsWith(".json") ||
                                                   //    x.ToLower().EndsWith(".html") ||
                                                   //    x.ToLower().EndsWith(".htm")
                                                   //)
                                                   .ToArray();
                            foreach (string pi in folders)
                            {
                                biHome.Append(string.Format("<a href=/{0}{1}/>{1}</a><br>", subPath, Path.GetFileName(pi)));
                            }
                            biHome.Append("<br>");
                            foreach (string pi in files)
                            {
                                biHome.Append(string.Format("<a href=/{0}{1}>{1}</a><br>", subPath, Path.GetFileName(pi)));
                            }

                            byte[] body = Encoding.UTF8.GetBytes(string.Format("<h1>{0}</h1>{1}<br><hr>{2}", request.Uri.LocalPath, biHome.ToString(), DateTime.Now.ToString()));
                            response.Body.Write(body, 0, body.Length);
                            response.Send();
                        }

                        return(true);
                    }

                    if (!CanHandle(request.Uri))
                    {
                        return(false);
                    }

                    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);
                            }
                        }
                    }

                    #endregion
                    break;
                }
            }
            catch (FileNotFoundException err)
            {
                throw new InternalServerException("Failed to process file.", err);
            }

            return(true);
        }
Ejemplo n.º 12
0
        private bool HandleGet(HttpListenerContext context, WebServer server, bool sendBuffer = true)
        {
            var urlPath = context.Request.Url.LocalPath.Replace('/', Path.DirectorySeparatorChar);

            // adjust the path to see if we've got a default document
            if (urlPath.Last() == Path.DirectorySeparatorChar)
            {
                urlPath = urlPath + DefaultDocument;
            }

            urlPath = urlPath.TrimStart(new char[] { Path.DirectorySeparatorChar });

            var localPath = Path.Combine(FileSystemPath, urlPath);
            var eTagValid = false;

            byte[] buffer        = null;
            var    fileDate      = DateTime.Today;
            var    partialHeader = context.RequestHeader(Constants.HeaderRange);
            var    usingPartial  = String.IsNullOrWhiteSpace(partialHeader) == false && partialHeader.StartsWith("bytes=");

            if (string.IsNullOrWhiteSpace(DefaultExtension) == false && DefaultExtension.StartsWith(".") &&
                File.Exists(localPath) == false)
            {
                var newPath = localPath + DefaultExtension;
                if (File.Exists(newPath))
                {
                    localPath = newPath;
                }
            }

            if (File.Exists(localPath) == false)
            {
                return(false);
            }

            if (usingPartial == false)
            {
                fileDate = File.GetLastWriteTime(localPath);
                var requestHash = context.RequestHeader(Constants.HeaderIfNotMatch);

                if (RamCache.ContainsKey(localPath) && RamCache[localPath].LastModified == fileDate)
                {
                    server.Log.DebugFormat("RAM Cache: {0}", localPath);
                    var currentHash = Extensions.ComputeMd5Hash(RamCache[localPath].Buffer) + '-' + fileDate.Ticks;

                    if (String.IsNullOrWhiteSpace(requestHash) || requestHash != currentHash)
                    {
                        buffer = RamCache[localPath].Buffer;
                        context.Response.AddHeader(Constants.HeaderETag, currentHash);
                    }
                    else
                    {
                        eTagValid = true;
                    }
                }
                else
                {
                    server.Log.DebugFormat("File System: {0}", localPath);
                    if (sendBuffer)
                    {
                        buffer = File.ReadAllBytes(localPath);

                        var currentHash = Extensions.ComputeMd5Hash(buffer) + '-' + fileDate.Ticks;

                        if (String.IsNullOrWhiteSpace(requestHash) || requestHash != currentHash)
                        {
                            if (UseRamCache && buffer.Length <= MaxRamCacheFileSize)
                            {
                                RamCache[localPath] = new RamCacheEntry()
                                {
                                    LastModified = fileDate, Buffer = buffer
                                };
                            }

                            context.Response.AddHeader(Constants.HeaderETag, currentHash);
                        }
                        else
                        {
                            eTagValid = true;
                        }
                    }
                }
            }

            // check to see if the file was modified or etag is the same
            var utcFileDateString = fileDate.ToUniversalTime()
                                    .ToString(Constants.BrowserTimeFormat, CultureInfo.InvariantCulture);

            if (usingPartial == false &&
                (eTagValid || context.RequestHeader(Constants.HeaderIfModifiedSince).Equals(utcFileDateString)))
            {
                context.Response.AddHeader(Constants.HeaderCacheControl, "private");
                context.Response.AddHeader(Constants.HeaderPragma, string.Empty);
                context.Response.AddHeader(Constants.HeaderExpires, string.Empty);
                context.Response.ContentType = string.Empty;

                context.Response.StatusCode = 304;
            }
            else
            {
                var extension = Path.GetExtension(localPath).ToLowerInvariant();
                if (MimeTypes.ContainsKey(extension))
                {
                    context.Response.ContentType = MimeTypes[extension];
                }

                context.Response.AddHeader(Constants.HeaderCacheControl, "private");
                context.Response.AddHeader(Constants.HeaderPragma, string.Empty);
                context.Response.AddHeader(Constants.HeaderExpires, string.Empty);
                context.Response.AddHeader(Constants.HeaderLastModified, utcFileDateString);
                context.Response.AddHeader(Constants.HeaderAcceptRanges, "bytes");

                if (sendBuffer)
                {
                    var lrange    = 0;
                    var urange    = 0;
                    var size      = (long)0;
                    var isPartial = false;
                    var fileSize  = new FileInfo(localPath).Length;

                    if (usingPartial)
                    {
                        var range = partialHeader.Replace("bytes=", "").Split('-');
                        if (range.Length == 2 && int.TryParse(range[0], out lrange) &&
                            int.TryParse(range[1], out urange))
                        {
                            isPartial = true;
                        }

                        if ((range.Length == 2 && int.TryParse(range[0], out lrange) &&
                             string.IsNullOrWhiteSpace(range[1])) ||
                            (range.Length == 1 && int.TryParse(range[0], out lrange)))
                        {
                            urange    = (int)fileSize - 1;
                            isPartial = true;
                        }

                        if (range.Length == 2 && string.IsNullOrWhiteSpace(range[0]) &&
                            int.TryParse(range[1], out urange))
                        {
                            lrange    = (int)fileSize - urange;
                            urange    = (int)fileSize - 1;
                            isPartial = true;
                        }
                    }

                    if (isPartial)
                    {
                        if (urange > fileSize)
                        {
                            context.Response.StatusCode = 416;
                            context.Response.AddHeader(Constants.HeaderContentRanges,
                                                       string.Format("bytes */{0}", fileSize));
                            return(true);
                        }

                        size = (urange - lrange) + 1;

                        context.Response.AddHeader(Constants.HeaderContentRanges,
                                                   string.Format("bytes {0}-{1}/{2}", lrange, urange, fileSize));

                        context.Response.StatusCode = 206;

                        server.Log.DebugFormat("Opening stream {0} bytes {1}-{2} size {3}", localPath, lrange, urange,
                                               size);

                        buffer = new byte[size];

                        // Open FileStream with FileShare
                        using (var fs = new FileStream(localPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            if (lrange + size > fs.Length)
                            {
                                size = fs.Length - lrange;
                            }
                            fs.Seek(lrange, SeekOrigin.Begin);
                            fs.Read(buffer, 0, (int)size);
                            fs.Close();
                        }

                        // Reset lower range
                        lrange = 0;
                    }
                    else
                    {
                        size = buffer.LongLength;

                        // Perform compression if available
                        if (context.RequestHeader(Constants.HeaderAcceptEncoding).Contains("gzip"))
                        {
                            buffer = buffer.Compress();
                            context.Response.AddHeader(Constants.HeaderContentEncoding, "gzip");
                            size   = buffer.LongLength;
                            lrange = 0;
                        }
                    }

                    context.Response.ContentLength64 = size;

                    try
                    {
                        context.Response.OutputStream.Write(buffer, lrange, (int)size);
                    }
                    catch (HttpListenerException)
                    {
                        // Connection error, nothing else to do
                    }
                }
                else
                {
                    context.Response.ContentLength64 = buffer == null
                        ? new FileInfo(localPath).Length
                        : buffer.LongLength;
                }
            }

            return(true);
        }
Ejemplo n.º 13
0
        private bool RequestHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            response.Status = HttpStatusCode.NotFound;

            if (!CanHandle(request.Uri))
            {
                return(true);
            }

            try
            {
                string path = GetPath(request.Uri);
                if (path == null)
                {
                    return(true);
                }
                string extension = GetFileExtension(path);
                if (extension == null)
                {
                    return(true);
                }

                if (MimeTypes.ContainsKey(extension))
                {
                    response.ContentType = MimeTypes[extension];
                }
                else
                {
                    return(true);
                }

                using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    response.Status = HttpStatusCode.OK;

                    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)
            {
                response.Status = HttpStatusCode.NotFound;
            }

            return(true);
        }
Ejemplo n.º 14
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);
        }