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
示例#2
0
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
示例#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()
示例#4
0
def test_response_ok(server_setup):
    test_body = b'body contents'
    response = server.response_ok(test_body, 'text/html', len(test_body))
    assert response == _CRLF.join([
        b'HTTP/1.1 200 OK',
        b'Content-Type: text/html',
        b'Content-Length: 13',
        test_body,
        b''])
def test_response_ok():
    """Test response_ok function."""
    from server import response_ok
    request_tuple = ("text/plain", "This is a very simple text file. Just to show that we can serve it up. It is three lines long.".encode('ascii'))
    SUCCESS_RESPONSE = ("""HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 94\r\n\r\nThis is a very simple text file. Just to show that we can serve it up. It is three lines long.""")
    response = response_ok(request_tuple)
    response = response.decode('utf-8')
    split_response = response.split('\r\n')
    split_success = SUCCESS_RESPONSE.split('\r\n')
    assert split_response[1] == split_success[1]
示例#6
0
def test_client_valid():
    """Test client with valid request."""
    body = '''
        This is a very simple text file.
        Just to show that we can serve it up.
        It is three lines long.
    '''
    from client import client
    from server import response_ok
    req = "GET sample.txt HTTP/1.1\r\nHost: me\r\n\r\n"
    assert client(req)[:15] == response_ok("text/plain", body)[:15]
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
示例#8
0
def test_ok_response_mime_type_is_there(fake_socket):
    """Test that request has a proper mime_type."""
    from server import response_ok
    if sys.version_info.major == 3:
        from http.client import HTTPResponse
    else:
        from httplib import HTTPResponse

    response_str = response_ok(b'htmlhtml', 'text/plain')
    source = fake_socket(response_str)
    response = HTTPResponse(source)
    response.begin()
    assert response.getheader('Content-Type') == 'text/plain'
示例#9
0
def test_ok_response_body_is_there(fake_socket):
    """Test that request has a body."""
    from server import response_ok
    if sys.version_info.major == 3:
        from http.client import HTTPResponse
    else:
        from httplib import HTTPResponse

    response_str = response_ok(b'htmlhtml', 'text/plain')
    source = fake_socket(response_str)
    response = HTTPResponse(source)
    response.begin()
    assert response.read(len(response_str)) == b'htmlhtml'
示例#10
0
def test_response_ok():
    body = 'this is a response'
    ctype = 'text/plain'
    response = response_ok(body, ctype)
    headers, rbody = process_response(response)
    assert rbody == body
    assert headers[0] == 'HTTP/1.1 200 OK'
    typefound = False
    for header in headers:
        if 'Content-Type: text/plain' in header:
            typefound = True
            break
    assert typefound
