Esempio n. 1
0
        public void StdFSFileReadOnlySharedAccessTest()
        {
            File422 file = root.CreateFile("file.txt");

            Stream stream1 = file.OpenReadOnly();
            Stream stream2 = file.OpenReadOnly();
            Stream stream3 = file.OpenReadWrite();

            Assert.NotNull(stream1);
            Assert.NotNull(stream2);
            Assert.Null(stream3);
        }
        public void f_ReadFileMany()
        {
            File422 testFile = root.GetFile("testFile");
            Stream  fs       = testFile.OpenReadOnly();
            Stream  fs1      = testFile.OpenReadOnly();
            Stream  fs2      = testFile.OpenReadOnly();

            Assert.AreNotEqual(null, fs);
            Assert.AreNotEqual(null, fs1);
            Assert.AreNotEqual(null, fs2);
            fs.Dispose();
            fs1.Dispose();
            fs2.Dispose();
        }
Esempio n. 3
0
        private void RespondWithFile(File422 file, WebRequest req)
        {
            Stream fs = file.OpenReadOnly();

            if (req.Headers.ContainsKey("range"))
            {
                WriteWithRangeHeader(file, fs, req);
                return;
            }

            // Send response code and headers
            string response = "HTTP/1.1 200 OK\r\n" +
                              "Content-Length: " + fs.Length + "\r\n" +
                              "Content-Type: " + file.GetContentType() + "\r\n\r\n";

            byte[] responseBytes = Encoding.ASCII.GetBytes(response);
            req.WriteResponse(responseBytes, 0, responseBytes.Length);

            while (true)
            {
                byte[] buf  = new byte[4096];
                int    read = fs.Read(buf, 0, buf.Length);
                if (read == 0)
                {
                    break;
                }
                req.WriteResponse(buf, 0, read);
            }
            fs.Close();
        }
Esempio n. 4
0
        private void RespondWithFile(File422 file, WebRequest req) //return a file
        {
            string contentType = "text/html";                      //default to text/html

            if (file.Name.Contains(".jpg") || file.Name.Contains(".jpeg"))
            {
                contentType = "image/jpeg";
            }
            else if (file.Name.Contains(".gif"))
            {
                contentType = "image/gif";
            }
            else if (file.Name.Contains(".png"))
            {
                contentType = "image/png";
            }
            else if (file.Name.Contains(".pdf"))
            {
                contentType = "application/pdf";
            }
            else if (file.Name.Contains(".mp4"))
            {
                contentType = "video/mp4";
            }
            else if (file.Name.Contains(".xml"))
            {
                contentType = "text/xml";
            }



            req.WriteHTMLResponse(file.OpenReadOnly(), contentType); //write a page as a file
        }
Esempio n. 5
0
        public void MemFSFileReadWriteSharedAccessTest()
        {
            File422 file = root.CreateFile("file.txt");

            Stream stream3 = file.OpenReadWrite();
            Stream stream1 = file.OpenReadOnly();
            Stream stream2 = file.OpenReadOnly();

            Assert.NotNull(stream3);
            Assert.Null(stream1);
            Assert.Null(stream2);


            Assert.AreEqual(1, ((MemFSFile)file).RefCount);

            stream3.Dispose();

            Assert.AreEqual(0, ((MemFSFile)file).RefCount);
        }
Esempio n. 6
0
        public string GetHttpHeader(File422 file)
        {
            MimeMapper mapper = new MimeMapper();

            _request.AddHeader("Content-Type", (mapper.GetMimeType(file.Name)));

            Stream filestream = file.OpenReadOnly();

            _request.AddHeader("Content-Length", filestream.Length.ToString());

            return(_request.GetHtmlResponseHeader());
        }
