Dir422 getParentDir(string path) { var dirStructure = path.Split('/'); if (dirStructure.Length == 1 && dirStructure [0].Length == 0) { return(fileSystem.GetRoot()); } Console.WriteLine(dirStructure [0]); var root = fileSystem.GetRoot(); int i = 0; for (i = 0; i < dirStructure.Length - 1; i++) { if (!root.ContainsDir(dirStructure[i], false)) { return(null); } else { root = root.GetDir(dirStructure[i]); } } return(root); }
public override void Handler(WebRequest req) { if (!req.URI.StartsWith(this.ServiceURI)) { throw new InvalidOperationException(); } // Percent-decode our filename string percenDecoded = Uri.UnescapeDataString(req.URI); //If we want the root folder if (percenDecoded == ServiceURI) { RespondWithList(r_sys.GetRoot(), req); return; } // The pluse one is the '/' after the '/files' so we remove '/files/' string[] peices = percenDecoded.Substring(ServiceURI.Length + 1).Split('/'); Dir422 dir = r_sys.GetRoot(); for (int i = 0; i < peices.Length - 1; i++) { dir = dir.GetDir(peices[i]); if (dir == null) { //This wants a response? req.WriteNotFoundResponse(string.Empty); return; } } string lastPeice = peices [peices.Length - 1]; File422 file = dir.GetFile(lastPeice); if (file != null) { //Send back the file to them. RespondWithFile(file, req); } else { //Send the dir contents (if it is a dir to send back) dir = dir.GetDir(lastPeice); if (dir != null) { //Respond with the list of files and dirs RespondWithList(dir, req); } else { req.WriteNotFoundResponse(string.Empty); } } }
private void GetHandler(WebRequest req) { //NOTE use Uri.UnescapeDataString to convert the escaped string //to it's unescaped representation. //i.e if we get http://localhost:4220/%20test/ //would become http://localhost:4220/ test/ string[] names = Uri.UnescapeDataString(req.RequestTarget).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); //first name is files. string currString = ""; Dir422 currNode = _fs.GetRoot(); //root is what we chose, the client knows it as "files". Dir422 nextNode = null; File422 file = null; int uriCase = 1; for (int i = 1; i < names.Length; i++) { currString = names[i]; if ((nextNode = currNode.GetDir(currString)) != null) { //go to next dir to repeat iteration. currNode = nextNode; } else if ((file = currNode.GetFile(currString)) != null) { uriCase = 2; break; } else { uriCase = 3; break; } } switch (uriCase) { //URI maps to an existing directory in the file system. case 1: string htmlString = BuildDirHTML(currNode); req.WriteHTMLResponse(htmlString); break; //The URI maps to an existing file in the file system case 2: SendFileContent(file, req); break; //The URI maps to something that doesn’t exist in the file system case 3: req.WriteNotFoundResponse(errorHtml); break; } }
public override void Handler(WebRequest req) { if (!req.requestTarget.StartsWith("/files")) { throw new Exception(); } if (req.requestTarget == "/files" || req.requestTarget == "files" || req.requestTarget == "/files/") { RespondWithList(_fs.GetRoot(), req); return; } var dir = _fs.GetRoot(); string newRequestTarget = System.Uri.UnescapeDataString(req.requestTarget.Substring(ServiceURI.Length)); string[] uriPieces = newRequestTarget.Split(new char[1] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (null == uriPieces || uriPieces.Length == 0) { req.WriteNotFoundResponse("NOT FOUND"); return; } for (int i = 0; i < uriPieces.Length - 1; i++) { string uriPiece = uriPieces[i]; dir = dir.GetDir(uriPiece); if (null == dir) { req.WriteNotFoundResponse("NOT FOUND"); return; } } var file = dir.GetFile(uriPieces[uriPieces.Length - 1]); if (null != file) { RespondWithFile(file, req); return; } dir = dir.GetDir(uriPieces[uriPieces.Length - 1]); if (dir == null) { req.WriteNotFoundResponse("NOT FOUND"); return; } RespondWithList(dir, req); }
public override void Handler(WebRequest req) { if (!req.RequestURI.StartsWith(ServiceURI, StringComparison.CurrentCulture)) { throw new InvalidOperationException(); } if (req.RequestURI == "/files" || req.RequestURI == "/files/") { RespondWithList(m_fs.GetRoot(), req); return; } string[] pieces = req.RequestURI.Substring(ServiceURI.Length).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (pieces == null || pieces.Length == 0) { req.WriteNotFoundResponse("404: Path error."); return; } Dir422 dir = m_fs.GetRoot(); for (int i = 0; i < pieces.Length - 1; i++) { string piece = pieces[i]; dir = dir.GetDir(piece); if (dir == null) { req.WriteNotFoundResponse("404: Path error."); return; } } string name = PercentDecoding(pieces[pieces.Length - 1]); File422 file = dir.GetFile(name); if (file != null) { RespondWithFile(file, req); return; } dir = dir.GetDir(name); if (dir == null) { req.WriteNotFoundResponse("404: Path error."); return; } RespondWithList(dir, req); }
string BuildDirHTML(Dir422 directory) { StringBuilder builder = new StringBuilder(); // Styling builder.Append("<html>"); builder.Append("<head><style>"); // It's gotta look stylish right? builder.Append(" tr:nth-child(even) {background-color: #f2f2f2} "); builder.Append(" table { text-align : center; border: 2px solid black } "); builder.Append(" .center { position: absolute; width : 75%; left: 12.5% } "); builder.Append(" h1 { font-size: 4em } "); builder.Append(" a { font-size: 2em } "); builder.Append("</style>"); builder.Append("</head>"); builder.Append("<body style='text-align:center'><div class='center'>"); builder.Append("<h1>Directories</h1>"); // Get all directories builder.Append("<table width='100%'>"); foreach (var dir in directory.GetDirs()) { // Need to get rid of '**/{current_dir}/' in uri string uri = ServiceURI + "/" + FullPath.Make(directory, Uri.EscapeDataString(dir.Name)).Replace(fileSystem.GetRoot().Name + "/", ""); builder.Append("<tr><td><a href='" + uri + "'>" + dir.Name + "</a></td></tr>"); } builder.Append("</table>"); builder.Append("<h1>Files</h1>"); // Get all files builder.Append("<table width='100%'>"); foreach (var file in directory.GetFiles()) { // Need to get rid of '**/{current_dir}/' in uri string uri = ServiceURI + "/" + FullPath.Make(directory, Uri.EscapeDataString(file.Name)).Replace(fileSystem.GetRoot().Name + "/", ""); builder.Append("<tr><td><a href='" + uri + "'>" + file.Name + "</a></td></tr>"); } builder.Append("</table>"); // Add the abillity to upload files if (allowUploads) { builder.Append(SCRIPT); builder.AppendFormat( "<hr><h3 id='uploadHdr'>Upload</h3><br>" + "<input id=\"uploader\" type='file' " + "onchange='selectedFileChanged(this,\"{0}\")' /><hr>", GetHREF(directory, true)); } builder.Append("</div></body></html>"); return(builder.ToString()); }
// Methods public override void Handler(WebRequest request) { Console.WriteLine("Service Handler: OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"); _request = request; // Parse the URI and determine which of the 3 is the case: string[] parsedURI = request.URI.Split('/'); List <string> dirNames = new List <string>(); int count = 0; foreach (string s in parsedURI) { if (count > 1)// so we only have traversable dirnames { Console.WriteLine("adding: " + parsedURI[count]); dirNames.Add(parsedURI[count]); } Console.WriteLine("s: " + s); Console.WriteLine("c: " + count); count++; } Console.WriteLine("dirNames.Count: " + dirNames.Count); Dir422 currentDir = _fs.GetRoot(); Dir422 lastDir; File422 file = null; foreach (string s in dirNames) { if (!String.IsNullOrEmpty(s)) { Console.WriteLine("locating: " + s); lastDir = currentDir; currentDir = currentDir.GetDir(s); if (null == currentDir) // check to see if a file { Console.WriteLine("Null Dir"); file = lastDir.GetFile(s); if (null == file) { Console.WriteLine("Null File"); //requested Resource does not exist // so 404 write to network and return request.WriteNotFoundResponse("Could not find file: " + s + "."); return; } // otherwise write file contents as html WriteFileContents(file); return; } } } // If this point is reached then we should have a dir and // we must write its file listing to the network WriteDirListing(currentDir); // Provide support for partial content responses // (i.e. support the Range header) }
public override void Handler(WebRequest req) { if (!req.URI.StartsWith(ServiceURI, StringComparison.Ordinal)) { throw new InvalidOperationException(); } //split the path string[] places = req.URI.Substring(ServiceURI.Length).Split('/'); Dir422 dir = r_sys.GetRoot(); for (int i = 0; i < places.Length - 1; i++) { dir = dir.GetDir(places[i]); if (dir == null) { req.WriteNotFoundResponse(""); return; } } File422 file = dir.GetFile(places[places.Length - 1]); if (file != null) { RespondWithFile(file, req); } else { dir = dir.GetDir(places[places.Length - 1]); if (dir != null) { RespondWithList(dir, req); } else { req.WriteNotFoundResponse(""); } } }
public override void Handler(WebRequest req) { if (req.URI.Length < this.ServiceURI.Length) { req.URI = this.ServiceURI; } if (!req.URI.StartsWith(this.ServiceURI)) { throw new InvalidOperationException(); } uriPath = req.URI; string[] pieces = req.URI.Substring(ServiceURI.Length).Split('/'); //split up the path by '/' tokens if (pieces.Length == 1 && pieces[0] == "") //we passed in only the root { RespondWithList(r_sys.GetRoot(), req); } for (int x = 0; x < pieces.Length; x++) { pieces[x] = decode(pieces[x]); } Dir422 dir = r_sys.GetRoot(); //grab the root of the filesystem if (req.httpMethod == "PUT") //if the method is put. { foreach (Tuple <string, string> header in req.headers) { if (header.Item1 == "Content-Length") { if (Convert.ToInt64(header.Item2) <= 0) { req.WriteInvalidUpload("400"); return; } } } for (int i = 0; i < pieces.Length - 1; i++) //go through the parts of the path { dir = dir.getDir(pieces[i]); if (dir == null) //if you encounter a directory that doesn't exist, tell the user that the target they requested is not found and return { req.WriteNotFoundResponse("File not found.\n"); return; } } File422 fileToCreate = dir.GetFile(pieces[pieces.Length - 1]); //grab the last file of the path if (fileToCreate == null) { string pathName = StandardFileSystem.rootPath; for (int i = 0; i < pieces.Length; i++) { pathName += "/"; pathName += pieces[i]; } FileStream fs = new FileStream(pathName, FileMode.Create, FileAccess.ReadWrite); int x = 0; byte[] bodyBytes = new byte[4096]; string bodyContent = ""; x = req.bodyStream.Read(bodyBytes, 0, 4096); fs.Write(bodyBytes, 0, 4096); while (x > 0) { bodyContent += Encoding.ASCII.GetString(bodyBytes); x = req.bodyStream.Read(bodyBytes, 0, 4096); fs.Write(bodyBytes, 0, 4096); } fs.Close(); req.WriteHTMLResponse("200 OK"); } else { req.WriteInvalidUpload("File already exists"); } return; } for (int i = 0; i < pieces.Length - 1; i++) //go through the parts of the path { dir = dir.getDir(pieces[i]); if (dir == null) //if you encounter a directory that doesn't exist, tell the user that the target they requested is not found and return { req.WriteNotFoundResponse("File not found.\n"); return; } } //we now have the directory of one above the file / directory //one piece to process left //check if dir is in the last piece we have File422 file = dir.GetFile(pieces[pieces.Length - 1]); //grab the last file of the path if (file != null) { RespondWithFile(file, req); } else { dir = dir.getDir(pieces[pieces.Length - 1]); //if it wasn't a file, grab it as a dir if (dir != null) { RespondWithList(dir, req); } else //if it's null, tell the user it was not found { req.WriteNotFoundResponse("Not found\n"); } } }
public override void Handler(WebRequest req) { //Every request should start with /files/ if (!req.URI.StartsWith(this.ServiceURI)) { throw new InvalidOperationException(); } //percent-decode URI string uri = req.URI; string[] pieces = req.URI.Substring(ServiceURI.Length).Split('/', '\\'); Dir422 dir = _fs.GetRoot(); //Grabs all the parts but the last part, which could be a file or a dir string piece = ""; for (int i = 1; i < pieces.Length - 1; i++) { piece = pieces[i]; //if (piece.Contains("%20")) piece = piece.Replace("%20", " "); dir = dir.GetDir(piece); //Check if directory exists if (dir == null) { req.WriteNotFoundResponse(); return; } } //Check if the last part is a file or a directory piece = pieces[pieces.Length - 1]; //if (piece.Contains("%20")) piece = piece.Replace("%20", " "); File422 file = dir.GetFile(piece); //TODO: This is returning Null and is not supposed to. if (file == null && req.Method == "PUT") { HandlePut(req, dir); return; } if (file != null) { //If it's a file, then return the file. Console.WriteLine("It's a file!"); RespondWithFile(file, req); } else { piece = pieces[pieces.Length - 1]; //if (piece.Contains("%20")) piece = piece.Replace("%20", " "); if (piece != "") { dir = dir.GetDir(piece); } if (dir != null) { //If it's a dir, return the dir RespondWithList(dir, req); } else { //Else return that nothing was found. req.WriteNotFoundResponse(); } } }
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); }
public override void Handler(WebRequest Req) { Dir422 Root = m_FS.GetRoot(); //Remove Last / here!!!! if (Req.URI.LastIndexOf('/') == Req.URI.Length - 1) { Req.URI = Req.URI.Substring(0, Req.URI.Length - 1); } //int x = 0; //1. Percent-decode URI. // THIS NOT GOOD ENOUGH!!! Req.URI = Utility.PercentDecode(Req.URI); //string test = Req.URI.Replace ("%20", " ");; // Set name of requested file||dir. string uriName = Utility.NameFromPath(Req.URI); //2. If it refers to file somewhere in the shared folder. if (Root.ContainsFile(uriName, true)) { string path = Req.URI.Substring(0, Req.URI.LastIndexOf("/")); Dir422 Dir = Utility.TraverseToDir(Root, path); StdFSFile File = (StdFSFile)Dir.GetFile(uriName); FileStream MyFileStream = (FileStream)File.OpenReadOnly(); if (Req.headers.ContainsKey("Range")) { // process partial response here Console.WriteLine("Process Partial Request"); int x = 0; } else { string contentType = Utility.ContentType(uriName); string response = Utility.BuildFileResponseString( MyFileStream.Length.ToString(), contentType); //if (contentType != "video/mp4") //{ byte[] sendResponseString = Encoding.ASCII.GetBytes(response); Req.bodyRequest.Write(sendResponseString, 0, sendResponseString.Length); //} //byte[] sendResponseString = Encoding.ASCII.GetBytes(response); int read = 0; byte[] send = new byte[7500]; while (read < MyFileStream.Length) { read = read + MyFileStream.Read(send, 0, send.Length); Req.bodyRequest.Write(send, 0, send.Length); } } } //3. Else if it refers to a folder somewhere in the shared folder. // Or is the shared directory else if (Root.ContainsDir(uriName, true) || Req.URI == ServiceURI || uriName == "") { if (Req.URI == ServiceURI || uriName == "") { string dirHTMLListing = BuildDirHTML(Root); byte[] sendResponseString = Encoding.ASCII.GetBytes(dirHTMLListing); Req.bodyRequest.Write(sendResponseString, 0, sendResponseString.Length); //Req.WriteHTMLResponse (dirHTMLListing); } else { Dir422 Dir = Utility.TraverseToDir(Root, Req.URI); string dirHTMLListing = BuildDirHTML(Dir); byte[] sendResponseString = Encoding.ASCII.GetBytes(dirHTMLListing); Req.bodyRequest.Write(sendResponseString, 0, sendResponseString.Length); //Req.WriteHTMLResponse (dirHTMLListing); } } //4.Else it’s a bad URI. else { Req.WriteNotFoundResponse("File or directory not found"); } }