diff --git a/Procfile b/Procfile new file mode 100644 index 0000000..e69de29 diff --git a/http_server.py b/http_server.py index 58d7386..a1e5f44 100644 --- a/http_server.py +++ b/http_server.py @@ -1,6 +1,8 @@ import socket import sys import traceback +import mimetypes +import os def response_ok(body=b"This is a minimal response", mimetype=b"text/plain"): """ @@ -19,21 +21,29 @@ def response_ok(body=b"This is a minimal response", mimetype=b"text/plain"): ''' """ - # TODO: Implement response_ok - return b"" + return b"\r\n".join([b"HTTP/1.1 200 OK", + b"Content-Type: " + mimetype, + b"", + body,]) def response_method_not_allowed(): """Returns a 405 Method Not Allowed response""" - # TODO: Implement response_method_not_allowed - return b"" + return b"\r\n".join([b"HTTP/1.1 405 Method Not Allowed", + b"", + b"GET requests only please!"]) def response_not_found(): """Returns a 404 Not Found response""" - # TODO: Implement response_not_found - return b"" + return b"HTTP/1.1 404 Not Found" + + +def response_unknown_error(err_text="unknown"): + return b"\r\n".join([b"HTTP/1.1 520 Web Server Returned an Unknown Error", + b"", + b"Error: {}".format(err_text)]) def parse_request(request): @@ -44,8 +54,13 @@ def parse_request(request): NotImplementedError if the method of the request is not GET. """ - # TODO: implement parse_request - return "" + method, path, version = request.split("\r\n")[0].split(" ") + + if method != "GET": + raise NotImplementedError + + return path + def response_path(path): """ @@ -75,21 +90,75 @@ def response_path(path): """ - # TODO: Raise a NameError if the requested content is not present + path = os.path.join("./webroot/", path[1:]) + + # Raise a NameError if the requested content is not present # under webroot. + if not os.path.exists(path): + raise NameError - # TODO: Fill in the appropriate content and mime_type give the path. + # Fill in the appropriate content and mime_type give the path. # See the assignment guidelines for help on "mapping mime-types", though # you might need to create a special case for handling make_time.py # # If the path is "make_time.py", then you may OPTIONALLY return the # result of executing `make_time.py`. But you need only return the # CONTENTS of `make_time.py`. - - content = b"not implemented" - mime_type = b"not implemented" - return content, mime_type + mime_type = '' + unencoded_content = None + content = None + + if os.path.isdir(path): + mime_type = 'text/plain' + file_list = os.listdir(path) + unencoded_content = "\r\n".join(file_list) + else: # it's a file + mime_type = mimetypes.guess_type(path)[0] + + if mime_type.startswith('text'): + with open(path, "rb") as f: + content = f.read() + else: # not a text file + with open(path, "rb") as f: + content = f.read() + + if unencoded_content: + content = unencoded_content.encode() + + return content, mime_type.encode() + + +def process_request(conn, addr): + request = '' + while True: + data = conn.recv(1024) + request += data.decode() + + if '\r\n\r\n' in request: + break + + print("Request received:\n{}\n\n".format(request)) + + return request + + +def generate_response(request): + try: + path = parse_request(request) + print("parse_request returned: {}".format(path)) + + content, mimetype = response_path(path) + + response = response_ok(content, mimetype) + except NotImplementedError: + response = response_method_not_allowed() + except NameError: + response = response_not_found() + except Exception as e: + response = response_unknown_error(e) + finally: + return response def server(log_buffer=sys.stderr): @@ -98,56 +167,43 @@ def server(log_buffer=sys.stderr): sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) print("making a server on {0}:{1}".format(*address), file=log_buffer) sock.bind(address) + # sock.settimeout(3.0) sock.listen(1) try: + response = "Failed to generate response." while True: print('waiting for a connection', file=log_buffer) conn, addr = sock.accept() # blocking + print('connection - {0}:{1}'.format(*addr), file=log_buffer) + # conn.settimeout(3.0) try: - print('connection - {0}:{1}'.format(*addr), file=log_buffer) - - request = '' - while True: - data = conn.recv(1024) - request += data.decode('utf8') - - if '\r\n\r\n' in request: - break - - - print("Request received:\n{}\n\n".format(request)) - - # TODO: Use parse_request to retrieve the path from the request. - - # TODO: Use response_path to retrieve the content and the mimetype, - # based on the request path. - - # TODO; If parse_request raised a NotImplementedError, then let - # response be a method_not_allowed response. If response_path raised - # a NameError, then let response be a not_found response. Else, - # use the content and mimetype from response_path to build a - # response_ok. - response = response_ok( - body=b"Welcome to my web server", - mimetype=b"text/plain" - ) - + request = process_request(conn, addr) + response = generate_response(request) conn.sendall(response) + # except socket.timeout: + # print("connection timed out") + # response = response_not_found() + # conn.close() except: + print("in internal exception") traceback.print_exc() + conn.close() finally: + print("response: {}".format(response)) + print("connection closing") conn.close() except KeyboardInterrupt: + print("caught KeyboardInterrupt") sock.close() return except: traceback.print_exc() + sock.close() + return if __name__ == '__main__': server() sys.exit(0) - -