Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(484)

Side by Side Diff: mojo/services/network/http_connection_impl.cc

Issue 1128863004: Mojo service implementation for HTTP server - part 2 (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 5 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2015 The Chromium Authors. All rights reserved. 1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "mojo/services/network/http_connection_impl.h" 5 #include "mojo/services/network/http_connection_impl.h"
6 6
7 #include <limits> 7 #include <limits>
8 8
9 #include "base/bind_helpers.h"
10 #include "base/callback.h"
11 #include "base/logging.h"
12 #include "base/stl_util.h"
13 #include "base/strings/string_util.h"
14 #include "mojo/common/handle_watcher.h"
9 #include "mojo/services/network/http_server_impl.h" 15 #include "mojo/services/network/http_server_impl.h"
10 #include "mojo/services/network/net_adapters.h" 16 #include "mojo/services/network/net_adapters.h"
11 #include "net/base/net_errors.h" 17 #include "net/base/net_errors.h"
18 #include "net/http/http_request_headers.h"
19 #include "net/http/http_status_code.h"
12 #include "net/server/http_server.h" 20 #include "net/server/http_server.h"
13 #include "net/server/http_server_request_info.h" 21 #include "net/server/http_server_request_info.h"
22 #include "net/server/http_server_response_info.h"
23 #include "third_party/mojo/src/mojo/public/cpp/bindings/type_converter.h"
24 #include "third_party/mojo/src/mojo/public/cpp/system/data_pipe.h"
14 25
15 namespace mojo { 26 namespace mojo {
16 27
28 // SimpleDataPipeReader reads till end-of-file, stores the data in a string and
29 // notifies completion.
30 class HttpConnectionImpl::SimpleDataPipeReader {
31 public:
32 using CompletionCallback =
33 base::Callback<void(SimpleDataPipeReader*, scoped_ptr<std::string>)>;
34
35 SimpleDataPipeReader() {}
36 ~SimpleDataPipeReader() {}
37
38 void Start(ScopedDataPipeConsumerHandle consumer,
39 const CompletionCallback& completion_callback) {
40 DCHECK(consumer.is_valid() && !consumer_.is_valid());
41 consumer_ = consumer.Pass();
42 completion_callback_ = completion_callback;
43 buffer_.reset(new std::string);
44 ReadMore();
45 }
46
47 private:
48 void ReadMore() {
49 const void* buf;
50 uint32_t buf_size;
51 MojoResult rv = BeginReadDataRaw(consumer_.get(), &buf, &buf_size,
52 MOJO_READ_DATA_FLAG_NONE);
53 if (rv == MOJO_RESULT_OK) {
54 buffer_->append(static_cast<const char*>(buf), buf_size);
55 EndReadDataRaw(consumer_.get(), buf_size);
56 WaitToReadMore();
57 } else if (rv == MOJO_RESULT_SHOULD_WAIT) {
58 WaitToReadMore();
59 } else if (rv == MOJO_RESULT_FAILED_PRECONDITION) {
60 // We reached end-of-file.
61 completion_callback_.Run(this, buffer_.Pass());
62 // Note: This object may have been destroyed in the callback.
63 } else {
64 CHECK(false);
65 }
66 }
67
68 void WaitToReadMore() {
69 watcher_.Start(consumer_.get(), MOJO_HANDLE_SIGNAL_READABLE,
70 MOJO_DEADLINE_INDEFINITE,
71 base::Bind(&SimpleDataPipeReader::OnHandleReady,
72 base::Unretained(this)));
73 }
74
75 void OnHandleReady(MojoResult result) { ReadMore(); }
76
77 ScopedDataPipeConsumerHandle consumer_;
78 common::HandleWatcher watcher_;
79 CompletionCallback completion_callback_;
80 scoped_ptr<std::string> buffer_;
81
82 DISALLOW_COPY_AND_ASSIGN(SimpleDataPipeReader);
83 };
84
85 template <>
86 struct TypeConverter<URLRequestPtr, net::HttpServerRequestInfo> {
87 static URLRequestPtr Convert(const net::HttpServerRequestInfo& obj) {
88 URLRequestPtr request(URLRequest::New());
89 request->url = obj.path;
90 request->method = obj.method;
91 request->headers.resize(obj.headers.size());
92 size_t index = 0;
93 for (const auto& item : obj.headers) {
94 HTTPHeaderPtr header(HTTPHeader::New());
95 header->name = item.first;
96 header->value = item.second;
97 request->headers[index++] = header.Pass();
98 }
99 if (!obj.data.empty()) {
100 uint32_t num_bytes = static_cast<uint32_t>(obj.data.size());
101 MojoCreateDataPipeOptions options;
102 options.struct_size = sizeof(MojoCreateDataPipeOptions);
103 options.flags = MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE;
104 options.element_num_bytes = 1;
105 options.capacity_num_bytes = num_bytes;
106 DataPipe data_pipe(options);
107 request->body.push_back(data_pipe.consumer_handle.Pass());
108 MojoResult result =
109 WriteDataRaw(data_pipe.producer_handle.get(), obj.data.data(),
110 &num_bytes, MOJO_WRITE_DATA_FLAG_ALL_OR_NONE);
111 CHECK_EQ(MOJO_RESULT_OK, result);
112 }
113 return request.Pass();
114 }
115 };
116
17 HttpConnectionImpl::HttpConnectionImpl(int connection_id, 117 HttpConnectionImpl::HttpConnectionImpl(int connection_id,
18 HttpServerImpl* owner, 118 HttpServerImpl* owner,
19 HttpConnectionDelegatePtr delegate, 119 HttpConnectionDelegatePtr delegate,
20 HttpConnectionPtr* connection) 120 HttpConnectionPtr* connection)
21 : connection_id_(connection_id), 121 : connection_id_(connection_id),
22 owner_(owner), 122 owner_(owner),
23 delegate_(delegate.Pass()), 123 delegate_(delegate.Pass()),
24 binding_(this, connection) { 124 binding_(this, connection) {
125 DCHECK(delegate_);
25 binding_.set_error_handler(this); 126 binding_.set_error_handler(this);
26 delegate_.set_error_handler(this); 127 delegate_.set_error_handler(this);
27 } 128 }
28 129
29 HttpConnectionImpl::~HttpConnectionImpl() {} 130 HttpConnectionImpl::~HttpConnectionImpl() {
131 STLDeleteElements(&response_body_readers_);
132 }
30 133
31 void HttpConnectionImpl::OnReceivedHttpRequest( 134 void HttpConnectionImpl::OnReceivedHttpRequest(
32 const net::HttpServerRequestInfo& info) { 135 const net::HttpServerRequestInfo& info) {
33 // TODO(yzshen): implement it. 136 if (EncounteredConnectionError())
137 return;
138
139 delegate_->OnReceivedRequest(
140 URLRequest::From(info), [this](URLResponsePtr response) {
141 if (response->body.is_valid()) {
142 SimpleDataPipeReader* reader = new SimpleDataPipeReader;
143 response_body_readers_.insert(reader);
144 reader->Start(
145 response->body.Pass(),
146 base::Bind(&HttpConnectionImpl::OnFinishedReadingResponseBody,
147 base::Unretained(this), base::Passed(&response)));
148 } else {
149 OnFinishedReadingResponseBody(response.Pass(), nullptr, nullptr);
150 }
151 });
34 } 152 }
35 153
36 void HttpConnectionImpl::OnReceivedWebSocketRequest( 154 void HttpConnectionImpl::OnReceivedWebSocketRequest(
37 const net::HttpServerRequestInfo& info) { 155 const net::HttpServerRequestInfo& info) {
38 // TODO(yzshen): implement it. 156 // TODO(yzshen): implement it.
39 } 157 }
40 158
41 void HttpConnectionImpl::OnReceivedWebSocketMessage(const std::string& data) { 159 void HttpConnectionImpl::OnReceivedWebSocketMessage(const std::string& data) {
42 // TODO(yzshen): implement it. 160 // TODO(yzshen): implement it.
43 } 161 }
(...skipping 14 matching lines...) Expand all
58 const SetReceiveBufferSizeCallback& callback) { 176 const SetReceiveBufferSizeCallback& callback) {
59 if (size > static_cast<uint32_t>(std::numeric_limits<int32_t>::max())) 177 if (size > static_cast<uint32_t>(std::numeric_limits<int32_t>::max()))
60 size = std::numeric_limits<int32_t>::max(); 178 size = std::numeric_limits<int32_t>::max();
61 179
62 owner_->server()->SetReceiveBufferSize( 180 owner_->server()->SetReceiveBufferSize(
63 connection_id_, static_cast<int32_t>(size)); 181 connection_id_, static_cast<int32_t>(size));
64 callback.Run(MakeNetworkError(net::OK)); 182 callback.Run(MakeNetworkError(net::OK));
65 } 183 }
66 184
67 void HttpConnectionImpl::OnConnectionError() { 185 void HttpConnectionImpl::OnConnectionError() {
68 // The proxy side of |binding_| or the impl side of |delegate_| has closed the 186 // This method is called when the proxy side of |binding_| or the impl side of
69 // pipe. The connection is not needed anymore. 187 // |delegate_| has closed the pipe. Although it is set as error handler for
70 owner_->server()->Close(connection_id_); 188 // both |binding_| and |delegate_|, it will only be called at most once
189 // because when called it closes/resets |binding_| and |delegate_|.
190 DCHECK(!EncounteredConnectionError());
191
192 binding_.Close();
193 delegate_.reset();
194
195 // Don't close the connection until all pending responses are sent.
196 if (response_body_readers_.empty())
197 owner_->server()->Close(connection_id_);
198 }
199
200 void HttpConnectionImpl::OnFinishedReadingResponseBody(
201 URLResponsePtr response,
202 SimpleDataPipeReader* reader,
203 scoped_ptr<std::string> body) {
204 if (reader) {
205 delete reader;
206 response_body_readers_.erase(reader);
207 }
208
209 net::HttpServerResponseInfo info(
210 static_cast<net::HttpStatusCode>(response->status_code));
211
212 std::string content_type;
213 for (size_t i = 0; i < response->headers.size(); ++i) {
214 const HTTPHeader& header = *(response->headers[i]);
215
216 if (body) {
217 // net::HttpServerResponseInfo::SetBody() automatically sets
218 // Content-Length and Content-Types, so skip the two here.
219 //
220 // TODO(yzshen): Consider adding to net::HttpServerResponseInfo a simple
221 // setter for body which doesn't fiddle with headers.
222 if (base::strcasecmp(header.name.data(),
223 net::HttpRequestHeaders::kContentLength) == 0) {
224 continue;
225 } else if (base::strcasecmp(header.name.data(),
226 net::HttpRequestHeaders::kContentType) == 0) {
227 content_type = header.value;
228 continue;
229 }
230 }
231 info.AddHeader(header.name, header.value);
232 }
233
234 if (body)
235 info.SetBody(*body, content_type);
236
237 owner_->server()->SendResponse(connection_id_, info);
238
239 if (response_body_readers_.empty() && EncounteredConnectionError())
240 owner_->server()->Close(connection_id_);
71 } 241 }
72 242
73 } // namespace mojo 243 } // namespace mojo
OLDNEW
« no previous file with comments | « mojo/services/network/http_connection_impl.h ('k') | mojo/services/network/http_server_apptest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698