Esempio n. 7
0
        //when a file is requested
        private void RespondWithFile(File422 file, WebRequest req)
        {
            StringBuilder sb = new StringBuilder();


            string[] extension = file.Name.Split('.');

            if (extension[1] == "png")
            {
                req.Type = "image/png";
            }

            else if (extension[1] == "jpg")
            {
                req.Type = "image/jpg";
            }

            else if (extension[1] == "pdf")
            {
                req.Type = "application/pdf";
            }

            else if (extension[1] == "mp4")
            {
                req.Type = "video/mp4";
            }

            else if (extension[1] == "mp3")
            {
                req.Type = "video/mp3";
            }

            else if (extension[1] == "html")
            {
                req.Type = "text/html";
            }

            else if (extension[1] == "XML")
            {
                req.Type = "text/xml";
            }

            else
            {
                req.Type = "text";
            }


            req.WriteFileResponse(file.OpenReadOnly());
        }
        public void f_ReadFileManyWriteOpen()
        {
            File422 testFile = root.GetFile("testFile");
            Stream  fs       = testFile.OpenReadWrite();
            string  text     = "This is a test for MemFileSystem.";

            fs.Write(Encoding.ASCII.GetBytes(text), 0, text.Length);
            Stream fs1 = testFile.OpenReadOnly();
            Stream fs2 = testFile.OpenReadOnly();

            Assert.AreEqual(null, fs1);
            Assert.AreEqual(null, fs2);

            fs.Dispose();

            Stream fs3 = testFile.OpenReadOnly();

            byte[] buf = new byte[Encoding.ASCII.GetBytes(text).Length];
            fs3.Read(buf, 0, Encoding.ASCII.GetBytes(text).Length);
            Stream fs4 = testFile.OpenReadOnly();

            fs3.Close(); fs4.Close();
            Assert.AreEqual(Encoding.ASCII.GetBytes(text), buf);

            fs = testFile.OpenReadWrite();
            string blah = "This is added Text.";

            fs.Seek(Encoding.ASCII.GetBytes(text).Length, SeekOrigin.Begin);
            fs.Write(Encoding.ASCII.GetBytes(blah), 0, blah.Length);
            fs.Dispose();
            fs3 = testFile.OpenReadOnly();
            buf = new byte[Encoding.ASCII.GetBytes(text + blah).Length];
            fs3.Read(buf, 0, Encoding.ASCII.GetBytes(text + blah).Length);
            //string s = Encoding.ASCII.GetString(buf);

            Assert.AreEqual(Encoding.ASCII.GetBytes(text + blah), buf);
        }
Esempio n. 9
0
        public void h_GetFileReadOnly()
        {
            //Dir422 dir = new StdFSDir(rootDir, true);
            //File422 fooFile = dir.GetFile("fooFile");
            File422 fooFile = root.GetFile("fooFile");
            Stream  fs      = fooFile.OpenReadOnly();

            try{
                string s = "Hello World";
                fs.Write(Encoding.ASCII.GetBytes(s), 0, s.Length);
            }
            catch (Exception e) {
                Assert.IsTrue(e is NullReferenceException);
            }
        }
Esempio n. 10
0
        private void RespondWithFile(File422 file, WebRequest req)
        {
            Stream fileStream = file.OpenReadOnly();

            if (req.Headers.ContainsKey("range"))
            {
                req.WritePartialDataResponse(fileStream, GetFileTypeHeader(file));
                fileStream.Close();
                return;
            }


            req.WriteGenericFileResponse(fileStream, GetFileTypeHeader(file));

            fileStream.Close();
        }
Esempio n. 11
0
        private void RespondWithFile(File422 file, WebRequest req)
        {
            Stream str = file.OpenReadOnly();

            string resp = "HTTP/1.1 200 OK\r\n" +
                          "Content-Length: " + str.Length + "\r\n" +
                          "Content-Type: " + GetContentType(file.Name) + "\r\n\r\n";

            // Write headers first
            byte[] buf = Encoding.ASCII.GetBytes(resp);
            req.WriteDirectResponse(buf, 0, buf.Length);

            buf = new byte[8192];
            int count = str.Read(buf, 0, buf.Length);

            while (count != 0)
            {
                req.WriteDirectResponse(buf, 0, count);
                buf   = new byte[8192];
                count = str.Read(buf, 0, buf.Length);
            }
            str.Close();
        }
Esempio n. 12
0
        public void WriteFileContents(File422 file)
        {
            Console.WriteLine("WriteFileContents(): ");

            Stream fileStream = file.OpenReadOnly();

            _request.StatusCode = 200;

            // send header
            string HttpHeader = GetHttpHeader(file);

            _request.WriteToNetworkStream(HttpHeader);

            byte[] buffer    = new byte[8000];
            int    bytesRead = 0;
            long   toRead    = 0;

            toRead = (buffer.Length > fileStream.Length) ? fileStream.Length : buffer.Length;

            bytesRead = fileStream.Read(buffer, bytesRead, (int)toRead);
            string content = Encoding.Default.GetString(buffer);

            _request.WriteToNetworkStream(content);
        }
