Ejemplo n.º 1
0
        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);
                }
            }
        }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
        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);
        }
Ejemplo n.º 4
0
        public static bool Start(int port, int number_threads)
        {
            // Create thread to listen for incoming clients
            new Thread(() =>
            {
                // Init and start server
                TcpListener listener = new TcpListener(IPAddress.Any, port);
                listener.Start();

                threadPool.Start((ushort)number_threads);

                while (true)
                {
                    TcpClient client = listener.AcceptTcpClient();

                    // Make thread task function and add it to the ThreadPool
                    threadPool.AddTask(() =>
                    {
                        WebRequest req = BuildRequest(client);

                        // Invalid request object, close connection.
                        if (null != req)
                        {
                            // Handle that request
                            // Find services that will handle the request URI
                            int longestPrefix       = 0;
                            WebService serviceToUse = null;

                            foreach (var service in services)
                            {
                                if (req.URI.StartsWith(service.ServiceURI))
                                {
                                    // We'll select the service that has a longer prefix of the request URI and use it
                                    if (service.ServiceURI.Length > longestPrefix)
                                    {
                                        longestPrefix = service.ServiceURI.Length;
                                        serviceToUse  = service;
                                    }
                                }
                            }

                            if (null == serviceToUse)
                            {
                                // send 404 reponse
                                req.WriteNotFoundResponse("");
                            }
                            else
                            {
                                // "Handle" request
                                serviceToUse.Handler(req);
                            }
                        }

                        client.Close();
                    });
                }
            }).Start();

            return(true);
        }
Ejemplo n.º 5
0
        public void ThreadWork()
        {
            WebRequest request = BuildRequest(_client);

            if (request == null)
            {
                _client.GetStream().Dispose();
                _client.Close();
            }
            else
            {
                // we have a valid http request
                // Try to find a valid service
                foreach (var service in services)
                {
                    if (validate.URI.StartsWith(service.ServiceURI))
                    {
                        service.Handler(request);
                        break;
                    }
                    else
                    {
                        // No handler exists.
                        request.WriteNotFoundResponse("Unable to find an appropriate handler");
                    }
                }

                //Thread.Sleep (5000);
                _client.GetStream().Dispose();
                _client.Close();
            }
        }
Ejemplo n.º 6
0
        private static void ThreadWork()
        {
            while (true)
            {
                TcpClient client = _collection.Take();
                if (client == null)
                {
                    return;
                }
                WebRequest request = BuildRequest(client);

                if (request == null)
                {
                    client.Close();
                    continue;
                }

                foreach (var service in _services)
                {
                    if (request.URI.StartsWith(service.ServiceURI))
                    {
                        service.Handler(request);
                        return;
                    }
                }
                // No valid handler
                request.WriteNotFoundResponse(request.URI);
            }
        }
Ejemplo n.º 7
0
        // 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)
        }
Ejemplo n.º 8
0
        //have this write back to the request
        public override void Handler(WebRequest req)
        {
            if (!req.Headers.ContainsKey("Content-Length"))
            {
                int length = 0;

                if (req.Body != null)
                {
                    length = (int)req.Body.Length;
                }

                req.Headers.Add("Content-Length", length.ToString());
            }

            //call the service on the request
            if (req.URI.StartsWith(ServiceURI, StringComparison.Ordinal))
            {
                req.WriteHtmlResponse(string.Format(c_template, req.Method,
                                                    req.URI, req.Headers["Content-Length"],
                                                    "11382134"));
            }

            else
            {
                req.WriteNotFoundResponse(string.Format(c_template, req.Method,
                                                        req.URI, req.Headers["Content-Length"],
                                                        "11382134"));
            }
        }
Ejemplo n.º 9
0
        static void ThreadWork(object clientObj)
        {
            TcpClient  client  = clientObj as TcpClient;
            WebRequest request = BuildRequest(client);

            processCount++;
            Console.WriteLine("process: {0}", processCount);
            Console.WriteLine("Request built");
            if (request == null)
            {
                client.Close();
                Console.WriteLine("Closing connection");
                return;
            }

            var handlerService = fetchHandler(request);

            if (handlerService == null)
            {
                Console.WriteLine("Handler not found, writing not found response");
                request.WriteNotFoundResponse("NoasdasdasdasdtFound");
                client.GetStream().Dispose();
                client.Close();
            }
            else
            {
                Console.WriteLine("Handler found, delegating response");
                handlerService.Handler(request);
                client.GetStream().Dispose();
                client.Close();
            }

            client.Close();
        }
Ejemplo n.º 10
0
        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;
            }
        }
