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
) {
201 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
202 if (DCHECK_IS_ON()) {
203 base::AutoLock
lock(fetch_state_lock_
);
204 DCHECK(!fetch_state_
.request_completed
);
206 DCHECK(url_for_request_
.is_empty())
207 << "HttpBridge::SetURL called more than once?!";
209 GURL::Replacements replacements
;
210 std::string port_str
= base::IntToString(port
);
211 replacements
.SetPort(port_str
.c_str(),
212 url_parse::Component(0, port_str
.length()));
213 url_for_request_
= temp
.ReplaceComponents(replacements
);
216 void HttpBridge::SetPostPayload(const char* content_type
,
218 const char* content
) {
219 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
220 if (DCHECK_IS_ON()) {
221 base::AutoLock
lock(fetch_state_lock_
);
222 DCHECK(!fetch_state_
.request_completed
);
224 DCHECK(content_type_
.empty()) << "Bridge payload already set.";
225 DCHECK_GE(content_length
, 0) << "Content length < 0";
226 content_type_
= content_type
;
227 if (!content
|| (content_length
== 0)) {
228 DCHECK_EQ(content_length
, 0);
229 request_content_
= " "; // TODO(timsteele): URLFetcher requires non-empty
230 // content for POSTs whereas CURL does not, for now
231 // we hack this to support the sync backend.
233 request_content_
.assign(content
, content_length
);
237 bool HttpBridge::MakeSynchronousPost(int* error_code
, int* response_code
) {
238 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
239 if (DCHECK_IS_ON()) {
240 base::AutoLock
lock(fetch_state_lock_
);
241 DCHECK(!fetch_state_
.request_completed
);
243 DCHECK(url_for_request_
.is_valid()) << "Invalid URL for request";
244 DCHECK(!content_type_
.empty()) << "Payload not set";
246 if (!network_task_runner_
->PostTask(
248 base::Bind(&HttpBridge::CallMakeAsynchronousPost
, this))) {
249 // This usually happens when we're in a unit test.
250 LOG(WARNING
) << "Could not post CallMakeAsynchronousPost task";
254 // Block until network request completes or is aborted. See
255 // OnURLFetchComplete and Abort.
256 http_post_completed_
.Wait();
258 base::AutoLock
lock(fetch_state_lock_
);
259 DCHECK(fetch_state_
.request_completed
|| fetch_state_
.aborted
);
260 *error_code
= fetch_state_
.error_code
;
261 *response_code
= fetch_state_
.http_response_code
;
262 return fetch_state_
.request_succeeded
;
265 void HttpBridge::MakeAsynchronousPost() {
266 DCHECK(network_task_runner_
->BelongsToCurrentThread());
267 base::AutoLock
lock(fetch_state_lock_
);
268 DCHECK(!fetch_state_
.request_completed
);
269 if (fetch_state_
.aborted
)
272 DCHECK(context_getter_for_request_
.get());
273 fetch_state_
.url_poster
= net::URLFetcher::Create(
274 url_for_request_
, net::URLFetcher::POST
, this);
275 fetch_state_
.url_poster
->SetRequestContext(context_getter_for_request_
.get());
276 fetch_state_
.url_poster
->SetUploadData(content_type_
, request_content_
);
277 fetch_state_
.url_poster
->SetExtraRequestHeaders(extra_headers_
);
278 fetch_state_
.url_poster
->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES
);
279 fetch_state_
.start_time
= base::Time::Now();
280 fetch_state_
.url_poster
->Start();
283 int HttpBridge::GetResponseContentLength() const {
284 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
285 base::AutoLock
lock(fetch_state_lock_
);
286 DCHECK(fetch_state_
.request_completed
);
287 return fetch_state_
.response_content
.size();
290 const char* HttpBridge::GetResponseContent() const {
291 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
292 base::AutoLock
lock(fetch_state_lock_
);
293 DCHECK(fetch_state_
.request_completed
);
294 return fetch_state_
.response_content
.data();
297 const std::string
HttpBridge::GetResponseHeaderValue(
298 const std::string
& name
) const {
300 DCHECK_EQ(base::MessageLoop::current(), created_on_loop_
);
301 base::AutoLock
lock(fetch_state_lock_
);
302 DCHECK(fetch_state_
.request_completed
);
305 fetch_state_
.response_headers
->EnumerateHeader(NULL
, name
, &value
);
309 void HttpBridge::Abort() {
310 base::AutoLock
lock(fetch_state_lock_
);
312 // Release |request_context_getter_| as soon as possible so that it is
313 // destroyed in the right order on its network task runner.
314 context_getter_for_request_
= NULL
;
316 DCHECK(!fetch_state_
.aborted
);
317 if (fetch_state_
.aborted
|| fetch_state_
.request_completed
)
320 fetch_state_
.aborted
= true;
321 if (!network_task_runner_
->PostTask(
323 base::Bind(&HttpBridge::DestroyURLFetcherOnIOThread
, this,
324 fetch_state_
.url_poster
))) {
326 NOTREACHED() << "Could not post task to delete URLFetcher";
329 fetch_state_
.url_poster
= NULL
;
330 fetch_state_
.error_code
= net::ERR_ABORTED
;
331 http_post_completed_
.Signal();
334 void HttpBridge::DestroyURLFetcherOnIOThread(net::URLFetcher
* fetcher
) {
335 DCHECK(network_task_runner_
->BelongsToCurrentThread());
339 void HttpBridge::OnURLFetchComplete(const net::URLFetcher
* source
) {
340 DCHECK(network_task_runner_
->BelongsToCurrentThread());
341 base::AutoLock
lock(fetch_state_lock_
);
342 if (fetch_state_
.aborted
)
345 fetch_state_
.end_time
= base::Time::Now();
346 fetch_state_
.request_completed
= true;
347 fetch_state_
.request_succeeded
=
348 (net::URLRequestStatus::SUCCESS
== source
->GetStatus().status());
349 fetch_state_
.http_response_code
= source
->GetResponseCode();
350 fetch_state_
.error_code
= source
->GetStatus().error();
352 // Use a real (non-debug) log to facilitate troubleshooting in the wild.
353 VLOG(2) << "HttpBridge::OnURLFetchComplete for: "
354 << fetch_state_
.url_poster
->GetURL().spec();
355 VLOG(1) << "HttpBridge received response code: "
356 << fetch_state_
.http_response_code
;
358 source
->GetResponseAsString(&fetch_state_
.response_content
);
359 fetch_state_
.response_headers
= source
->GetResponseHeaders();
362 // End of the line for url_poster_. It lives only on the IO loop.
363 // We defer deletion because we're inside a callback from a component of the
364 // URLFetcher, so it seems most natural / "polite" to let the stack unwind.
365 base::MessageLoop::current()->DeleteSoon(FROM_HERE
, fetch_state_
.url_poster
);
366 fetch_state_
.url_poster
= NULL
;
368 // Wake the blocked syncer thread in MakeSynchronousPost.
369 // WARNING: DONT DO ANYTHING AFTER THIS CALL! |this| may be deleted!
370 http_post_completed_
.Signal();
373 net::URLRequestContextGetter
* HttpBridge::GetRequestContextGetterForTest()
375 base::AutoLock
lock(fetch_state_lock_
);
376 return context_getter_for_request_
.get();
379 void HttpBridge::UpdateNetworkTime() {
380 std::string sane_time_str
;
381 if (!fetch_state_
.request_succeeded
|| fetch_state_
.start_time
.is_null() ||
382 fetch_state_
.end_time
< fetch_state_
.start_time
||
383 !fetch_state_
.response_headers
->EnumerateHeader(NULL
, "Sane-Time-Millis",
388 int64 sane_time_ms
= 0;
389 if (base::StringToInt64(sane_time_str
, &sane_time_ms
)) {
390 network_time_update_callback_
.Run(
391 base::Time::FromJsTime(sane_time_ms
),
392 base::TimeDelta::FromMilliseconds(1),
393 fetch_state_
.end_time
- fetch_state_
.start_time
);
397 } // namespace syncer