Beispiel #1
0
def do_something_put(message_body, headers):
    file_path = os.getcwd() + "/../text_files/" + headers.get('file_name')
    try:
        if os.path.exists(file_path):
            permissions = os.stat(file_path)
            permission = int(oct(permissions.st_mode)[-1:])
            if permission | 2 != permission:
                return build_generic_response(403, "Forbidden")
            my_file = open(file_path, 'w')
            if len(message_body) > 0:
                my_file.write(message_body)
                response = build_generic_response(200, "OK")
            else:
                response = build_generic_response(204, "No Content")
            my_file.close()
        else:
            my_file = open(file_path, 'w+')
            os.chmod(file_path, 0o646)
            my_file.write(message_body)
            response = build_generic_response(201, "Created")
            my_file.close()
    except OSError:
        return get_404_response()

    return response
Beispiel #2
0
def do_something_post(message_body, headers):
    expect_value = ''
    content_type = ''
    try:
        expect_value = headers['Expect']
        content_type = headers['Content-Type']
    except KeyError as e:
        print 'Header does not exist', e
    if expect_value == '100-continue':
        if content_type == 'application/json' and headers[
                'protocol_version'] == '1.1':
            response = build_generic_response(100, "Continue")
        else:
            response = build_generic_response(417, "Expectation Failed")
    else:
        message_len = len(message_body) + 1
        response = ResponseBuilder(200, "OK")
        response = response \
            .with_header({"key": "Date", "value": formatdate(timeval=None, localtime=False, usegmt=True)}) \
            .with_header({"key": "Content-type", "value": "text/html; charset=utf-8"}) \
            .with_header({"key": "Host", "value": "FredsServer"}) \
            .with_header({"key": "Content-length", "value": message_len}) \
            .with_body({"body": message_body}) \
            .build_response()
    return response
def handle_request(message, conn, thread_pool, server_env, broker):
    try:
        headers, query_params = parse_headers(message)
        request_operation = headers['request_operation']
        message_body = get_message_body(message)

        if request_operation == 'GET' or request_operation == 'HEAD':
            head_req = False if request_operation == 'GET' else True
            thread_pool.submit_task(
                task_handle_get, {
                    'connection': conn,
                    'headers': headers,
                    'head_request': head_req,
                    'server_env': server_env,
                    'query_params': query_params,
                    'broker': broker,
                })
        elif request_operation == 'POST':
            message_body = get_message_body(message)
            thread_pool.submit_task(
                task_handle_post_request, {
                    'message_body': message_body,
                    'connection': conn,
                    'headers': headers,
                    'server_env': server_env,
                    'query_params': query_params
                })
        elif request_operation == 'PUT':
            thread_pool.submit_task(
                task_handle_put_request, {
                    'message_body': message_body,
                    'connection': conn,
                    'headers': headers,
                    'server_env': server_env,
                    'query_params': query_params
                })
        elif request_operation == 'DELETE':
            thread_pool.submit_task(
                task_handle_delete_request, {
                    'connection': conn,
                    'headers': headers,
                    'server_env': server_env,
                    'query_params': query_params
                })
    except HttpVersionException as e:
        response = build_generic_response(505, e.message)
        conn.send(response.build())
        conn.close()
    except BadRequestException as e:
        response = build_generic_response(400, e.message)
        conn.send(response)
        conn.close()
Beispiel #4
0
def do_something_delete(headers):
    if 'file_name' in headers:
        file_path = os.getcwd() + "/../text_files/" + headers['file_name']
        permissions = os.stat(file_path)
        permission = int(oct(permissions.st_mode)[-1:])
        if permission | 2 != permission:
            return build_generic_response(403, "Forbidden")
        if os.path.exists(file_path):
            os.remove(file_path)
            response = build_generic_response(200, "OK")
        else:
            response = build_generic_response(404, "Not Found")
    else:
        response = build_generic_response(400, "Bad Request")

    return response
 def submit_task(self, task, kwargs):
     task_obj = TaskObj(task, kwargs)
     # thread = self._thread_queue.pop().value
     try:
         thread = MyThread(target=task_obj.task, kwargs=task_obj.kwargs)
         # thread.set_target(task_obj.task, task_obj.kwargs)
         thread.daemon = True
         thread.start()
     except threading.ThreadError as e:
         conn = kwargs.get('connection', None)
         if conn is not None:
             response = build_generic_response(500, "Internal server error")
             conn.send(response)
             print e
         else:
             print "no connection object - something went seriously wrong"
             raise e
Beispiel #6
0
def do_something_get(connection, headers, head_request):
    try:
        file_path = os.getcwd() + "/../../../chat2/" + headers['file_name']
        permissions = os.stat(file_path)
        permission = int(oct(permissions.st_mode)[-1:])

        if permission | 4 != permission:
            response = build_generic_response(403, "Forbidden")
            connection.send(response)
        else:
            my_file = open(file_path)

            if not head_request:
                body = my_file.read(1024)
            else:
                body = None
            response = ResponseBuilder(200, "OK")
            response = response \
                .with_header({"key": "Date", "value": formatdate(timeval=None, localtime=False, usegmt=True)}) \
                .with_header({"key": "Content-type", "value": "text/html; charset=utf-8"}) \
                .with_header({"key": "Host", "value": "FredServer"}) \
                .with_header({"key": "Content-length", "value": os.path.getsize(file_path)}) \
                .with_body({"body": body}) \
                .build_response()

            connection.send(response)
            while body and not head_request:
                body = my_file.read(1024)
                connection.sendall(body)
            my_file.close()
    except IOError:
        response = get_404_response()
        connection.send(response)
    except OSError:
        response = get_404_response()
        connection.send(response)

    finally:
        connection.close()
                addr_ = socket.gethostbyaddr(addr[0])[0]
            except Exception as e:
                addr_ = "Nothing"
                print "no address", e

            server_env_vars = ServerEnvironmentVariables(
                HTTP_HOST='FredsServer',
                DOCUMENT_ROOT=os.getcwd(),
                REMOTE_ADDR=addr[0],
                REMOTE_HOST=addr_,
                SERVER_PORT=PORT,
                SERVER_PROTOCOL="Http/1.1",
                SERVER_SOFTWARE="0.0.1")

            full_message = recvall_http(conn, 2048)
            print full_message
            try:
                handle_request(full_message, conn, thread_pool,
                               server_env_vars, broker)
            except Exception as e:
                response = build_generic_response(500, "Internal server error")
                conn.send(response)
                conn.close()
                print e
        except KeyboardInterrupt:
            conn.close()
            sock.close()
            raise
        finally:
            pass