Esempio n. 13
0
        private void RespondWithFile(File422 file, WebRequest req)
        {
            int range_start = -1;
            int range_stop  = -1;
            int total_read  = 0;

            if (req.Headers.ContainsKey("Content-Range") || req.Headers.ContainsKey("content-range"))
            {
                //Get content Range.
                try
                {
                    range_start = Convert.ToInt32(req.Headers["Content-Range"].Split('/', '-')[0]);
                    range_stop  = Convert.ToInt32(req.Headers["Content-Range"].Split('/', '-')[1]);
                }
                catch { };
            }

            string content_type = "";

            if (file.Name.ToLower().EndsWith(".jpg") || file.Name.EndsWith(".jpeg"))
            {
                content_type = "image/jpeg";
            }
            if (file.Name.ToLower().EndsWith(".png"))
            {
                content_type = "image/png";
            }
            if (file.Name.ToLower().EndsWith(".pdf"))
            {
                content_type = "application/pdf";
            }
            if (file.Name.ToLower().EndsWith(".mp4"))
            {
                content_type = "video/mp4";
            }
            if (file.Name.ToLower().EndsWith(".txt"))
            {
                content_type = "text/html";
            }
            if (file.Name.ToLower().EndsWith(".html"))
            {
                content_type = "text/html";
            }
            if (file.Name.ToLower().EndsWith(".xml"))
            {
                content_type = "text/xml";
            }

            Stream output = file.OpenReadOnly();
            string res    = "HTTP/1.1 200 OK\r\n" +
                            "Content-Length: " + output.Length + "\r\n" +
                            "Content-Type: " + content_type +
                            "\r\n\r\n";

            byte[] msg = System.Text.Encoding.ASCII.GetBytes(res);
            req.Response.Write(msg, 0, msg.Length);

            int bytes_read = 0;

            byte[] input = new byte[8000];

            while (total_read < range_start)
            {
                if (range_start - total_read > input.Length)
                {
                    bytes_read = output.Read(input, 0, input.Length);
                }
                else
                {
                    bytes_read = output.Read(input, 0, range_start - total_read);
                }
                total_read += bytes_read;
            }

            string html = "";

            if (range_stop != -1)
            {
                while (total_read < range_stop)
                {
                    if (range_stop - total_read > input.Length)
                    {
                        bytes_read = output.Read(input, 0, input.Length);
                    }
                    else
                    {
                        bytes_read = output.Read(input, 0, range_stop - total_read);
                    }
                    total_read += bytes_read;
                    req.Response.Write(input, 0, input.Length);
                }
            }
            else
            {
                bytes_read  = output.Read(input, 0, input.Length);
                total_read += bytes_read;
                req.Response.Write(input, 0, input.Length);

                while (bytes_read != 0)
                {
                    bytes_read  = output.Read(input, 0, input.Length);
                    total_read += bytes_read;
                    req.Response.Write(input, 0, input.Length);
                }
            }

            output.Close();
        }
