blob: 73bb8169f04bc5789844956c58d83090ca9f94d8 [file] [log] [blame]
Alex Vakulenko039da312015-02-03 08:58:55 -08001// Copyright 2014 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef WEBSERVER_LIBWEBSERV_CONNECTION_H_
6#define WEBSERVER_LIBWEBSERV_CONNECTION_H_
7
8#include <map>
9#include <string>
10#include <vector>
11
12#include <base/macros.h>
13#include <base/memory/ref_counted.h>
14#include <base/memory/scoped_ptr.h>
15#include <chromeos/errors/error.h>
16#include <libwebserv/export.h>
17
18struct MHD_Connection;
19struct MHD_PostProcessor;
20
21namespace base {
22class TaskRunner;
23} // namespace base
24
25namespace libwebserv {
26
27class Request;
28class RequestHandlerInterface;
29class Response;
30class Server;
31
32// A wrapper class around low-level HTTP connection.
33class LIBWEBSERV_EXPORT Connection final : public base::RefCounted<Connection> {
34 public:
35 ~Connection();
36
37 // Factory creator method. Creates an instance of the connection and
38 // initializes some complex data members. This is safer and easier to
39 // report possible failures than reply on just the constructor.
40 static scoped_refptr<Connection> Create(Server* server,
41 const std::string& url,
42 const std::string& method,
43 MHD_Connection* connection,
44 RequestHandlerInterface* handler);
45
46 private:
47 LIBWEBSERV_PRIVATE Connection(
48 const scoped_refptr<base::TaskRunner>& task_runner,
49 MHD_Connection* connection,
50 RequestHandlerInterface* handler);
51
52 // Helper callback methods used by Server's ConnectionHandler to transfer
53 // request headers and data to the Connection's Request object.
54 LIBWEBSERV_PRIVATE bool BeginRequestData();
55 LIBWEBSERV_PRIVATE bool AddRequestData(const void* data, size_t size);
56 LIBWEBSERV_PRIVATE void EndRequestData();
57
58 // Callback for libmicrohttpd's PostProcessor.
59 LIBWEBSERV_PRIVATE bool ProcessPostData(const char* key,
60 const char* filename,
61 const char* content_type,
62 const char* transfer_encoding,
63 const char* data,
64 uint64_t off,
65 size_t size);
66
67 scoped_refptr<base::TaskRunner> task_runner_;
68 MHD_Connection* raw_connection_{nullptr};
69 RequestHandlerInterface* handler_{nullptr};
70 MHD_PostProcessor* post_processor_{nullptr};
71 scoped_ptr<Request> request_;
72 scoped_ptr<Response> response_;
73
74 enum class State { kIdle, kRequestSent, kResponseReceived, kDone };
75 State state_{State::kIdle};
76 int response_status_code_{0};
77 std::vector<uint8_t> response_data_;
78 std::multimap<std::string, std::string> response_headers_;
79
80 friend class ConnectionHelper;
81 friend class Request;
82 friend class Response;
83 friend class ServerHelper;
84 DISALLOW_COPY_AND_ASSIGN(Connection);
85};
86
87} // namespace libwebserv
88
89#endif // WEBSERVER_LIBWEBSERV_CONNECTION_H_