def set_server(conn, adr):
    while True:
        try:
            msg = ""
            while True:
                msg_chunk = conn.recv(64)
                msg += msg_chunk
                if len(msg_chunk) < 64:
                    try:
                        resp_uri = server.parse_request(msg)
                    except ValueError:
                        response = server.response_error(400, b"Bad Request")
                    except NotImplementedError:
                        response = server.response_error(505, b"Version Not Supported")
                    except IndexError:
                        response = server.response_error(405, b"Method Not Allowed")
                    except LookupError:
                        response = server.response_error(404, b"Not Found")
                    except Exception:
                        response = server.response_error(500, b"Internal Server Error")
                    else:
                        response = server.response_ok(resp_uri)

                    conn.sendall(response)
                    conn.close()

        except KeyboardInterrupt:
            break
def return_concurrent_request():
    ADDR = ('127.0.0.1', 8000)
    socket = g.socket(
        g.AF_INET, g.SOCK_STREAM, g.IPPROTO_IP
    )

    socket.bind(ADDR)
    socket.listen(5)
    while True:
        try:
            conn, addr = socket.accept()
            request = ""
            while True:
                msg = conn.recv(1024)
                request += msg
                if len(msg) < 1024:
                    break
            try:
                response = server.response_ok(server.parse_request(request))
            except ValueError as detail:
                response = server.response_error(b"400", str(detail))
            except LookupError as detail:
                response = server.response_error(b"404", str(detail))
            except AttributeError as detail:
                response = server.response_error(b"405", str(detail))
            except NotImplementedError as detail:
                response = server.response_error(b"400", str(detail))
            except UserWarning as detail:
                response = server.response_error(b"403", str(detail))
            conn.sendall(response)
            conn.close()
        except KeyboardInterrupt:
            break
Exemple #3
0
def send_response(conn, addr):
    """Send response to client."""
    conn.settimeout(2)
    req = b''
    try:
        packet = conn.recv(8)
        req = packet
        while b'\r\n\r\n' not in req:
            packet = conn.recv(8)
            req += packet
    except socket.timeout:
        pass

    print(req.decode('utf8'))

    try:
        uri = parse_request(req)
        uri = uri if isinstance(uri, str) else uri.decode('utf8')
        res = response_ok(*resolve_uri(uri))

    except ValueError:
        res = response_error(400, 'Bad Request')

    except NotImplementedError as error:
        if 'GET' in error.args[0]:
            res = response_error(405, 'Method Not Allowed')
        else:
            res = response_error(501, 'Not Implmented')

    except (OSError, IOError) as error:
        res = response_error(404, 'Not Found')

    conn.sendall(res)
    conn.close()
def test_response_error():
    response = server.response_error(400, 'Bad Request').split(b'\r\n')
    assert b"HTTP/1.1 400 Bad Request" in response[0]
    assert b"Content-Type: text/plain" in response

    response = server.response_error(405, 'Method Not Allowed').split(b'\r\n')
    assert b"HTTP/1.1 405 Method Not Allowed" in response[0]
    assert b"Content-Type: text/plain" in response

    response = server.response_error(403, 'Forbidden').split(b'\r\n')
    assert b"HTTP/1.1 403 Forbidden" in response[0]
    assert b"Content-Type: text/plain" in response
def test_parse():
    """Assert 404 error works correctly."""
    from server import response_error
    request = u'404 Page Not Found'
    response = response_error(request)
    response = response.split()
    assert response[1] == '404'
def test_response_error():
    """Test response_error function."""
    from server import response_error
    response = response_error("405", "Method not allowed")
    response = response.decode('utf-8')
    slit_response = response[9:12]
    assert "405" == slit_response
def test_response_error_504(server_setup):
    valid = []
    valid.append(b'HTTP/1.1 504 Gateway Timeout')
    valid.append(b'Content-Type: text/html; charset=UTF-8' + _CRLF)
    valid = _CRLF.join(valid)
    response = server.response_error(504, 'Gateway Timeout')
    assert valid == response
def test_response_error_500(server_setup):
    valid = []
    valid.append(b'HTTP/1.1 500 Internal Server Error')
    valid.append(b'Content-Type: text/html; charset=UTF-8' + _CRLF)
    valid = _CRLF.join(valid)

    response = server.response_error(500, 'Internal Server Error')
    assert valid == response
def test_response_error():
    response = server.response_error(
        b"405",
        b"Method Not Allowed",
        b"GET method required."
    )
    assert b"GET method required" in response
    assert b"text/html" in response
    assert b"</body>" in response
Exemple #10
0
def test_response_error():
    from server import response_error
    response = response_error()
    lines = response.split('\n')
    init_line = lines[0].split(' ')
    assert len(lines) >= 1
    assert '500' in init_line[1]
    assert init_line[0][:4] == 'HTTP'
    assert 'Internal' in init_line[2]
    assert 'Server' in init_line[3]
    assert 'Error' in init_line[4]
    assert '\r\n' in response