Esempio n. 14
0
        void SendFileRange(File422 file, long start, long end, long chunkSize, WebRequest req)
        {
            if (end < start)
            {
                throw new ArgumentException("Invalid start and end range");
            }

            var fileStream = file.OpenReadOnly();

            long fileSize = fileStream.Length;

            if (start > end)
            {
                req.WriteNotFoundResponse("Invalid Range Header Specified");
            }

            if (end == 0)
            {
                end = fileSize;
            }
            req.Headers = new System.Collections.Concurrent.ConcurrentDictionary <string, string> ();

            if (end - start + 1 < chunkSize)
            {
                // only need to send 1 response
                string contentType = GetContentType(file.Name);
                if (contentType != null)
                {
                    req.Headers ["Content-Type"] = contentType;
                }
                else
                {
                    req.Headers ["Content-Type"] = "text/plain";
                }
                var fileContents = GetFileRange(fileStream, start, end);
                req.WriteResponse("206 Partial Content", fileContents);
            }
            else
            {
                // need to send multiple responses
                string boundary = "5187ab27335732";

                string contentType = GetContentType(file.Name);
                if (contentType != null)
                {
                    req.Headers ["Content-Type"] = contentType;
                }


                long offset = start;
                long sent   = 0;
                req.Headers ["Accept-Ranges"] = "bytes";

                long sizeToSend = end - start + 1;

                while (sent <= sizeToSend)
                {
                    long currentSize = (sizeToSend - sent) < chunkSize ? sizeToSend - sent: chunkSize;

                    if (offset + currentSize > fileSize)
                    {
                        currentSize = fileSize - offset + 1;
                    }


                    if (currentSize <= 0)
                    {
                        break;
                    }
                    //Console.WriteLine ("Getting file range [{0}, {1}]", offset, offset + currentSize);
                    var fileContents = GetFileRange(fileStream, offset, offset + currentSize);

                    req.Headers ["Content-Range"] = String.Format("bytes {0}-{1}/{2}", offset, currentSize + offset, sizeToSend);


                    req.WriteResponse("206 PartialContent", fileContents);

                    offset += currentSize + 1;
                    sent   += currentSize;
                }
            }
        }
Esempio n. 15
0
        private void SendFileContent(File422 file, WebRequest req)
        {
            byte[]        buffer = new byte[1024]; //1kb buffer
            StringBuilder sb     = new StringBuilder();
            string        contentType;             //default contentType
            string        status = "200 Success";  //default status
            int           initialPos;
            long          contentLength, startByte = 0;

            //find extension
            if (!exts.TryGetValue(Path.GetExtension(file.Name).ToLower(),
                                  out contentType))
            {
                //default
                contentType = "application/octet-stream";
            }

            using (Stream fs = file.OpenReadOnly()){
                contentLength = fs.Length;
                //if client sent a range request.
                if (req.Headers.ContainsKey("range"))
                {
                    var t = req.GetRangeHeader(fs.Length);
                    //find range
                    if (t == null)
                    {
                        string pageHTML = "<html><h1>416 REQUESTED RANGE NOT SATISFIABLE</h1></html>";
                        req.WriteRangeNotSatisfiableResponse(pageHTML,
                                                             fs.Length.ToString());
                        return;
                    }
                    status        = "206 Partial Content";
                    startByte     = t.Item1;                 //start offset byte
                    contentLength = (t.Item2 - t.Item1) + 1; //because contentLength is the length, not last byte.
                }

                sb.Append("HTTP/1.1 " + status + "\r\n");
                sb.Append("Content-Length: " + contentLength + "\r\n");
                sb.Append("Content-Type: " + contentType + "\r\n");

                //we need this so that the file downloads, instead
                //of trying to switch views.

                /*sb.Append("Content-Disposition: attachment; filename=\"" +
                 *  file.Name + "\"\r\n");*/

                sb.Append("\r\n");
                initialPos = sb.Length;

                ASCIIEncoding.ASCII.GetBytes(sb.ToString()).CopyTo(buffer, 0);

                if (req.Headers.ContainsKey("range"))
                {
                    int totalBytesRead;
                    int bytesRead = 0;

                    //seek to startbyte.
                    fs.Seek(startByte, SeekOrigin.Begin);

                    //our initial read has to be the smaller of one of these 2.
                    int initialRead = ((buffer.Length - initialPos) < contentLength)
                        ? buffer.Length - initialPos
                        : (int)contentLength; // if (buffer.Length - initialPos) >= cL

                    totalBytesRead = fs.Read(buffer, initialPos, initialRead);

                    //Console.WriteLine(ASCIIEncoding.ASCII.GetString(buffer));

                    //has to be what we had initially plus what we just read.
                    req.WriteResponse(buffer, initialPos + initialRead);
                    Array.Clear(buffer, 0, buffer.Length);

                    //if we still have not read up to content length, keep reading.
                    if (totalBytesRead < contentLength)
                    {
                        int subsequentRead = (buffer.Length < contentLength)
                            ? buffer.Length
                            : (int)contentLength; // if (buffer.Length - initialPos) >= cL

                        //keep track of previous total bytes
                        int prevTotalBytesRead = totalBytesRead;

                        while ((bytesRead = fs.Read(buffer, 0, subsequentRead)) != 0 &&
                               (totalBytesRead += bytesRead) < contentLength)
                        {
                            prevTotalBytesRead = totalBytesRead;

                            req.WriteResponse(buffer, bytesRead);
                            Array.Clear(buffer, 0, buffer.Length);
                        }

                        if (totalBytesRead >= contentLength)
                        {
                            //we subtract the value of totalBytes right before it was more than contentLength,
                            //from content length (contentLength - prevTotalBytesRead)
                            //this gives us the last bit we need to write to achieve the range requested's length.
                            req.WriteResponse(buffer, (int)contentLength - prevTotalBytesRead);
                        }
                    }
                }
                else
                {
                    fs.Read(buffer, initialPos, buffer.Length - initialPos);
                    req.WriteResponse(buffer);

                    while (fs.Read(buffer, 0, buffer.Length) != 0)
                    {
                        req.WriteResponse(buffer);
                        Array.Clear(buffer, 0, buffer.Length);
                    }
                }

                req.CloseResponse();
            }
        }
