示例#1
0
        /// <summary>
        /// Processes the request for the content of a bundle.
        /// </summary>
        /// <param name="args"></param>
        private void HandleRequestForBundle(RequestReceivedEventArgs args)
        {
            List <string> bundlePathsAndFiles;

            lock (_SyncLock) _BundleToRequestFileNameMap.TryGetValue(args.File.ToLower(), out bundlePathsAndFiles);
            if (bundlePathsAndFiles != null)
            {
                var bundle  = GetUtf8Content(bundlePathsAndFiles);
                var content = Encoding.UTF8.GetBytes(bundle);

                var preamble = Encoding.UTF8.GetPreamble();
                args.Handled = true;
                args.Response.EnableCompression(args.Request);
                args.Response.StatusCode      = HttpStatusCode.OK;
                args.Response.MimeType        = MimeType.GetForExtension(Path.GetExtension(args.PathAndFile));
                args.Response.ContentEncoding = Encoding.UTF8;
                args.Classification           = MimeType.GetContentClassification(args.Response.MimeType);
                args.Response.ContentLength   = content.LongLength + preamble.LongLength;

                using (var memoryStream = new MemoryStream(preamble)) {
                    StreamHelper.CopyStream(memoryStream, args.Response.OutputStream, 10);
                }
                using (var memoryStream = new MemoryStream(content)) {
                    StreamHelper.CopyStream(memoryStream, args.Response.OutputStream, 4096);
                }
            }
        }
示例#2
0
        public void MimeType_GetForExtension_Returns_Correct_MimeType_For_Extensions_With_Leading_Full_Stop()
        {
            var excelWorkSheet = new ExcelWorksheetData(TestContext);
            var mimeType       = excelWorkSheet.String("MimeType");
            var extension      = String.Format(".{0}", excelWorkSheet.String("Extension"));

            Assert.AreEqual(mimeType, MimeType.GetForExtension(extension), extension);
        }
示例#3
0
        public void MimeType_GetForExtension_Returns_Correct_MimeType_For_Extension()
        {
            var excelWorkSheet = new ExcelWorksheetData(TestContext);
            var mimeType       = excelWorkSheet.String("MimeType");
            var extension      = excelWorkSheet.String("Extension");

            Assert.AreEqual(mimeType, MimeType.GetForExtension(extension), extension);
        }
示例#4
0
        public void MimeType_GetForExtension_Is_Case_Insensitive()
        {
            var worksheet = new ExcelWorksheetData(TestContext);
            var mimeType  = worksheet.String("MimeType");
            var extension = String.Format(".{0}", worksheet.String("Extension"));

            Assert.AreEqual(mimeType, MimeType.GetForExtension(extension.ToLower()), extension.ToLower());
            Assert.AreEqual(mimeType, MimeType.GetForExtension(extension.ToUpper()), extension.ToUpper());
        }
示例#5
0
        /// <summary>
        /// Honours requests for files from the file system. Returns false if no file matched the request.
        /// </summary>
        /// <param name="environment"></param>
        /// <returns></returns>
        private bool ServeFromFileSystem(IDictionary <string, object> environment)
        {
            var result = false;

            var context  = PipelineContext.GetOrCreate(environment);
            var request  = context.Request;
            var response = context.Response;

            var relativePath = ConvertRequestPathToRelativeFilePath(request.FlattenedPath);

            relativePath = RejectInvalidCharacters(relativePath);
            if (!String.IsNullOrEmpty(relativePath))
            {
                foreach (var siteRoot in _Configuration.GetSiteRootFolders())
                {
                    var fullPath = Path.Combine(siteRoot, relativePath);

                    if (FileSystemProvider.FileExists(fullPath))
                    {
                        var extension = Path.GetExtension(fullPath);
                        var mimeType  = MimeType.GetForExtension(extension) ?? "application/octet-stream";
                        var content   = FileSystemProvider.FileReadAllBytes(fullPath);

                        if (_Configuration.IsFileUnmodified(siteRoot, request.FlattenedPath, content))
                        {
                            content = RaiseTextLoadedFromFile(request, content, mimeType);
                            SendContent(response, content, mimeType);
                        }
                        else
                        {
                            if (mimeType != MimeType.Html)
                            {
                                response.StatusCode = (int)HttpStatusCode.BadRequest;
                            }
                            else
                            {
                                content = Encoding.UTF8.GetBytes("<HTML><HEAD><TITLE>No</TITLE></HEAD><BODY>VRS will not serve content that has been tampered with. Install the custom content plugin if you want to alter the site's files.</BODY></HTML>");
                                SendContent(response, content, mimeType);
                            }
                        }

                        result = true;
                        break;
                    }
                }
            }

            return(result);
        }
示例#6
0
        /// <summary>
        /// Reads the content of the text file passed across, modifies it and then sends it back to the browser.
        /// </summary>
        /// <param name="args"></param>
        /// <param name="fileName"></param>
        /// <param name="extension"></param>
        /// <param name="modifyContent"></param>
        private void ModifyAndSendContent(RequestReceivedEventArgs args, string fileName, string extension, Action<TextContent> modifyContent)
        {
            var textContent = LoadTextFileWithBom(fileName);
            modifyContent(textContent);

            var bytes = textContent.GetBytes();
            args.Response.EnableCompression(args.Request);
            args.Response.ContentLength = bytes.Length;
            args.Response.MimeType = MimeType.GetForExtension(extension);
            args.Classification = MimeType.GetContentClassification(args.Response.MimeType);
            args.Response.StatusCode = HttpStatusCode.OK;
            using(var stream = new MemoryStream(bytes)) {
                StreamHelper.CopyStream(stream, args.Response.OutputStream);
            }
        }