示例#11
0
def test_response_ok():
    from server import response_ok
    response = response_ok()
    lines = response.split('\n')
    init_line = lines[0].split(' ')
    second_line = lines[1].split(' ')
    assert len(lines) >= 1
    assert '200' in init_line[1]
    assert init_line[0][:4] == 'HTTP'
    assert 'OK' in init_line[2]
    assert 'Content-Type:' in second_line[0]
    assert 'text/plain' in second_line[1]
    assert '\r\n' in response
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] == ""
示例#13
0
def test_resolve_uri_to_response_ok_working_for_html(fake_socket):
    """Test that response_ok returns the file from resolve_uri as the body."""
    from server import response_ok, resolve_uri
    if sys.version_info.major == 3:
        from http.client import HTTPResponse
    else:
        from httplib import HTTPResponse

    response_str = response_ok(*resolve_uri('/a_web_page.html'))
    source = fake_socket(response_str)
    response = HTTPResponse(source)
    response.begin()
    assert response.read(len(response_str)) == b"""<!DOCTYPE html>
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"
示例#15
0
def test_ok_response_well_formatted(fake_socket):
    """Test that formatting of 200 HTTP response is correct."""
    from server import response_ok
    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_ok(b'', 'text/plain'))
    response = HTTPResponse(source)
    response.begin()
    assert response.status == 200
    assert time.strptime(response.getheader('Date'),
                         '%a, %d %b %Y %H:%M:%S %Z')
示例#16
0
def test_ok():
    """Test to get correct server response."""
    from server import response_ok
    msg = response_ok()
    msg = msg.split()
    HTTP = msg[0]
    status_code = msg[1]
    content_type = msg[4]
    charset = msg[5]
    body = (str(msg[15] + msg[16]))

    assert HTTP == 'HTTP/1.1'
    assert status_code == '200'
    assert content_type == 'text/plain;'
    assert charset == 'charset=utf-8'
    assert body == "HelloWorld"
示例#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 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()
示例#19
0
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()
示例#20
0
def test_response_ok_has_response_header():
    """Will test response ok has correct header."""
    from server import response_ok
    assert b"200 OK" in response_ok('bloop', 'text/bloop')
示例#21
0
def test_response_ok():
    assert server.response_ok() == b'HTTP/1.1 200 OK\r\n'
示例#22
0
def test_response_ok(msg, result):
    """Take a msg and receive a well-formatted HTTP 200 response."""
    from server import response_ok
    assert response_ok(msg) == result
示例#23
0
def test_length():
    request = b"GET sample.txt HTTP/1.1\r\nHost:"
    uri = parse_request(request)
    response = response_ok(uri)
    assert "Content-Length: 96" in response
示例#24
0
def test_response_ok():
    """Test good connection message from server returns correct string."""
    from server import response_ok
    assert response_ok() == b'HTTP/1.1 200 OK\n\r\n'
示例#25
0
def test_response_ok():
    """Test that response_ok returns '200 OK' if connection is good."""
    from server import response_ok
    assert response_ok().split(b'\r\n')[0] == b'HTTP/1.1 %s' % OK_200
示例#26
0
def test_response_ok():
    """Test for functionality of response_ok."""
    from server import response_ok
    assert response_ok('contents', 'content_type', 'size').endswith(b'@')
示例#27
0
def test_response_ok():
    response = server.response_ok(b"123456789", "text/plain")
    assert "text/plain" in response
    assert '9' in response
示例#28
0
def test_response_ok():
    """Test for server response_ok function."""
    from server import response_ok
    assert response_ok("body", "type").endswith(b'@FULL_STOP@')
示例#29
0
def test_file_request():
    """Test if a valid request for file gets return properly."""
    txt = 'This is a very simple text file. Just to show that we can serve it up. It is three lines long.'
    returned = client_socket('GET sample.txt HTTP/1.1 Host:')
    ok_message = response_ok((txt, 95, '.txt'))
    assert returned[:50] == ok_message[:50]
示例#30
0
def test_response_message_response():
    """Testing for ok msg function."""
    ok_message = response_ok((1, 2, 3))
    assert ok_message[:15] == 'HTTP/1.1 200 OK'
示例#31
0
def test_response_ok_content_length(ftype, body):
    """Test content-length header."""
    from server import response_ok, parse_headers
    headers = response_ok(ftype, body).split(b'\r\n\r\n')[0]
    assert parse_headers(
        headers.split(b'\r\n')[1:])[b"Content-Length"] == b'11'
示例#32
0
def test_response_ok_end_header():
    """Test to make sure response header has two CLRFs, i.e end of header."""
    from server import response_ok
    end_header = b'\r\n\r\n'
    response = response_ok(b"webroot/a_web_page.html")
    assert end_header in response
示例#33
0
def test_dir_request():
    """Test if a valid request for a dir gets return a proper HTML listing."""
    listing = ['JPEG_example.jpg', 'Sample_Scene_Balls.jpg', 'sample_1.png']
    returned = client_socket('GET images/ HTTP/1.1 Host:')
    ok_message = response_ok((listing, 3, 'HTML LISTING'))
    assert returned == ok_message
示例#34
0
def test_response_ok():
    response = server.response_ok().split(b'\r\n')
    assert b"HTTP/1.1 200 OK" in response[0]
    assert b"Content-Type: text/plain" in response
示例#35
0
def test_ok():
    """Test that the server returns 200 OK."""
    from server import response_ok
    assert response_ok() == 'HTTP/1.1 200 OK\r\n\r\n'
示例#36
0
def test_response_ok():
    foo_uri = b'http://www.host.com'
    response = server.response_ok(foo_uri)
    assert parse_response(response)[0] == '200'
示例#37
0
def test_response_ok(content, content_size, content_type, result):
    """Test for proper request and content reply."""
    body = content, content_size, content_type
    assert response_ok(body) == result
示例#38
0
def test_response_ok_contains_message_body():
    """Test that ok_response also contains valid response body."""
    from server import response_ok
    return_val = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 95\r\n\r\nThis is a very simple text file.\nJust to show that we can serve it up.\nIt is three lines long.\n"
    assert response_ok(b'webroot/sample.txt') == return_val
示例#39
0
def test_response_ok():
    response = response_ok('a_web_page.html')
    assert "HTTP/1.1 200 OK" in response
    assert ("<p>A fine place to spend a week learning web "
            "programming!</p>" in response)
示例#40
0
def test_response_from_server_received():
    """Test that response received from server is valid response."""
    from client import client
    from server import response_ok
    response = client(u"GET ../webroot/sample.txt HTTP/1.1\r\nHost: www.host1.com\r\n\r\n")
    assert response == response_ok(b"webroot/sample.txt").decode("utf8")
示例#41
0
def test_response_ok_number_of_crlf(ftype, body):
    """Test server response contains the right amount of CRLF."""
    from server import response_ok
    assert response_ok(ftype, body).count(b'\r\n') == 6