Esempio n. 16
0
        public void RunTest(FileSys422 mySys)
        {
            Dir422 root = mySys.GetRoot();

            //We should not be able to go above our root.
            Assert.IsNull(root.Parent);

            // Checking that we do not have a file
            Assert.IsFalse(root.ContainsFile("NewFile.txt", false));
            //create the file
            root.CreateFile("NewFile.txt");
            // Check that we can find it.
            Assert.IsTrue(root.ContainsFile("NewFile.txt", false));

            // Same with directory
            Assert.IsFalse(root.ContainsDir("SubDir", false));
            Dir422 subDir = root.CreateDir("SubDir");

            Assert.IsTrue(root.ContainsDir("SubDir", false));

            //Creating a file in a sub dir
            subDir.CreateFile("subText.txt");

            // Testing the recursive methods on files
            Assert.IsFalse(root.ContainsFile("subText.txt", false));
            Assert.IsTrue(root.ContainsFile("subText.txt", true));

            //Testing recurcive method on dirs
            subDir.CreateDir("newSubDir");

            Assert.IsFalse(root.ContainsDir("newSubDir", false));
            Assert.IsTrue(root.ContainsDir("newSubDir", true));

            //Checking getDir
            Dir422 recivedDir = root.GetDir("InvalidDir");

            Assert.IsNull(recivedDir);
            recivedDir = root.GetDir("SubDir");
            Assert.AreEqual("SubDir", recivedDir.Name);

            // Checking that if a file does not exist we return null,
            // otherwise we recived the file we wanted.
            File422 recidedFile = root.GetFile("InvalidFile");

            Assert.IsNull(recidedFile);
            recidedFile = root.GetFile("NewFile.txt");
            Assert.AreEqual("NewFile.txt", recidedFile.Name);

            //Checking the name validation function.
            // All of these methods use the same Validate Name method.
            Assert.IsNull(subDir.CreateFile("file/New.txt"));
            Assert.IsNull(subDir.CreateDir("file/New"));

            string bufString = "hello world";

            byte[] buff        = ASCIIEncoding.ASCII.GetBytes(bufString);
            var    writeStream = recidedFile.OpenReadWrite();

            writeStream.Write(buff, 0, 11);

            var readStream = recidedFile.OpenReadOnly();

            Assert.IsNull(readStream);

            writeStream.Dispose();

            readStream = recidedFile.OpenReadOnly();
            Assert.IsNotNull(readStream);

            //First read 'hello ' from each stream
            byte[] readBuf = new byte[6];
            readStream.Read(readBuf, 0, 6);
            Assert.AreEqual("hello ", ASCIIEncoding.ASCII.GetString(readBuf));

            //Having two streams open for read
            var readStream2 = recidedFile.OpenReadOnly();

            Assert.IsNotNull(readStream2);

            byte[] readBuf2 = new byte[6];
            readStream2.Read(readBuf2, 0, 6);
            Assert.AreEqual("hello ", ASCIIEncoding.ASCII.GetString(readBuf2));

            //Next read 'world' from each stream
            readBuf = new byte[5];
            readStream.Read(readBuf, 0, 5);
            Assert.AreEqual("world", ASCIIEncoding.ASCII.GetString(readBuf));

            readBuf2 = new byte[5];
            readStream2.Read(readBuf2, 0, 5);
            Assert.AreEqual("world", ASCIIEncoding.ASCII.GetString(readBuf2));

            //try to open a stream to write while there are streams open for read
            writeStream = recidedFile.OpenReadWrite();
            Assert.IsNull(writeStream);

            //Close streams and try again
            readStream.Close();
            readStream2.Close();

            writeStream = recidedFile.OpenReadWrite();
            Assert.IsNotNull(writeStream);
        }