def test_response_break():
    """Test responses for blank break line between header and body."""
    from server import response_ok
    from server import response_error
    good_resp_msg = response_ok()
    bad_resp_msg = response_error("500", "some text")

    good_split = good_resp_msg.split("\r\n\r\n")
    bad_split = bad_resp_msg.split("\r\n\r\n")

    assert len(good_split) == 2
    assert len(bad_split) == 2
def send_http_response(conn, address):  # pragma: no cover
    """Send a properly formatted HTTP response to the client.

    Request sent by the client should be a properly formatted
    HTTP request.
    """
    conn.settimeout(2)

    request = b''
    try:
        packet = conn.recv(8)
        request = packet
        while b'\r\n\r\n' not in request:
            packet = conn.recv(8)
            request += packet
    except socket.timeout:
        pass

    print(request.decode('utf8'))

    try:
        uri = parse_request(request)
        uri = uri if isinstance(uri, str) else uri.decode('utf8')
        response = response_ok(*resolve_uri(uri))

    except ValueError:
        response = response_error(400, 'Bad Request')

    except NotImplementedError as error:
        if 'GET' in error.args[0]:
            response = response_error(405, 'Method Not Allowed')
        else:
            response = response_error(501, 'Not Implmented')

    except (OSError, IOError) as error:
        response = response_error(404, 'Not Found')

    conn.sendall(response)
    conn.close()
def test_response_headers():
    """Test responses for proper headers."""
    from server import response_ok
    from server import response_error
    good_resp_msg = response_ok()
    bad_resp_msg = response_error("500", "some text")

    good_split = good_resp_msg.split("\r\n")
    bad_split = bad_resp_msg.split("\r\n")

    assert good_split[1][:7:] == "Content"
    assert good_split[1][12] == ":"
    assert bad_split[1] == ""
def test_response_status():
    """Test responses for presence of status code and protocol."""
    from server import response_ok
    from server import response_error
    good_resp_msg = response_ok()
    bad_resp_msg = response_error("500", "some text")

    good_split = good_resp_msg.split(" ")
    bad_split = bad_resp_msg.split(" ")

    assert good_split[1][:1:] == "2"
    assert bad_split[1][:1:] == "5"
    assert good_split[0] == "HTTP/1.1"
    assert bad_split[0] == "HTTP/1.1"
def test_error_response_405_well_formatted(fake_socket):
    """Test that error reponse of 405 HTTP response is correct."""
    from server import response_error
    from datetime import datetime as time

    if sys.version_info.major == 3:
        from http.client import HTTPResponse
    else:
        from httplib import HTTPResponse

    source = fake_socket(response_error(405, 'Method Not Allowed'))
    response = HTTPResponse(source)
    response.begin()
    assert response.status == 405
    assert time.strptime(response.getheader('Date'),
                         '%a, %d %b %Y %H:%M:%S %Z')
Exemple #16
0
def test_error():
    """Test to get an error response."""
    from server import response_error
    msg = response_error()
    msg = msg.split()
    HTTP = msg[0]
    status_code = msg[1]
    content_type = msg[6]
    charset = msg[7]
    body = (str(msg[17] + msg[18]))

    assert HTTP == 'HTTP/1.1'
    assert status_code == '500'
    assert content_type == 'text/plain;'
    assert charset == 'charset=utf-8'
    assert body == "ServerError"
Exemple #17
0
def server_handler(connection, address):
    """Handles the gevent StreamServer for individual clients."""
    try:
        result, mime = parse_request(server_read(connection))
        print("log:", result)
        to_send = response_ok(result, mime)
        server_response(to_send, connection)
    except Exception as error:
        try:
            error = error.args[0]
            code = int(error.split(':')[0])
            error = error.split(':')[1].strip()
        except:
            code = 500
            error = "Server Error"
        server_response(response_error(code, error), connection)
    finally:
        connection.close()
def server(conn, address):
    """Return message to client."""
    try:
        buffer_length = 8
        reply_complete = False
        full_string = u""
        while not reply_complete:
            part = conn.recv(buffer_length)
            full_string = full_string + part.decode('utf-8')
            if len(part) < buffer_length:
                reply_complete = True
        print(full_string)
        try:
            uri = parse_request(full_string)
            body_tuple = resolve_uri(uri)
            if body_tuple:
                conn.send(response_ok(body_tuple))
            else:
                conn.sendall(response_error(u'404 Page Not Found'))
            conn.close()
        except NameError('Method not GET'):
            conn.sendall(response_error(u'405 Method Not Allowed'))
            conn.close()
        except TypeError('HTTP protol incorrect'):
            conn.sendall(response_error(u'505 HTTP Version Not Supported'))
            conn.close()
        except SyntaxError('URI incorrect'):
            conn.sendall(response_error(u'404 Page Not Found'))
            conn.close()
        except IOError('File not found'):
            conn.sendall(response_error(u'404 Page Not Found'))
            conn.close()
    except SystemError('Request not fully received'):
        conn.sendall(response_error())
        conn.close()
    except KeyboardInterrupt:
        conn.close()
    finally:
        conn.close()
