public override void Handler(WebRequest req) { try { req.WriteHTMLResponse(string.Format(c_template, req.Method, req.URI, req.Body.Length, "11337255")); } catch (Exception ex) { req.WriteHTMLResponse(string.Format(c_template, req.Method, req.URI, 0, "11337255")); } }
private void RespondWithList(Dir422 dir, WebRequest req) { string html = BuildDirHTML(dir); html += "</html>"; req.WriteHTMLResponse(html); }
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 }
public void HandlePut(WebRequest req, Dir422 dir) { File422 file = dir.CreateFile(req.URI.Split('/', '\\').Last()); Stream outputStream = file.OpenReadWrite(); Stream inputStream = req._networkStream; inputStream.ReadTimeout = 1000; int BUFFER_SIZE = 8000; int bytesRead = 0; byte[] bytes = new byte[BUFFER_SIZE]; try { bytesRead = inputStream.Read(bytes, 0, bytes.Length); } catch { } while (bytesRead != 0) { // Translate data bytes to a ASCII string. outputStream.Write(bytes, 0, bytesRead); bytes = new byte[BUFFER_SIZE]; try { bytesRead = inputStream.Read(bytes, 0, bytes.Length); } catch { break; } Console.WriteLine(bytesRead.ToString()); } req.WriteHTMLResponse("Hello"); outputStream.Close(); inputStream.Close(); }
public override void Handler(WebRequest req) { // TODO maybe change this var url = req.RequestTarget.Substring("/files/".Length); if (url.Length == 0) { Console.WriteLine("Root requested"); req.WriteHTMLResponse(BuildDirHTML(fileSystem.GetRoot())); return; } if (url.EndsWith("/")) { url = url.Remove(url.Length - 1, 1); } var dir = getParentDir(url); Console.WriteLine(url); var tokens = url.Split('/'); var fileOrFolderName = tokens [tokens.Length - 1]; if (dir == null) { Console.WriteLine("Not found null"); return; } else if (dir.ContainsFile(fileOrFolderName, false)) { Console.WriteLine("file"); SendFile(dir.GetFile(fileOrFolderName), req); } else if (dir.ContainsDir(fileOrFolderName, false)) { Console.WriteLine("folder: {0}, parent: {1}", fileOrFolderName, dir.GetDir(fileOrFolderName).Name); req.Headers = new System.Collections.Concurrent.ConcurrentDictionary <string, string> (); req.WriteHTMLResponse(BuildDirHTML(dir.GetDir(fileOrFolderName))); } else { req.WriteNotFoundResponse(@"<h1>File not found</h1>"); } Console.WriteLine("done"); }
private static void ThreadWork() { Client client = null; //Try to dequeue a client to perform work _Clients.TryDequeue(out client); //Build a web request WebRequest wr = null; //Check for malicious request greater than 10 seconds Thread thr = new Thread(() => { wr = BuildRequest(client.GetClient); }); try { thr.Start(); if (!thr.Join(TimeSpan.FromSeconds(10))) { TerminateSocketConnection(client); return; } } catch (Exception e) { Console.WriteLine(e); } //If it is not a valid request then close the client connection and return the thread to wait if (wr == null) { TerminateSocketConnection(client); } else { //Need a boolean flag to see if a service was found for the web request bool foundService = false; /*We will use a simple definition of how to know whether or not a WebService object can handle * a request: if the request-target/URI starts with the string specified by the WebService object’s * ServiceURI parameter, then it can process that request.*/ foreach (WebService ws in _Services) { if (wr.RequestURI.StartsWith(ws.ServiceURI)) { ws.Handler(wr); foundService = true; } } //If no service was found, then return a 404 response if (!foundService) { wr.WriteHTMLResponse("<html>404: Page not found </html>"); } TerminateSocketConnection(client); } }
public override void Handler(WebRequest req) { string temp = String.Format(c_template, req.HTTPMethod, req.RequestURI, 0, 11114444); temp = String.Format(c_template, req.HTTPMethod, req.RequestURI, Encoding.ASCII.GetByteCount(temp), 11114444); req.WriteHTMLResponse(temp); }
public override void Handler(WebRequest req) { req.HTTP_method = req.HTTP_method.Substring(0, 3); int byteCount = System.Text.ASCIIEncoding.Unicode.GetByteCount(c_template); string respond = String.Format(c_template, req.HTTP_method, req.URI, byteCount.ToString(), "11395829"); req.WriteHTMLResponse(respond); }
public override void Handler(WebRequest req) { string c_template = "<html>This is the response to the request:<br>" + "Method: {0}<br>Request-Target/URI: {1}<br>" + "Request body size, in bytes: {2}<br><br>" + "Student ID: {3}</html>"; try { req.WriteHTMLResponse(String.Format(c_template, req.Method, req.URI, req.Length, 11354621)); } catch { req.WriteHTMLResponse(String.Format(c_template, req.Method, req.URI, -1, 11354621)); } }
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 request) { _request = request; // cREATE response string response = FormatResponseTemplate(c_template); // Write response Console.WriteLine("About to Write to the networkStream"); bool writeSuccessful = request.WriteHTMLResponse(response); Console.WriteLine("DemoService Response Write status: " + writeSuccessful); }
private void RespondWithList(Dir422 dir, WebRequest req) { var html = new System.Text.StringBuilder("<html>"); var files = dir.GetFiles(); var dirs = dir.GetDirs(); string dirPath = ""; Dir422 temp = dir; dirPath = "/files"; string tempPath = ""; while (temp.Parent != null) { tempPath = "/" + temp.Name + tempPath; temp = temp.Parent; } dirPath = dirPath + tempPath + "/"; html.Append("<h1> Folders</h1>"); foreach (var d in dirs) { string href = dirPath + d.Name; html.AppendFormat("<a href=\"{0}\">{1}</a><br />", href, d.Name); } html.Append("<h1> Files</h1>"); foreach (var f in files) { // makesure dirPath has only one / at the end // TODO string href = dirPath + f.Name; html.AppendFormat("<a href=\"{0}\">{1}</a><br />", href, f.Name); } html.Append("</HTML>"); req.WriteHTMLResponse(html.ToString()); Console.WriteLine("SENT LIST"); return; }
public override void Handler(WebRequest request) { string body; try { body = request._body.Length.ToString(); } catch { body = "BodyLengthUnknown"; } string uri = request.RequestTarget; string id = "11259460"; string method = request.Method; string response = String.Format(c_template, method, uri, body, id); request.WriteHTMLResponse(response); }
public override void Handler(WebRequest req) { Tuple <string, string> t; bool success = req.Headers.TryGetValue("Content-Length".ToLower(), out t); string requestBodySize = "0"; //no content-length provided. if (success) { requestBodySize = t.Item2; } string formattedString = String.Format(c_template, req.Method, req.RequestTarget, requestBodySize, "11346814"); req.WriteHTMLResponse(formattedString); }
/* * Don’t allow overwriting existing files * Allow all (non-existing-file-overwriting) uploads provided the file name doesn’t contain reserve characters (/ and \) * Files can be uploaded to any directory that the service shares * Files must be uploaded into the current directory that the user is seeing the listing for within the browser * There is no limit on file sizes or content * You only need to support uploading 1 file at a time (1 per page refresh, as described below) * You do NOT need to support cross-origin requests or the OPTIONS method, which will have been discussed in class * */ void handlePUT(WebRequest req) { string[] path = req.URI.Split('/'); // The file already exists if (fileSystem.GetRoot().ContainsFile(path[path.Length - 1], true)) { req.WriteNotFoundResponse("File exists"); } // Make file else { 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.CreateFile(path[path.Length - 1]); using (Stream stream = file.OpenReadWrite()) { byte[] buffer = new byte[1024 * 8]; int bytesRead = 0, size = int.Parse(req.Headers["content-length"]), totalRead = 0; while (totalRead < size) { bytesRead = req.Body.Read(buffer, 0, (size - totalRead > buffer.Length) ? buffer.Length : size - totalRead); totalRead += bytesRead; Console.WriteLine(totalRead < size); stream.Write(buffer, 0, (bytesRead < size) ? bytesRead : size); } } Console.WriteLine("File uploaded"); req.WriteHTMLResponse("file uploaded!"); } }
public override void Handler(WebRequest req) { string bodyLength; try { // If the req had a content length header, // this will work bodyLength = req.BodyLength.ToString(); } catch { // otherwise, it will throw an exception because // we do not know the length. bodyLength = "Undefined"; } req.WriteHTMLResponse(string.Format(c_template, req.Method, req.URI, bodyLength, "11398813")); }
private void PUTHandler(WebRequest req, string name, Dir422 dir) { if (dir.ContainsFile(name, false) || name.Contains("\\") || name.Contains("/")) { string bodyMessage = "Invalid: File already exists or filename is invalid"; string template = "HTTP/1.1 400 Bad Request\r\n" + "Content-Type: text/html\r\n" + "Content-Length: {0}\r\n\r\n" + "{1}"; string response = string.Format(template, Encoding.ASCII.GetBytes(bodyMessage).Length, bodyMessage); byte[] responseBytes = Encoding.ASCII.GetBytes(response); req.WriteResponse(responseBytes, 0, responseBytes.Length); return; } File422 file = dir.CreateFile(name); FileStream fs = (FileStream)file.OpenReadWrite(); long fileSize = 0; Int64.TryParse(req.BodySize, out fileSize); int totalread = 0; while (true) { byte[] buf = new byte[4096]; int read = req.Body.Read(buf, 0, buf.Length); fs.Write(buf, 0, read); totalread += read; if ((read == 0) || read < buf.Length && totalread >= fileSize) { break; } } fs.Dispose(); fs.Close(); req.WriteHTMLResponse("Successfully uploaded file: " + name); }
public override void Handler(WebRequest req) { req.WriteHTMLResponse(c_template); }
public override void Handler(WebRequest req) { string html = String.Format(c_template, req.Method, req.URI, req.Length, "11239845"); req.WriteHTMLResponse(html); }
public override void Handler(WebRequest req) { req.WriteHTMLResponse(string.Format(c_template, req.HTTPMethod, req.RequestURI, req.BodySize, "11216720", DateTime.Now.ToString("h:mm:ss"))); }
private void UploadFile(WebRequest req) { string[] pieces = req.URI.Substring(ServiceURI.Length).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (pieces == null || pieces.Length == 0) { req.WriteNotFoundResponse("404: Path error."); return; } Dir422 dir = r_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; } } File422 file = dir.GetFile(PercentDecoding(pieces[pieces.Length - 1])); if (file != null) { req.WriteHTMLResponse("<html> File Already Exists! </html>"); return; } File422 newFile = dir.CreateFile(PercentDecoding(pieces[pieces.Length - 1])); FileStream str = (newFile.OpenReadWrite() as FileStream); Stream reqStr = req.Body; byte[] buf = new byte[4096]; long len = req.Len; if (len < 4096) { reqStr.Read(buf, 0, (int)len); str.Write(buf, 0, (int)len); str.Close(); return; } int count = reqStr.Read(buf, 0, 4096); int totalRead = count; while (count != 0 && totalRead < len) { str.Write(buf, 0, count); buf = new byte[4096]; count = reqStr.Read(buf, 0, 4096); totalRead += count; } // If bytes were read last time, trim zeroes and write last bit if (count != 0) { str.Write(buf, 0, count); } str.Close(); req.WriteHTMLResponse("<html> Upload Successful! </html>"); return; }
public override void Handler(WebRequest req) { req.WriteHTMLResponse(string.Format(c_template, req.httpMethod, req.URI, req.bodyLength, "11349302")); }
public override void Handler(WebRequest req) { req.WriteHTMLResponse(String.Format(RESPONSE_TEMPLATE, req.Method, req.RequestTarget, RESPONSE_TEMPLATE.Length + "11404808".Length, "11404808")); }
private void RespondWithList(Dir422 dir, WebRequest req) { req.WriteHTMLResponse(BuildDirHTML(dir).ToString()); }
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; } }
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"); } } }
private void DoUpload(WebRequest req, string percenDecoded) { string fileName = ""; Dir422 currentDir = null; if (percenDecoded == ServiceURI) { currentDir = r_sys.GetRoot(); } else { // The pluse one is the '/' after the '/files' so we remove '/files/' string[] pathPeices = percenDecoded.Substring(ServiceURI.Length + 1).Split('/'); currentDir = r_sys.GetRoot(); for (int i = 0; i < pathPeices.Length - 1; i++) { currentDir = currentDir.GetDir(pathPeices[i]); if (currentDir == null) { req.WriteNotFoundResponse(string.Empty); return; } } fileName = pathPeices [pathPeices.Length - 1]; } File422 newFile = currentDir.CreateFile(fileName); if (newFile == null) { // We could not create a new file return; } Stream s = newFile.OpenReadWrite(); if (s == null) { return; } byte[] bodyBytes = new byte[1024]; long bytesRead = 0; //Read all that we can. while (bytesRead < req.BodyLength) { // We need to read chuncks at a time since read wants an int // as the count, and we may loose data if we cast a long to an int. int read = req.Body.Read(bodyBytes, 0, 1024); bytesRead += read; if (read == 0) { break; } s.Write(bodyBytes, 0, read); Array.Clear(bodyBytes, 0, bodyBytes.Length); } s.Close(); req.WriteHTMLResponse(""); return; }