Esempio n. 17
0
        void handleGET(WebRequest req)
        {
            try
            {
                string[] path = req.URI.Split('/');

                // To handle '/files' request
                if (path.Length == 2)
                {
                    req.WriteHTMLResponse(BuildDirHTML(fileSystem.GetRoot()));

                    return;
                }

                // This handles '/files/**'
                // The URI maps to an existing directory in the file system
                if (fileSystem.GetRoot().ContainsDir(path[path.Length - 1], true))
                {
                    // Imidiately set the content-type to html since we are returning html code
                    req.Headers["content-type"] = "text/html";

                    Dir422 currentDir = fileSystem.GetRoot();
                    for (int i = 2; i < path.Length; i++)
                    {
                        // Fix '/' at end of URI
                        if (path[i] != "")
                        {
                            currentDir = currentDir.GetDir(path[i]);
                        }
                    }

                    req.WriteHTMLResponse(BuildDirHTML(currentDir));
                }
                // The URI maps to an existing file in the file system
                else if (fileSystem.GetRoot().ContainsFile(path[path.Length - 1], true))
                {
                    // Get the file type and set the content-type to the file type
                    string filename = path[path.Length - 1];

                    int    dot  = filename.LastIndexOf('.');
                    string type = (dot >= 0) ? filename.Substring(dot).ToLower() : "";

                    switch (type)
                    {
                    case ".txt":
                        req.Headers["content-type"] = "text/plain";
                        break;

                    case ".xml":
                        req.Headers["content-type"] = "text/xml";
                        break;

                    case ".jpg":
                        req.Headers["content-type"] = "image/jpg";
                        break;

                    case ".jpeg":
                        req.Headers["content-type"] = "image/jpeg";
                        break;

                    case ".png":
                        req.Headers["content-type"] = "image/png";
                        break;

                    case ".mp4":
                        req.Headers["content-type"] = "video/mp4";
                        break;

                    case ".pdf":
                        req.Headers["content-type"] = "application/pdf";
                        break;

                    default:
                        req.Headers["content-type"] = "text/html";
                        break;
                    }

                    Dir422 currentDir = fileSystem.GetRoot();

                    // Don't include last element because thats the file name
                    for (int i = 2; i < path.Length - 1; i++)
                    {
                        // Fix '/' at end of URI
                        if (path[i] != "")
                        {
                            currentDir = currentDir.GetDir(path[i]);
                        }
                    }

                    File422 file = currentDir.GetFile(path[path.Length - 1]);

                    // Get the file stuff
                    int bytesRead;

                    // Did the client send us a range header
                    string rangeValue;
                    if (req.Headers.TryGetValue("range", out rangeValue))
                    {
                        byte[] buffer;

                        // Send the chunk they want. Only works for bytes=%d-%d
                        rangeValue = rangeValue.Replace(" ", "");
                        rangeValue = rangeValue.Remove(0, "bytes=".Length);
                        string[] bytes = rangeValue.Split('-');
                        int      start = int.Parse(bytes[0]), end = int.Parse(bytes[1]), totalRead = 0;
                        buffer = new byte[end - start];

                        using (BufferedStream reader = new BufferedStream(file.OpenReadOnly()))
                        {
                            // Add header = content-range: bytes %d-%d/%d
                            req.Headers["content-range"] = "bytes " + rangeValue + "/" + reader.Length;

                            req.WritePreBody(206, buffer.Length);

                            while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                req.WriteFile(buffer, totalRead, bytesRead);

                                totalRead += bytesRead;
                            }
                        }
                    }
                    else
                    {
                        // Send the entire thing
                        BufferedStream reader = new BufferedStream(file.OpenReadOnly());
                        byte[]         buffer = new byte[8 * 1024];

                        req.WritePreBody(200, reader.Length);

                        while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            req.WriteFile(buffer, 0, bytesRead);
                        }

                        reader.Close();
                    }
                }
                else
                {
                    // The URI maps to something that doesn’t exist in the file system
                    req.WriteNotFoundResponse("<h1>404</h1><br><b>Content not found</b>");
                }
            }
            catch (Exception)
            {
                return;
            }
        }