Ejemplo n.º 11
0
        //Accept TCP client and Call BulildRequest
        static void ThreadWork(Object clnt)
        {
            TcpClient client = clnt as TcpClient;

            WebRequest req = BuildRequest(client);

            WebService handler = null;;

            bool processRequest;


            if (req == null)
            {
                //close client connection
                client.GetStream().Close();
                client.Close();
            }
            else
            {
                //if the request-target/URI starts with the string specified by the WebService object’s
                //ServiceURI parameter, then it can process that request.

                processRequest = false;

                foreach (var x in servicesList)
                {
                    if (req.URI.StartsWith(x.Key))
                    {
                        processRequest = true;
                        handler        = x.Value;
                    }
                }
                if (processRequest)
                {
                    //find appropriate handler  in the list of
                    //handlers/services that the webserver stores

                    //WebService handler;
                    //servicesList.TryGetValue (req.URI, out handler);

                    //call the handle
                    handler.Handler(req);
                }
                //write a 404 – Not Found response
                else
                {
                    string pageHTML = "<html> ERROR! </html>";
                    req.WriteNotFoundResponse(pageHTML);
                }

                //client.
                client.GetStream().Close();
                client.Close();
            }
        }
Ejemplo n.º 12
0
        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("");
                }
            }
        }
Ejemplo n.º 13
0
        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");
        }
Ejemplo n.º 14
0
        public override void Handler(WebRequest req)
        {
            switch (req.Method.ToUpper())
            {
            case "GET":
                handleGET(req);
                break;

            case "PUT":
                handlePUT(req);
                break;

            default:
                req.WriteNotFoundResponse("<h1>404</h1><br/><h2><strong>Not Found</strong></h2>");
                break;
            }
        }
Ejemplo n.º 15
0
        /*
         * 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!");
            }
        }
Ejemplo n.º 16
0
        private void GETHandler(WebRequest req, string name, Dir422 dir)
        {
            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);
        }
Ejemplo n.º 17
0
        /*
         * ThreadWork function to serve as the request-handling function for a thread from the thread pool
         */
        private static void ThreadWork()
        {
            while (true)
            {
                TcpClient client = _collection.Take();
                if (client == null)
                {
                    break;
                }

                /*
                 * Processing a client involves calling the BuildRequest function first.
                 * Should the return value be null, the client connection is closed immediately
                 * and the thread goes back into a waiting/sleeping state.
                 * Should it be non-null,
                 * then an appropriate handler is found in the list of handlers/services that the web
                 * server stores, and the request is sent to that handler by calling its “Handle” function
                 */
                WebRequest request = BuildRequest(client);

                if (request == null)
                {
                    client.Close();
                }
                else
                {
                    WebService handler = Handler(request);

                    if (handler != null)
                    {
                        handler.Handler(request);
                        client.GetStream().Dispose();
                        client.Close();
                    }
                    else
                    {
                        request.WriteNotFoundResponse(request.RequestURI);
                        client.GetStream().Dispose();
                        client.Close();
                    }
                }
            }
        }
Ejemplo n.º 18
0
        static void ThreadWork(object clientObj)
        {
            TcpClient client = clientObj as TcpClient;

            while (client.Connected)
            {
                //Console.WriteLine ("about to build request");
                WebRequest request = BuildRequest(client);

                processCount++;

                //Console.WriteLine ("process: {0}", processCount);
                //Console.WriteLine ("Request built");

                if (request == null)
                {
                    //Console.WriteLine ("Closing connection");

                    client.Close();
                }
                else
                {
                    var handlerService = fetchHandler(request);

                    if (handlerService == null)
                    {
                        //Console.WriteLine ("Handler not found, writing not found response");
                        request.WriteNotFoundResponse("not found");
                    }
                    else
                    {
                        //Console.WriteLine ("Handler found, delegating response");
                        handlerService.Handler(request);
                    }
                }
                //Console.WriteLine ("Loopoing");
            }

            client.Close();
            //Console.WriteLine ("Exiting");
        }
Ejemplo n.º 19
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;
            }
        }
Ejemplo n.º 20
0
        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();
                }
            }
        }
Ejemplo n.º 21
0
        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;
        }
Ejemplo n.º 22
0
        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");
            }
        }
Ejemplo n.º 23
0
        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;
        }
