1 // Copyright 2012 The Chromium 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.
5 #include "sync/internal_api/public/http_bridge.h"
7 #include "base/message_loop/message_loop.h"
8 #include "base/message_loop/message_loop_proxy.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "net/base/load_flags.h"
11 #include "net/base/net_errors.h"
12 #include "net/cookies/cookie_monster.h"
13 #include "net/dns/host_resolver.h"
14 #include "net/http/http_cache.h"
15 #include "net/http/http_network_layer.h"
16 #include "net/http/http_response_headers.h"
17 #include "net/proxy/proxy_service.h"
18 #include "net/url_request/static_http_user_agent_settings.h"
19 #include "net/url_request/url_fetcher.h"
20 #include "net/url_request/url_request_context.h"
21 #include "net/url_request/url_request_status.h"
22 #include "sync/internal_api/public/base/cancelation_signal.h"
26 HttpBridge::RequestContextGetter::RequestContextGetter(
27 net::URLRequestContextGetter* baseline_context_getter,
28 const std::string& user_agent)
29 : baseline_context_getter_(baseline_context_getter),
31 baseline_context_getter_->GetNetworkTaskRunner()),
32 user_agent_(user_agent) {
33 DCHECK(baseline_context_getter_.get());
34 DCHECK(network_task_runner_.get());
35 DCHECK(!user_agent_.empty());
38 HttpBridge::RequestContextGetter::~RequestContextGetter() {}
40 net::URLRequestContext*
41 HttpBridge::RequestContextGetter::GetURLRequestContext() {
42 // Lazily create the context.
44 net::URLRequestContext* baseline_context =
45 baseline_context_getter_->GetURLRequestContext();
47 new RequestContext(baseline_context, GetNetworkTaskRunner(),
49 baseline_context_getter_ = NULL;
52 return context_.get();
55 scoped_refptr<base::SingleThreadTaskRunner>
56 HttpBridge::RequestContextGetter::GetNetworkTaskRunner() const {
57 return network_task_runner_;
60 HttpBridgeFactory::HttpBridgeFactory(
61 net::URLRequestContextGetter* baseline_context_getter,
62 const NetworkTimeUpdateCallback& network_time_update_callback,
63 CancelationSignal* cancelation_signal)
64 : baseline_request_context_getter_(baseline_context_getter),
65 network_time_update_callback_(network_time_update_callback),
66 cancelation_signal_(cancelation_signal) {
67 // Registration should never fail. This should happen on the UI thread during
68 // init. It would be impossible for a shutdown to have been requested at this
70 bool result = cancelation_signal_->TryRegisterHandler(this);
74 HttpBridgeFactory::~HttpBridgeFactory() {
75 cancelation_signal_->UnregisterHandler(this);
78 void HttpBridgeFactory::Init(const std::string& user_agent) {
79 base::AutoLock lock(context_getter_lock_);
81 if (!baseline_request_context_getter_.get()) {
82 // Uh oh. We've been aborted before we finished initializing. There's no
83 // point in initializating further; let's just return right away.
87 request_context_getter_ =
88 new HttpBridge::RequestContextGetter(
89 baseline_request_context_getter_, user_agent);
92 HttpPostProviderInterface* HttpBridgeFactory::Create() {
93 base::AutoLock lock(context_getter_lock_);
95 // If we've been asked to shut down (something which may happen asynchronously
96 // and at pretty much any time), then we won't have a request_context_getter_.
97 // Some external mechanism must ensure that this function is not called after
98 // we've been asked to shut down.
99 CHECK(request_context_getter_.get());
101 HttpBridge* http = new HttpBridge(request_context_getter_.get(),
102 network_time_update_callback_);
107 void HttpBridgeFactory::Destroy(HttpPostProviderInterface* http) {
108 static_cast<HttpBridge*>(http)->Release();
111 void HttpBridgeFactory::OnSignalReceived() {
112 base::AutoLock lock(context_getter_lock_);
113 // Release |baseline_request_context_getter_| as soon as possible so that it
114 // is destroyed in the right order on its network task runner. The
115 // |request_context_getter_| has a reference to the baseline, so we must
116 // drop our reference to it, too.
117 baseline_request_context_getter_ = NULL;
118 request_context_getter_ = NULL;
121 HttpBridge::RequestContext::RequestContext(
122 net::URLRequestContext* baseline_context,
123 const scoped_refptr<base::SingleThreadTaskRunner>&
125 const std::string& user_agent)
126 : baseline_context_(baseline_context),
127 network_task_runner_(network_task_runner) {
128 DCHECK(!user_agent.empty());
130 // Create empty, in-memory cookie store.
131 set_cookie_store(new net::CookieMonster(NULL, NULL));
133 // We don't use a cache for bridged loads, but we do want to share proxy info.
134 set_host_resolver(baseline_context->host_resolver());
135 set_proxy_service(baseline_context->proxy_service());
136 set_ssl_config_service(baseline_context->ssl_config_service());
138 // We want to share the HTTP session data with the network layer factory,
139 // which includes auth_cache for proxies.
140 // Session is not refcounted so we need to be careful to not lose the parent
142 net::HttpNetworkSession* session =
143 baseline_context->http_transaction_factory()->GetSession();
145 set_http_transaction_factory(new net::HttpNetworkLayer(session));
147 // TODO(timsteele): We don't currently listen for pref changes of these
148 // fields or CookiePolicy; I'm not sure we want to strictly follow the
149 // default settings, since for example if the user chooses to block all
150 // cookies, sync will start failing. Also it seems like accept_lang/charset
151 // should be tied to whatever the sync servers expect (if anything). These
152 // fields should probably just be settable by sync backend; though we should
153 // figure out if we need to give the user explicit control over policies etc.
154 http_user_agent_settings_.reset(new net::StaticHttpUserAgentSettings(
155 baseline_context->GetAcceptLanguage(),
157 set_http_user_agent_settings(http_user_agent_settings_.get());
159 set_net_log(baseline_context->net_log());
162 HttpBridge::RequestContext::~RequestContext() {
163 DCHECK(network_task_runner_->BelongsToCurrentThread());
164 delete http_transaction_factory();
167 HttpBridge::URLFetchState::URLFetchState() : url_poster(NULL),
169 request_completed(false),
170 request_succeeded(false),
171 http_response_code(-1),
173 HttpBridge::URLFetchState::~URLFetchState() {}
175 HttpBridge::HttpBridge(
176 HttpBridge::RequestContextGetter* context_getter,
177 const NetworkTimeUpdateCallback& network_time_update_callback)
178 : created_on_loop_(base::MessageLoop::current()),
179 http_post_completed_(false, false),
180 context_getter_for_request_(context_getter),
181 network_task_runner_(
182 context_getter_for_request_->GetNetworkTaskRunner()),
183 network_time_update_callback_(network_time_update_callback) {
186 HttpBridge::~HttpBridge() {
189 void HttpBridge::SetExtraRequestHeaders(const char * headers) {
190 DCHECK(extra_headers_.empty())
191 << "HttpBridge::SetExtraRequestHeaders called twice.";
192 extra_headers_.assign(headers);
195 void HttpBridge::SetURL(const char* url, int port) {
196 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
197 if (DCHECK_IS_ON()) {
198 base::AutoLock lock(fetch_state_lock_);
199 DCHECK(!fetch_state_.request_completed);
201 DCHECK(url_for_request_.is_empty())
202 << "HttpBridge::SetURL called more than once?!";
204 GURL::Replacements replacements;
205 std::string port_str = base::IntToString(port);
206 replacements.SetPort(port_str.c_str(),
207 url_parse::Component(0, port_str.length()));
208 url_for_request_ = temp.ReplaceComponents(replacements);
211 void HttpBridge::SetPostPayload(const char* content_type,
213 const char* content) {
214 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
215 if (DCHECK_IS_ON()) {
216 base::AutoLock lock(fetch_state_lock_);
217 DCHECK(!fetch_state_.request_completed);
219 DCHECK(content_type_.empty()) << "Bridge payload already set.";
220 DCHECK_GE(content_length, 0) << "Content length < 0";
221 content_type_ = content_type;
222 if (!content || (content_length == 0)) {
223 DCHECK_EQ(content_length, 0);
224 request_content_ = " "; // TODO(timsteele): URLFetcher requires non-empty
225 // content for POSTs whereas CURL does not, for now
226 // we hack this to support the sync backend.
228 request_content_.assign(content, content_length);
232 bool HttpBridge::MakeSynchronousPost(int* error_code, int* response_code) {
233 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
234 if (DCHECK_IS_ON()) {
235 base::AutoLock lock(fetch_state_lock_);
236 DCHECK(!fetch_state_.request_completed);
238 DCHECK(url_for_request_.is_valid()) << "Invalid URL for request";
239 DCHECK(!content_type_.empty()) << "Payload not set";
241 if (!network_task_runner_->PostTask(
243 base::Bind(&HttpBridge::CallMakeAsynchronousPost, this))) {
244 // This usually happens when we're in a unit test.
245 LOG(WARNING) << "Could not post CallMakeAsynchronousPost task";
249 // Block until network request completes or is aborted. See
250 // OnURLFetchComplete and Abort.
251 http_post_completed_.Wait();
253 base::AutoLock lock(fetch_state_lock_);
254 DCHECK(fetch_state_.request_completed || fetch_state_.aborted);
255 *error_code = fetch_state_.error_code;
256 *response_code = fetch_state_.http_response_code;
257 return fetch_state_.request_succeeded;
260 void HttpBridge::MakeAsynchronousPost() {
261 DCHECK(network_task_runner_->BelongsToCurrentThread());
262 base::AutoLock lock(fetch_state_lock_);
263 DCHECK(!fetch_state_.request_completed);
264 if (fetch_state_.aborted)
267 DCHECK(context_getter_for_request_.get());
268 fetch_state_.url_poster = net::URLFetcher::Create(
269 url_for_request_, net::URLFetcher::POST, this);
270 fetch_state_.url_poster->SetRequestContext(context_getter_for_request_.get());
271 fetch_state_.url_poster->SetUploadData(content_type_, request_content_);
272 fetch_state_.url_poster->SetExtraRequestHeaders(extra_headers_);
273 fetch_state_.url_poster->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES);
274 fetch_state_.start_time = base::Time::Now();
275 fetch_state_.url_poster->Start();
278 int HttpBridge::GetResponseContentLength() const {
279 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
280 base::AutoLock lock(fetch_state_lock_);
281 DCHECK(fetch_state_.request_completed);
282 return fetch_state_.response_content.size();
285 const char* HttpBridge::GetResponseContent() const {
286 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
287 base::AutoLock lock(fetch_state_lock_);
288 DCHECK(fetch_state_.request_completed);
289 return fetch_state_.response_content.data();
292 const std::string HttpBridge::GetResponseHeaderValue(
293 const std::string& name) const {
295 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
296 base::AutoLock lock(fetch_state_lock_);
297 DCHECK(fetch_state_.request_completed);
300 fetch_state_.response_headers->EnumerateHeader(NULL, name, &value);
304 void HttpBridge::Abort() {
305 base::AutoLock lock(fetch_state_lock_);
307 // Release |request_context_getter_| as soon as possible so that it is
308 // destroyed in the right order on its network task runner.
309 context_getter_for_request_ = NULL;
311 DCHECK(!fetch_state_.aborted);
312 if (fetch_state_.aborted || fetch_state_.request_completed)
315 fetch_state_.aborted = true;
316 if (!network_task_runner_->PostTask(
318 base::Bind(&HttpBridge::DestroyURLFetcherOnIOThread, this,
319 fetch_state_.url_poster))) {
321 NOTREACHED() << "Could not post task to delete URLFetcher";
324 fetch_state_.url_poster = NULL;
325 fetch_state_.error_code = net::ERR_ABORTED;
326 http_post_completed_.Signal();
329 void HttpBridge::DestroyURLFetcherOnIOThread(net::URLFetcher* fetcher) {
330 DCHECK(network_task_runner_->BelongsToCurrentThread());
334 void HttpBridge::OnURLFetchComplete(const net::URLFetcher* source) {
335 DCHECK(network_task_runner_->BelongsToCurrentThread());
336 base::AutoLock lock(fetch_state_lock_);
337 if (fetch_state_.aborted)
340 fetch_state_.end_time = base::Time::Now();
341 fetch_state_.request_completed = true;
342 fetch_state_.request_succeeded =
343 (net::URLRequestStatus::SUCCESS == source->GetStatus().status());
344 fetch_state_.http_response_code = source->GetResponseCode();
345 fetch_state_.error_code = source->GetStatus().error();
347 // Use a real (non-debug) log to facilitate troubleshooting in the wild.
348 VLOG(2) << "HttpBridge::OnURLFetchComplete for: "
349 << fetch_state_.url_poster->GetURL().spec();
350 VLOG(1) << "HttpBridge received response code: "
351 << fetch_state_.http_response_code;
353 source->GetResponseAsString(&fetch_state_.response_content);
354 fetch_state_.response_headers = source->GetResponseHeaders();
357 // End of the line for url_poster_. It lives only on the IO loop.
358 // We defer deletion because we're inside a callback from a component of the
359 // URLFetcher, so it seems most natural / "polite" to let the stack unwind.
360 base::MessageLoop::current()->DeleteSoon(FROM_HERE, fetch_state_.url_poster);
361 fetch_state_.url_poster = NULL;
363 // Wake the blocked syncer thread in MakeSynchronousPost.
364 // WARNING: DONT DO ANYTHING AFTER THIS CALL! |this| may be deleted!
365 http_post_completed_.Signal();
368 net::URLRequestContextGetter* HttpBridge::GetRequestContextGetterForTest()
370 base::AutoLock lock(fetch_state_lock_);
371 return context_getter_for_request_.get();
374 void HttpBridge::UpdateNetworkTime() {
375 std::string sane_time_str;
376 if (!fetch_state_.request_succeeded || fetch_state_.start_time.is_null() ||
377 fetch_state_.end_time < fetch_state_.start_time ||
378 !fetch_state_.response_headers->EnumerateHeader(NULL, "Sane-Time-Millis",
383 int64 sane_time_ms = 0;
384 if (base::StringToInt64(sane_time_str, &sane_time_ms)) {
385 network_time_update_callback_.Run(
386 base::Time::FromJsTime(sane_time_ms),
387 base::TimeDelta::FromMilliseconds(1),
388 fetch_state_.end_time - fetch_state_.start_time);
392 } // namespace syncer