示例#7
0
        public void FileSystemServer_Infers_Mime_Type_From_File_Extension()
        {
            foreach (var extension in MimeType.GetKnownExtensions())
            {
                TestCleanup();
                TestInitialise();

                AddSiteRootAndFile(@"c:\web\root", $"file.{extension}", extension);
                ConfigureRequest($"/file.{extension}");

                _Pipeline.BuildAndCallMiddleware(_Server.AppFuncBuilder, _Environment.Environment);

                var expectedMimeType = MimeType.GetForExtension(extension);
                AssertFileReturned(expectedMimeType, extension);
            }
        }
示例#8
0
        /// <summary>
        /// See base class docs.
        /// </summary>
        /// <param name="server"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        protected override bool DoHandleRequest(IWebServer server, RequestReceivedEventArgs args)
        {
            var requestFile = GetRequestFile(args.PathParts, args.File);

            var result = requestFile != null && !String.IsNullOrEmpty(requestFile.FileName) && File.Exists(requestFile.FileName);
            if(result) {
                var normalisedRequestPath = NormaliseRequestPath(args.PathAndFile);
                var extension = Path.GetExtension(requestFile.FileName);
                var isProtected = requestFile.Root.IsProtectedContent;

                var checksumEntry = isProtected ? requestFile.Root.FindChecksum(normalisedRequestPath, requestPathIsNormalised: true) : null;
                result = !isProtected || checksumEntry != null;
                if(result) {
                    var isHtml = ".html".Equals(extension, StringComparison.OrdinalIgnoreCase) || ".htm".Equals(extension, StringComparison.OrdinalIgnoreCase);

                    if(isProtected && !requestFile.Root.TestChecksum(checksumEntry, requestFile.FileName)) {
                        Factory.Singleton.Resolve<ILog>().Singleton.WriteLine("Will not serve {0}, it has failed the checksum test", args.PathAndFile);
                        if(!isHtml) {
                            args.Response.StatusCode = HttpStatusCode.BadRequest;
                        } else {
                            Responder.SendText(args.Request, args.Response, "<HTML><HEAD><TITLE>No</TITLE></HEAD><BODY>VRS will not serve content that has been tampered with. Install the custom content plugin if you want to alter the site's files.</BODY></HTML>", Encoding.UTF8, MimeType.Html);
                            args.Classification = ContentClassification.Html;
                        }
                    } else {
                        if(isHtml) {
                            ModifyAndSendContent(args, requestFile.FileName, extension, r => {
                                var textContentArgs = new TextContentEventArgs(args.Request, args.PathAndFile, r.Content, r.Encoding);
                                _WebSite.OnHtmlLoadedFromFile(textContentArgs);
                                r.Content = textContentArgs.Content;

                                _WebSite.InjectHtmlContent(args.PathAndFile, r);
                                _WebSite.BundleHtml(args.PathAndFile, r);
                            });
                        } else if(".js".Equals(extension, StringComparison.OrdinalIgnoreCase)) {
                            ModifyAndSendContent(args, requestFile.FileName, extension, r => {
                                _WebSite.InjectIntoJavaScript(args.PathAndFile, r);
                                _WebSite.MinifyJavaScript(r);
                            });
                        } else if(".css".Equals(extension, StringComparison.OrdinalIgnoreCase)) {
                            ModifyAndSendContent(args, requestFile.FileName, extension, r => {
                                _WebSite.MinifyCss(r);
                            });
                        } else {
                            args.Response.MimeType = MimeType.GetForExtension(extension);

                            var enableCompression = true;
                            if(args.Response.MimeType == MimeType.IconImage) enableCompression = false;
                            else if(args.Response.MimeType.StartsWith("image/")) enableCompression = false;

                            if(enableCompression) args.Response.EnableCompression(args.Request);
                            args.Response.ContentLength = new FileInfo(requestFile.FileName).Length;
                            args.Classification = MimeType.GetContentClassification(args.Response.MimeType);
                            args.Response.StatusCode = HttpStatusCode.OK;
                            using(var fileStream = new FileStream(requestFile.FileName, FileMode.Open, FileAccess.Read)) {
                                StreamHelper.CopyStream(fileStream, args.Response.OutputStream, 4096);
                            }
                        }
                    }
                }
            }

            return result;
        }
示例#9
0
 public void MimeType_GetForExtension_Returns_Null_When_Passed_Empty_String()
 {
     Assert.AreEqual(null, MimeType.GetForExtension(""));
 }
示例#10
0
 public void MimeType_GetForExtension_Returns_Null_When_Passed_Null()
 {
     Assert.AreEqual(null, MimeType.GetForExtension(null));
 }
示例#11
0
 public void MimeType_GetForExtension_Returns_Octet_Mime_Type_For_Unknown_Extensions()
 {
     Assert.AreEqual("application/octet-stream", MimeType.GetForExtension("Well, this is just gibberish!"));
 }