private Dir422 TraverseToDirectory(Dir422 currentLocation, string[] uriPieces, WebRequest req)
        {
            File422 fileAtRoot = null;

            //Iterate over all path parts until we get to the file or directory wanted
            for (int item = 0; item < uriPieces.Length - 1; item++)
            {
                fileAtRoot = currentLocation.GetFile(uriPieces[item]);

                if (fileAtRoot == null)
                {
                    currentLocation = currentLocation.GetDir(uriPieces[item]);

                    if (currentLocation == null)
                    {
                        req.WriteNotFoundResponse("<html>404 File Not Found<br>" + "</html>");
                    }
                }
                else
                {
                    break;
                }
            }

            return(currentLocation);
        }
Example #2
0
        //Create a new directory. If the directory exists then just return
        //an instance of it.
        public override Dir422 CreateDir(string dirName)
        {
            if (!CheckValidName(dirName))
            {
                return(null);
            }

            Dir422 newDir = null;

            if (Directory.Exists(_path + "/" + dirName))
            {
                newDir = GetDir(dirName);
            }
            else
            {
                try
                {
                    Directory.CreateDirectory(_path + "/" + dirName);
                    newDir = new StdFSDir(_path + "/" + dirName);
                }
                catch (Exception e)
                {
                    newDir = null;
                }
            }

            return(newDir);
        }
        private string BuildDirHTML(Dir422 Dir)
        {
            var html = new System.Text.StringBuilder("<html>");

            html.AppendLine(@"<script>
				function selectedFileChanged(fileInput, urlPrefix) {
				document.getElementById('uploadHdr').innerText = 'Uploading ' + fileInput.files[0].name + '...';
				// Need XMLHttpRequest to do the upload
				if (!window.XMLHttpRequest)
				{
					alert('Your browser does not support XMLHttpRequest. Please update your browser.');
					return;
				}
				// Hide the file selection controls while we upload
				var uploadControl = document.getElementById('uploader');
				if (uploadControl)
				{
					uploadControl.style.visibility = 'hidden';
				}
				// Build a URL for the request
				if (urlPrefix.lastIndexOf('/') != urlPrefix.length - 1)
				{
					urlPrefix += '/';
				}
                var uploadURL = urlPrefix + fileInput.files[0].name;
				// Create the service request object
				var req = new XMLHttpRequest();
				req.open('PUT', uploadURL);
				req.onreadystatechange = function() {
					document.getElementById('uploadHdr').innerText = 'Upload (request status == ' + req.status + ')';
					location.reload();
					document.getElementById('responseMessage').innerHTML= req.responseText;
				};
				req.send(fileInput.files[0]);
			}
			</script> "            );

            //Add all filenames and links
            html.AppendLine("<h1>Files</h1>");
            foreach (File422 file in Dir.GetFiles())
            {
                string encodedName = file.Name.Replace("#", "%23");
                html.AppendFormat("<a href=\"{0}\">{1}</a><br>", BuildPath(null, file) + "/" + encodedName, file.Name);
            }

            //Add all directories and links
            html.AppendLine("<br><h1>Directories</h1>");
            foreach (Dir422 dir in Dir.GetDirs())
            {
                html.AppendFormat("<a href=\"{0}\">{1}</a><br>", BuildPath(dir, null), dir.Name);
            }

            html.AppendFormat("<hr><h3 id='uploadHdr'>Upload</h3><br>" +
                              "<input id=\"uploader\" type='file' " + "onchange='selectedFileChanged(this,\"{0}\")' /><h2 id='responseMessage'></h2><hr>", BuildPath(Dir, null));

            //Close page tags
            html.AppendLine("</html>");

            return(html.ToString());
        }
        private string BuildPath(Dir422 dir, File422 file)
        {
            Dir422 tempDir;

            //Check if we are building a path for a file or a directory
            if (file != null)
            {
                tempDir = file.Parent;
            }
            else
            {
                tempDir = dir;
            }

            List <string> pathItems = new List <string>();

            if (tempDir.Parent != null)
            {
                //Work our way up the tree
                while (tempDir.Parent.Parent != null)
                {
                    pathItems.Add(tempDir.Name);
                    tempDir = tempDir.Parent;
                }
            }

            string path = "";

            //Are they accessing an item in the root directory?
            if (pathItems.Count > 0)
            {
                path = "/files/" + pathItems[pathItems.Count - 1];

                for (int i = pathItems.Count - 2; i > -1; i--)
                {
                    path += "/" + pathItems[i];
                }
            }
            else
            {
                if (file != null)
                {
                    path = "/files/" + file.Name;
                }
                else
                {
                    path = "/files/" + dir.Name;
                }
            }

            return(path);
        }
Example #5
0
        public virtual bool Contains(Dir422 dir)
        {
            Dir422 parent = dir.Parent;

            while (parent.Parent != null)
            {
                parent = parent.Parent;
            }

            if (parent == GetRoot())
            {
                return(true);
            }

            return(false);
        }
Example #6
0
        public override Dir422 CreateDir(string dirName)
        {
            if (!CheckValidName(dirName))
            {
                return(null);
            }

            Dir422 newDir = GetDir(dirName);

            if (newDir == null)
            {
                newDir = new MemFSDir(dirName, this);
                _directories.Add(newDir);
            }

            return(newDir);
        }
        private string GetRangeHeader(WebRequest req, Dir422 currentLocation, string[] uriPieces)
        {
            string header = "";
            string value  = "";

            req.GetHeaders().TryGetValue("range", out value);
            value = value.Substring(6);
            string[] nums = value.Split('-');

            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i].Contains("\r\n"))
                {
                    nums[i] = nums[i].Substring(0, nums[i].LastIndexOf("\r\n"));
                }
            }

            Stream selectedFile = currentLocation.GetFile(uriPieces[uriPieces.Length - 1]).OpenReadOnly();

            long a, b;

            long.TryParse(nums[0], out a);
            long.TryParse(nums[1], out b);

            if (b == 0 && nums[1] == string.Empty)
            {
                b       = (int)selectedFile.Length;
                nums[1] = b.ToString();
            }

            long length = b - a;

            if (b == selectedFile.Length)
            {
                b = b - 1;
            }

            header = string.Format(partialFileHeaderTemplate, req.GetHTTPVersion(), GetContentType(currentLocation.GetFile(uriPieces[uriPieces.Length - 1]).Name), a, b, selectedFile.Length, length);

            selectedFile.Close();

            return(header);
        }
        public override void Handler(WebRequest req)
        {
            //If the request URI doesn't start with the proper service URI
            if (!req.GetUri().StartsWith(this.ServiceURI, StringComparison.CurrentCulture))
            {
                throw new InvalidOperationException();
            }

            //Get Uri pieces
            string[] uriPieces = GetUriPeices(req);

            //Decode path
            uriPieces = DecodePath(uriPieces);

            //Get the root directory
            Dir422 currentLocation = FileSystem.GetRoot();

            //Handle PUT requests
            if (req.GetHTTPType() == "PUT")
            {
                FileStream newFileStream = null;

                try
                {
                    currentLocation = TraverseToDirectory(currentLocation, uriPieces, req);

                    if (currentLocation.ContainsFile(uriPieces[uriPieces.Length - 1], false) == true)
                    {
                        req.WriteNotFoundResponse("<html>File Already Exists!</html>");
                    }
                    else
                    {
                        File422 newFile = currentLocation.CreateFile(uriPieces[uriPieces.Length - 1]);
                        newFileStream = (FileStream)newFile.OpenReadWrite();

                        CopyBytes(req.GetBody(), newFileStream, req.GetBody().Length);

                        newFileStream.Close();

                        string response = "<html>File Uploaded!</html>";
                        string header   = string.Format(putHeaderTemplate, req.GetHTTPVersion(), "text/html", response.Length);

                        req.WriteHTMLResponse(header + response);
                    }
                }
                catch (Exception e)
                {
                    if (newFileStream != null)
                    {
                        newFileStream.Close();
                    }
                }
            }
            //Handle GET requests
            else
            {
                //If we're at the root directory, respond with a list
                if (uriPieces.Length == 0)
                {
                    string response = BuildDirHTML(FileSystem.GetRoot());

                    string header = string.Format(dirHeaderTemplate, req.GetHTTPVersion(), "text/html", response.Length);

                    req.WriteHTMLResponse(header + response);
                }
                else
                {
                    currentLocation = TraverseToDirectory(currentLocation, uriPieces, req);

                    //If the wanted item is a file, respond with a file
                    if (currentLocation.GetFile(uriPieces[uriPieces.Length - 1]) != null)
                    {
                        //If we have a range header, we need to use a partial response header
                        if (req.GetHeaders().ContainsKey("range"))
                        {
                            string header = GetRangeHeader(req, currentLocation, uriPieces);

                            req.WriteHTMLResponse(header);
                        }
                        //Write repsonse for displaying file contents
                        else
                        {
                            Stream selectedFile = currentLocation.GetFile(uriPieces[uriPieces.Length - 1]).OpenReadOnly();
                            string header       = string.Format(fileHeaderTemplate, req.GetHTTPVersion(), GetContentType(currentLocation.GetFile(uriPieces[uriPieces.Length - 1]).Name), selectedFile.Length);
                            selectedFile.Close();

                            req.WriteHTMLResponse(header);
                        }

                        BuildFileHTML(currentLocation.GetFile(uriPieces[uriPieces.Length - 1]), req);
                    }
                    //If the wanted item is a directory, respond with a directory listing
                    else
                    {
                        //Write response for displaying directory
                        if (currentLocation.GetDir(uriPieces[uriPieces.Length - 1]) != null)
                        {
                            string response = BuildDirHTML(currentLocation.GetDir(uriPieces[uriPieces.Length - 1]));

                            string header = string.Format(dirHeaderTemplate, req.GetHTTPVersion(), "text/html", response.ToString().Length);

                            req.WriteHTMLResponse(header + response);
                        }
                        //Request item could not be found
                        else
                        {
                            req.WriteNotFoundResponse("<html>404 File Not Found<br>" + "</html>");
                        }
                    }
                }
            }
        }