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 std::string accepted_language_list
;
155 if (baseline_context
->http_user_agent_settings()) {
156 accepted_language_list
=
157 baseline_context
->http_user_agent_settings()->GetAcceptLanguage();
159 http_user_agent_settings_
.reset(new net::StaticHttpUserAgentSettings(
160 accepted_language_list
,
162 set_http_user_agent_settings(http_user_agent_settings_
.get());
164 set_net_log(baseline_context
->net_log());
167 HttpBridge::RequestContext::~RequestContext() {
168 DCHECK(network_task_runner_
->BelongsToCurrentThread());
169 delete http_transaction_factory();
172 HttpBridge::URLFetchState::URLFetchState() : url_poster(NULL
),
174 request_completed(false),
175 request_succeeded(false),
176 http_response_code(-1),
178 HttpBridge::URLFetchState::~URLFetchState() {}
180 HttpBridge::HttpBridge(
181 HttpBridge::RequestContextGetter
* context_getter
,
182 const NetworkTimeUpdateCallback
& network_time_update_callback
)
183 : created_on_loop_(base::MessageLoop::current()),
184 http_post_completed_(false, false),
185 context_getter_for_request_(context_getter
),
186 network_task_runner_(
187 context_getter_for_request_
->GetNetworkTaskRunner()),
188 network_time_update_callback_(network_time_update_callback
) {
191 HttpBridge::~HttpBridge() {
194 void HttpBridge::SetExtraRequestHeaders(const char * headers
) {
195 DCHECK(extra_headers_
.empty())
196 << "HttpBridge::SetExtraRequestHeaders called twice.";
197 extra_headers_
.assign(headers
);
200 void HttpBridge::SetURL(const char* url
, int port
) {
202 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
204 base::AutoLock
lock(fetch_state_lock_
);
205 DCHECK(!fetch_state_
.request_completed
);
207 DCHECK(url_for_request_
.is_empty())
208 << "HttpBridge::SetURL called more than once?!";
211 GURL::Replacements replacements
;
212 std::string port_str
= base::IntToString(port
);
213 replacements
.SetPort(port_str
.c_str(),
214 url_parse::Component(0, port_str
.length()));
215 url_for_request_
= temp
.ReplaceComponents(replacements
);
218 void HttpBridge::SetPostPayload(const char* content_type
,
220 const char* content
) {
222 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
224 base::AutoLock
lock(fetch_state_lock_
);
225 DCHECK(!fetch_state_
.request_completed
);
227 DCHECK(content_type_
.empty()) << "Bridge payload already set.";
228 DCHECK_GE(content_length
, 0) << "Content length < 0";
230 content_type_
= content_type
;
231 if (!content
|| (content_length
== 0)) {
232 DCHECK_EQ(content_length
, 0);
233 request_content_
= " "; // TODO(timsteele): URLFetcher requires non-empty
234 // content for POSTs whereas CURL does not, for now
235 // we hack this to support the sync backend.
237 request_content_
.assign(content
, content_length
);
241 bool HttpBridge::MakeSynchronousPost(int* error_code
, int* response_code
) {
243 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
245 base::AutoLock
lock(fetch_state_lock_
);
246 DCHECK(!fetch_state_
.request_completed
);
248 DCHECK(url_for_request_
.is_valid()) << "Invalid URL for request";
249 DCHECK(!content_type_
.empty()) << "Payload not set";
252 if (!network_task_runner_
->PostTask(
254 base::Bind(&HttpBridge::CallMakeAsynchronousPost
, this))) {
255 // This usually happens when we're in a unit test.
256 LOG(WARNING
) << "Could not post CallMakeAsynchronousPost task";
260 // Block until network request completes or is aborted. See
261 // OnURLFetchComplete and Abort.
262 http_post_completed_
.Wait();
264 base::AutoLock
lock(fetch_state_lock_
);
265 DCHECK(fetch_state_
.request_completed
|| fetch_state_
.aborted
);
266 *error_code
= fetch_state_
.error_code
;
267 *response_code
= fetch_state_
.http_response_code
;
268 return fetch_state_
.request_succeeded
;
271 void HttpBridge::MakeAsynchronousPost() {
272 DCHECK(network_task_runner_
->BelongsToCurrentThread());
273 base::AutoLock
lock(fetch_state_lock_
);
274 DCHECK(!fetch_state_
.request_completed
);
275 if (fetch_state_
.aborted
)
278 DCHECK(context_getter_for_request_
.get());
279 fetch_state_
.url_poster
= net::URLFetcher::Create(
280 url_for_request_
, net::URLFetcher::POST
, this);
281 fetch_state_
.url_poster
->SetRequestContext(context_getter_for_request_
.get());
282 fetch_state_
.url_poster
->SetUploadData(content_type_
, request_content_
);
283 fetch_state_
.url_poster
->SetExtraRequestHeaders(extra_headers_
);
284 fetch_state_
.url_poster
->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES
);
285 fetch_state_
.start_time
= base::Time::Now();
286 fetch_state_
.url_poster
->Start();
289 int HttpBridge::GetResponseContentLength() const {
290 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
291 base::AutoLock
lock(fetch_state_lock_
);
292 DCHECK(fetch_state_
.request_completed
);
293 return fetch_state_
.response_content
.size();
296 const char* HttpBridge::GetResponseContent() const {
297 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
298 base::AutoLock
lock(fetch_state_lock_
);
299 DCHECK(fetch_state_
.request_completed
);
300 return fetch_state_
.response_content
.data();
303 const std::string
HttpBridge::GetResponseHeaderValue(
304 const std::string
& name
) const {
306 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
307 base::AutoLock
lock(fetch_state_lock_
);
308 DCHECK(fetch_state_
.request_completed
);
311 fetch_state_
.response_headers
->EnumerateHeader(NULL
, name
, &value
);
315 void HttpBridge::Abort() {
316 base::AutoLock
lock(fetch_state_lock_
);
318 // Release |request_context_getter_| as soon as possible so that it is
319 // destroyed in the right order on its network task runner.
320 context_getter_for_request_
= NULL
;
322 DCHECK(!fetch_state_
.aborted
);
323 if (fetch_state_
.aborted
|| fetch_state_
.request_completed
)
326 fetch_state_
.aborted
= true;
327 if (!network_task_runner_
->PostTask(
329 base::Bind(&HttpBridge::DestroyURLFetcherOnIOThread
, this,
330 fetch_state_
.url_poster
))) {
332 NOTREACHED() << "Could not post task to delete URLFetcher";
335 fetch_state_
.url_poster
= NULL
;
336 fetch_state_
.error_code
= net::ERR_ABORTED
;
337 http_post_completed_
.Signal();
340 void HttpBridge::DestroyURLFetcherOnIOThread(net::URLFetcher
* fetcher
) {
341 DCHECK(network_task_runner_
->BelongsToCurrentThread());
345 void HttpBridge::OnURLFetchComplete(const net::URLFetcher
* source
) {
346 DCHECK(network_task_runner_
->BelongsToCurrentThread());
347 base::AutoLock
lock(fetch_state_lock_
);
348 if (fetch_state_
.aborted
)
351 fetch_state_
.end_time
= base::Time::Now();
352 fetch_state_
.request_completed
= true;
353 fetch_state_
.request_succeeded
=
354 (net::URLRequestStatus::SUCCESS
== source
->GetStatus().status());
355 fetch_state_
.http_response_code
= source
->GetResponseCode();
356 fetch_state_
.error_code
= source
->GetStatus().error();
358 // Use a real (non-debug) log to facilitate troubleshooting in the wild.
359 VLOG(2) << "HttpBridge::OnURLFetchComplete for: "
360 << fetch_state_
.url_poster
->GetURL().spec();
361 VLOG(1) << "HttpBridge received response code: "
362 << fetch_state_
.http_response_code
;
364 source
->GetResponseAsString(&fetch_state_
.response_content
);
365 fetch_state_
.response_headers
= source
->GetResponseHeaders();
368 // End of the line for url_poster_. It lives only on the IO loop.
369 // We defer deletion because we're inside a callback from a component of the
370 // URLFetcher, so it seems most natural / "polite" to let the stack unwind.
371 base::MessageLoop::current()->DeleteSoon(FROM_HERE
, fetch_state_
.url_poster
);
372 fetch_state_
.url_poster
= NULL
;
374 // Wake the blocked syncer thread in MakeSynchronousPost.
375 // WARNING: DONT DO ANYTHING AFTER THIS CALL! |this| may be deleted!
376 http_post_completed_
.Signal();
379 net::URLRequestContextGetter
* HttpBridge::GetRequestContextGetterForTest()
381 base::AutoLock
lock(fetch_state_lock_
);
382 return context_getter_for_request_
.get();
385 void HttpBridge::UpdateNetworkTime() {
386 std::string sane_time_str
;
387 if (!fetch_state_
.request_succeeded
|| fetch_state_
.start_time
.is_null() ||
388 fetch_state_
.end_time
< fetch_state_
.start_time
||
389 !fetch_state_
.response_headers
->EnumerateHeader(NULL
, "Sane-Time-Millis",
394 int64 sane_time_ms
= 0;
395 if (base::StringToInt64(sane_time_str
, &sane_time_ms
)) {
396 network_time_update_callback_
.Run(
397 base::Time::FromJsTime(sane_time_ms
),
398 base::TimeDelta::FromMilliseconds(1),
399 fetch_state_
.end_time
- fetch_state_
.start_time
);
403 } // namespace syncer