Ejemplo n.º 24
0
        public static bool Start(int port, int threadCount)
        {
            //enable to true for testing with console outputs.
            bool test = false;

            //you need at least one to listen and additional for TCP sockets.
            threadCount = (threadCount <= 0) ? threadCount = 64 : threadCount;

            Initialize(threadCount);



            int threadCounter = 0;

            while (threadCounter < threadCount)
            {
                Thread t = new Thread(
                    new ThreadStart(() => {
                    ThreadWork(coll);
                })
                    );

                threads.Add(t);

                //start the ThreadWorkerMethod from this thread
                t.Start();

                threadCounter++;
            }

            //create listen thread
            Thread listenerThread = new Thread(
                new ThreadStart(() =>
            {
                tcpListener = new TcpListener(IPAddress.Any, port);
                tcpListener.Start();     // start listening

                while (true)
                {
                    try
                    {
                        TcpClient client = tcpListener.AcceptTcpClient();     //******NOTE: must dispose yourself.

                        //create a thread to deal with new TCP socket.
                        coll.Add(() =>
                        {
                            WebRequest request = BuildRequest(client);

                            if (request != null)
                            {
                                if (test)
                                {
                                    Console.WriteLine();
                                    Console.WriteLine("METHOD = {0}", request.Method);
                                    Console.WriteLine("REQUEST-TARGET = {0}", request.RequestTarget);
                                    Console.WriteLine("HTTP-VERSION = {0}", request.HTTPVersion);

                                    foreach (Tuple <string, string> t in request.Headers.Values)
                                    {
                                        Console.WriteLine("{0}: {1}", t.Item1, t.Item2);
                                    }
                                    Console.WriteLine();

                                    byte[] buffer   = new byte[1024];
                                    int bytesRead   = 0;
                                    string dataRead = "";

                                    while ((bytesRead = request.Body.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        dataRead += System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
                                    }

                                    Console.WriteLine("dataRead.Length = {0}", dataRead.Length);
                                    Console.WriteLine("dataRead = {0}", dataRead);
                                }

                                //should it be non-null then an appropriate handler is found in the list
                                //of handlers/services that the web stores

                                bool flag = false;

                                for (int i = 0; i < services.Count; i++)
                                {
                                    string SURI = services[i].ServiceURI;


                                    //if serviceURI is a prefix of request-target
                                    if (SURI == request.RequestTarget.Substring(0, SURI.Length))
                                    {
                                        services[i].Handler(request);
                                        flag = true;
                                        break;
                                    }
                                }

                                if (!flag)
                                {
                                    request.WriteNotFoundResponse(errorHtml);
                                }
                            }         //else if request was null, then invalid request from client.

                            //thread will go back to idle if it is null

                            //close client before we leave.
                            client.Close();
                        });
                    }
                    catch (SocketException)
                    {
                        /*if (e.SocketErrorCode == SocketError.Interrupted){
                         *  break;
                         * } */

                        break;
                    }
                }
            })
                );

            listenerThread.Start();

            return(true);
        }
Ejemplo n.º 25
0
        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");
                }
            }
        }
Ejemplo n.º 26
0
        public static bool Start(int port, int threadCount)
        {
            //you need at least one to listen and additional for TCP sockets.
            threadCount = (threadCount <= 0) ? threadCount = 64 : threadCount;

            Initialize(threadCount);

            int threadCounter = 0;

            while (threadCounter < threadCount)
            {
                Thread t = new Thread(
                    new ThreadStart(() => {
                    ThreadWork(coll);
                })
                    );

                threads.Add(t);

                //start the ThreadWorkerMethod from this thread
                t.Start();

                threadCounter++;
            }

            //create listen thread
            Thread listenerThread = new Thread(
                new ThreadStart(() =>
            {
                tcpListener = new TcpListener(IPAddress.Any, port);
                tcpListener.Start();     // start listening

                while (true)
                {
                    try
                    {
                        TcpClient client = tcpListener.AcceptTcpClient();     //******NOTE: must dispose yourself.

                        //create a thread to deal with new TCP socket.
                        coll.Add(() =>
                        {
                            WebRequest request = BuildRequest(client);

                            if (request != null)
                            {
                                //should it be non-null then an appropriate handler is found in the list
                                //of handlers/services that the web stores

                                bool flag = false;

                                for (int i = 0; i < services.Count; i++)
                                {
                                    string SURI = services[i].ServiceURI;

                                    //if serviceURI is a prefix of request-target
                                    if (request.RequestTarget.Length >= SURI.Length &&
                                        SURI == request.RequestTarget.Substring(0, SURI.Length))
                                    {
                                        services[i].Handler(request);
                                        flag = true;
                                        break;
                                    }
                                }

                                if (!flag)
                                {
                                    request.WriteNotFoundResponse(errorHtml);
                                }
                            }         //else if request was null, then invalid request from client.

                            //thread will go back to idle if it is null

                            //close client before we leave.
                            client.Close();
                        });
                    }
                    catch (SocketException)
                    {
                        /*if (e.SocketErrorCode == SocketError.Interrupted){
                         *  break;
                         * } */

                        break;
                    }
                }
            }
                                ));

            listenerThread.Start();

            return(true);
        }
Ejemplo n.º 27
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;
                }
            }
        }