def test_response_error_unknown():
    with pytest.raises(KeyError):
        response_error('700')
Exemple #20
0
def test_response_error(msg, result):
    """Pass in an error and receive the appropriate response."""
    from server import response_error
    assert response_error(msg) == result
Exemple #21
0
def test_404_message_response():
    """Testing for if 200 ok is triggered."""
    returned = client_socket('GET /URI HTTP/1.1 Host:')
    error_message = response_error('404')
    assert returned == error_message
def test_response_error(code, result):
    """Test return of error message from response error function."""
    assert response_error(code) == result
Exemple #23
0
def test_response_error():
    response = server.response_error(500, b"Internal Server Error")
    assert parse_response(response)[0] == '500'
def test_response_error_no_support_returns_505_error():
    """Test that no_support error returns 505 Error."""
    from server import response_error
    assert b"HTTP" in response_error("no_support")
Exemple #25
0
def test_response_error(code, result):
    """Test response error for correct error messages for a given code."""
    from server import response_error
    assert response_error(code) == result
def test_error():
    """Test that the server retruns 500 on error."""
    from server import response_error
    assert response_error() == 'HTTP/1.1 500 Internal Server Error\r\n'
Exemple #27
0
def test_405_error_message_response():
    """Testing for if 405 error is triggered."""
    returned = client_socket('POST /URI HTTP/1.1 Host:')
    error_message = response_error('405')
    assert returned == error_message
def test_response_error():
    response = response_error('405')
    headers, body = process_response(response)
    assert headers[0] == 'HTTP/1.1 405 Method Not Allowed'
Exemple #29
0
def test_400_error_message_respoonse():
    """Testing if 500 error is triggered."""
    returned = client_socket('GET /URI HTTP/1.1 HO')
    error_message = response_error('400')
    assert returned == error_message
Exemple #30
0
def test_response_error():
    """Test to see if response error returns a correct error message."""
    from server import response_error
    valid_header = b"HTTP/1.1 500 Internal Server Error\r\n\r\n"
    assert response_error(500, "Internal Server Error") == valid_header
Exemple #31
0
def test_response_error():
    """Check if correct message sent when response ok called."""
    from server import response_error
    assert response_error(
        '405', 'METHOD NOT ALLOWED') == b"""HTTP/1.1 405 METHOD NOT ALLOWED
def test_response_error_malformed_request_returns_400_error():
    """Test that malformed_request error returns 400 Error."""
    from server import response_error
    assert b"server" in response_error("malformed_request")
def test_response_error_bad_request_returns_400_error():
    """Test that bad_request error returns 400 Error."""
    from server import response_error
    assert b"No" in response_error("bad_request")
Exemple #34
0
def test_not_found_error(n, result):
    """Test invalid http request returns response error."""
    from client import client
    from server import response_error
    assert client(n) == response_error(*result)
Exemple #35
0
def test_505_error_message_response():
    """Testing if 505 error is triggered."""
    returned = client_socket('GET /URI HTTP/1.2 Host:')
    error_message = response_error('505')
    assert returned == error_message
def test_server_error():
    """Test server error."""
    from server import response_error
    assert response_error(
        "failure"
    ) == '''HTTP/1.1 500 Internal Server Error\r\nUnknown arguements passed into request.\r\n\r\n'''
def test_response_error(err_msg):
    """Test that response_error returns '500 Internal Server Error'."""
    from server import response_error
    error_text = b'HTTP/1.1 %s' % err_msg
    assert response_error(err_msg).split(b'\r\n')[0] == error_text
Exemple #38
0
def test_response_error():
    """Test that we get an 500 error message."""
    from server import response_error
    resp = response_error("500", 'Internal Server Error')
    assert resp.startswith(b"HTTP/1.1 500")
def test_response_error_forbidden_returns_403_error():
    """Test that forbidden error returns 403 Error."""
    from server import response_error
    assert b"permission" in response_error("forbidden")
Exemple #40
0
def test_response_error_returns_valid_response_header():
    """Test that the error_response returns a correctly formed response."""
    from server import response_error
    assert response_error(404, "Not Found") == b"HTTP/1.1 404 Not Found\r\n\r\n"
def test_response_error():
    """Test first line of server faliure response message."""
    from server import response_error
    output_ = 'HTTP/1.1 500 Internal Server Error'
    http_list = response_error().split('\r\n')
    assert http_list[0] == output_
Exemple #42
0
def test_response_error_end_header():
    """Test to make sure response header has two CLRFs, i.e end of header."""
    from server import response_error
    end_header = b'\r\n\r\n'
    response = response_error(500, "Internal Server Error")
    assert end_header in response
Exemple #43
0
def test_response_error_number_of_crlf(error):
    """Test server response contains the right amount of CRLF."""
    from server import response_error
    assert response_error(error).count(b'\r\n') == 4