Esempio n. 18
0
        private void RespondWithFile(File422 file, WebRequest req)
        {
            StringBuilder resp       = new StringBuilder();
            string        ext        = Path.GetExtension(file.Name).ToLower();
            var           fileStream = file.OpenReadOnly();
            int           bytesRead  = -1;

            byte[] buffer        = new byte[8192];
            string contentType   = "text/plain";
            string statusCode    = "200 OK";
            long   rangeBegin    = 0;
            long   rangeEnd      = (fileStream.Length - 1);
            long   contentLength = fileStream.Length - 1;

            if (req.getHeader("range") != null)
            {
                statusCode = "206 Partial Content";

                // need to determine what bytes they want
                string   r          = req.getHeader("range");
                string[] firstSplit = r.Split('=');
                //firstSplit[1] now has the range

                string[] range = firstSplit[1].Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);

                //now range should have two pieces if it is a range
                // one piece if it is requesting from front or back of file
                // determine where the - is to figure out which, this is stored in firstSplit[1] still
                long a = 0;
                long b = 0;
                if (range.Length == 2)
                {
                    long.TryParse(range[0], out a);
                    long.TryParse(range[1], out b);
                    rangeBegin = a;
                    rangeEnd   = b;
                }
                else
                {
                    if (firstSplit[1][0] == '-')
                    {
                        //wants the back of the file
                        long.TryParse(range[0], out a);
                        rangeBegin = (fileStream.Length - 1 - a);
                        rangeEnd   = (fileStream.Length - 1);
                    }
                    else
                    {
                        // wants the front of the file
                        long.TryParse(range[0], out a);
                        rangeBegin = a;
                        rangeEnd   = (fileStream.Length - 1);
                    }
                }
                contentLength = rangeEnd - rangeBegin;
            }
            // determine type of file
            if (ext == ".jpeg" || ext == ".jpg")
            {
                contentType = "image/jpeg";
            }
            else if (ext == ".png")
            {
                contentType = "image/png";
            }
            else if (ext == ".pdf")
            {
                contentType = "application/pdf";
            }
            else if (ext == ".mp4")
            {
                contentType = "video/mp4";
            }
            else if (ext == ".txt")
            {
                contentType = "text/plain";
            }
            else if (ext == ".html")
            {
                contentType = "text/html";
            }
            else if (ext == ".xml")
            {
                contentType = "application/xml";
            }

            if (contentLength == 0)
            {
                contentLength = 1;
            }

            resp.Append("HTTP/1.1 " + statusCode + "\r\nContent-Type:" + contentType + "\r\n" + "Content-Length:" + contentLength.ToString() + "\r\nAccept-Ranges: bytes\r\n");

            if (req.getHeader("range") != null)
            {
                // add on content-range
                resp.Append("Content-Range: bytes " + rangeBegin.ToString() + "-" + rangeEnd.ToString() + "/" + fileStream.Length.ToString() + "\r\n");
            }
            resp.Append("\r\n");

            Console.WriteLine("RESPONSE");
            Console.WriteLine(resp.ToString());

            req.WriteFileResponse(Encoding.ASCII.GetBytes(resp.ToString()));

            if (req.getHeader("range") != null)
            {
                fileStream.Position = rangeBegin;
                while (bytesRead != 0)
                {
                    try{
                        int readAmmount = Convert.ToInt32(Math.Max(buffer.Length, fileStream.Position - rangeEnd));
                        bytesRead = fileStream.Read(buffer, 0, readAmmount);
                        req.WriteFileResponse(buffer);
                    }
                    catch {
                    }
                }
            }
            else
            {
                while (bytesRead != 0)
                {
                    try{
                        bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                        req.WriteFileResponse(buffer);
                    }
                    catch {
                    }
                }
            }

            return;
        }