Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / sync / internal_api / http_bridge.cc
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.
4
5 #include "sync/internal_api/public/http_bridge.h"
6
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"
23
24 namespace syncer {
25
26 HttpBridge::RequestContextGetter::RequestContextGetter(
27     net::URLRequestContextGetter* baseline_context_getter,
28     const std::string& user_agent)
29     : baseline_context_getter_(baseline_context_getter),
30       network_task_runner_(
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());
36 }
37
38 HttpBridge::RequestContextGetter::~RequestContextGetter() {}
39
40 net::URLRequestContext*
41 HttpBridge::RequestContextGetter::GetURLRequestContext() {
42   // Lazily create the context.
43   if (!context_) {
44     net::URLRequestContext* baseline_context =
45         baseline_context_getter_->GetURLRequestContext();
46     context_.reset(
47         new RequestContext(baseline_context, GetNetworkTaskRunner(),
48                            user_agent_));
49     baseline_context_getter_ = NULL;
50   }
51
52   return context_.get();
53 }
54
55 scoped_refptr<base::SingleThreadTaskRunner>
56 HttpBridge::RequestContextGetter::GetNetworkTaskRunner() const {
57   return network_task_runner_;
58 }
59
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
69   // point.
70   bool result = cancelation_signal_->TryRegisterHandler(this);
71   DCHECK(result);
72 }
73
74 HttpBridgeFactory::~HttpBridgeFactory() {
75   cancelation_signal_->UnregisterHandler(this);
76 }
77
78 void HttpBridgeFactory::Init(const std::string& user_agent) {
79   base::AutoLock lock(context_getter_lock_);
80
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.
84     return;
85   }
86
87   request_context_getter_ =
88       new HttpBridge::RequestContextGetter(
89           baseline_request_context_getter_, user_agent);
90 }
91
92 HttpPostProviderInterface* HttpBridgeFactory::Create() {
93   base::AutoLock lock(context_getter_lock_);
94
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());
100
101   HttpBridge* http = new HttpBridge(request_context_getter_.get(),
102                                     network_time_update_callback_);
103   http->AddRef();
104   return http;
105 }
106
107 void HttpBridgeFactory::Destroy(HttpPostProviderInterface* http) {
108   static_cast<HttpBridge*>(http)->Release();
109 }
110
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;
119 }
120
121 HttpBridge::RequestContext::RequestContext(
122     net::URLRequestContext* baseline_context,
123     const scoped_refptr<base::SingleThreadTaskRunner>&
124         network_task_runner,
125     const std::string& user_agent)
126     : baseline_context_(baseline_context),
127       network_task_runner_(network_task_runner) {
128   DCHECK(!user_agent.empty());
129
130   // Create empty, in-memory cookie store.
131   set_cookie_store(new net::CookieMonster(NULL, NULL));
132
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());
137
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
141   // context.
142   net::HttpNetworkSession* session =
143       baseline_context->http_transaction_factory()->GetSession();
144   DCHECK(session);
145   set_http_transaction_factory(new net::HttpNetworkLayer(session));
146
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();
158   }
159   http_user_agent_settings_.reset(new net::StaticHttpUserAgentSettings(
160       accepted_language_list,
161       user_agent));
162   set_http_user_agent_settings(http_user_agent_settings_.get());
163
164   set_net_log(baseline_context->net_log());
165 }
166
167 HttpBridge::RequestContext::~RequestContext() {
168   DCHECK(network_task_runner_->BelongsToCurrentThread());
169   delete http_transaction_factory();
170 }
171
172 HttpBridge::URLFetchState::URLFetchState() : url_poster(NULL),
173                                              aborted(false),
174                                              request_completed(false),
175                                              request_succeeded(false),
176                                              http_response_code(-1),
177                                              error_code(-1) {}
178 HttpBridge::URLFetchState::~URLFetchState() {}
179
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) {
189 }
190
191 HttpBridge::~HttpBridge() {
192 }
193
194 void HttpBridge::SetExtraRequestHeaders(const char * headers) {
195   DCHECK(extra_headers_.empty())
196       << "HttpBridge::SetExtraRequestHeaders called twice.";
197   extra_headers_.assign(headers);
198 }
199
200 void HttpBridge::SetURL(const char* url, int port) {
201 #if DCHECK_IS_ON
202   DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
203   {
204     base::AutoLock lock(fetch_state_lock_);
205     DCHECK(!fetch_state_.request_completed);
206   }
207   DCHECK(url_for_request_.is_empty())
208       << "HttpBridge::SetURL called more than once?!";
209 #endif
210   GURL temp(url);
211   GURL::Replacements replacements;
212   std::string port_str = base::IntToString(port);
213   replacements.SetPort(port_str.c_str(), url::Component(0, port_str.length()));
214   url_for_request_ = temp.ReplaceComponents(replacements);
215 }
216
217 void HttpBridge::SetPostPayload(const char* content_type,
218                                 int content_length,
219                                 const char* content) {
220 #if DCHECK_IS_ON
221   DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
222   {
223     base::AutoLock lock(fetch_state_lock_);
224     DCHECK(!fetch_state_.request_completed);
225   }
226   DCHECK(content_type_.empty()) << "Bridge payload already set.";
227   DCHECK_GE(content_length, 0) << "Content length < 0";
228 #endif
229   content_type_ = content_type;
230   if (!content || (content_length == 0)) {
231     DCHECK_EQ(content_length, 0);
232     request_content_ = " ";  // TODO(timsteele): URLFetcher requires non-empty
233                              // content for POSTs whereas CURL does not, for now
234                              // we hack this to support the sync backend.
235   } else {
236     request_content_.assign(content, content_length);
237   }
238 }
239
240 bool HttpBridge::MakeSynchronousPost(int* error_code, int* response_code) {
241 #if DCHECK_IS_ON
242   DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
243   {
244     base::AutoLock lock(fetch_state_lock_);
245     DCHECK(!fetch_state_.request_completed);
246   }
247   DCHECK(url_for_request_.is_valid()) << "Invalid URL for request";
248   DCHECK(!content_type_.empty()) << "Payload not set";
249 #endif
250
251   if (!network_task_runner_->PostTask(
252           FROM_HERE,
253           base::Bind(&HttpBridge::CallMakeAsynchronousPost, this))) {
254     // This usually happens when we're in a unit test.
255     LOG(WARNING) << "Could not post CallMakeAsynchronousPost task";
256     return false;
257   }
258
259   // Block until network request completes or is aborted. See
260   // OnURLFetchComplete and Abort.
261   http_post_completed_.Wait();
262
263   base::AutoLock lock(fetch_state_lock_);
264   DCHECK(fetch_state_.request_completed || fetch_state_.aborted);
265   *error_code = fetch_state_.error_code;
266   *response_code = fetch_state_.http_response_code;
267   return fetch_state_.request_succeeded;
268 }
269
270 void HttpBridge::MakeAsynchronousPost() {
271   DCHECK(network_task_runner_->BelongsToCurrentThread());
272   base::AutoLock lock(fetch_state_lock_);
273   DCHECK(!fetch_state_.request_completed);
274   if (fetch_state_.aborted)
275     return;
276
277   DCHECK(context_getter_for_request_.get());
278   fetch_state_.url_poster = net::URLFetcher::Create(
279       url_for_request_, net::URLFetcher::POST, this);
280   fetch_state_.url_poster->SetRequestContext(context_getter_for_request_.get());
281   fetch_state_.url_poster->SetUploadData(content_type_, request_content_);
282   fetch_state_.url_poster->SetExtraRequestHeaders(extra_headers_);
283   fetch_state_.url_poster->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES);
284   fetch_state_.start_time = base::Time::Now();
285   fetch_state_.url_poster->Start();
286 }
287
288 int HttpBridge::GetResponseContentLength() const {
289   DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
290   base::AutoLock lock(fetch_state_lock_);
291   DCHECK(fetch_state_.request_completed);
292   return fetch_state_.response_content.size();
293 }
294
295 const char* HttpBridge::GetResponseContent() const {
296   DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
297   base::AutoLock lock(fetch_state_lock_);
298   DCHECK(fetch_state_.request_completed);
299   return fetch_state_.response_content.data();
300 }
301
302 const std::string HttpBridge::GetResponseHeaderValue(
303     const std::string& name) const {
304
305   DCHECK_EQ(base::MessageLoop::current(), created_on_loop_);
306   base::AutoLock lock(fetch_state_lock_);
307   DCHECK(fetch_state_.request_completed);
308
309   std::string value;
310   fetch_state_.response_headers->EnumerateHeader(NULL, name, &value);
311   return value;
312 }
313
314 void HttpBridge::Abort() {
315   base::AutoLock lock(fetch_state_lock_);
316
317   // Release |request_context_getter_| as soon as possible so that it is
318   // destroyed in the right order on its network task runner.
319   context_getter_for_request_ = NULL;
320
321   DCHECK(!fetch_state_.aborted);
322   if (fetch_state_.aborted || fetch_state_.request_completed)
323     return;
324
325   fetch_state_.aborted = true;
326   if (!network_task_runner_->PostTask(
327           FROM_HERE,
328           base::Bind(&HttpBridge::DestroyURLFetcherOnIOThread, this,
329                      fetch_state_.url_poster))) {
330     // Madness ensues.
331     NOTREACHED() << "Could not post task to delete URLFetcher";
332   }
333
334   fetch_state_.url_poster = NULL;
335   fetch_state_.error_code = net::ERR_ABORTED;
336   http_post_completed_.Signal();
337 }
338
339 void HttpBridge::DestroyURLFetcherOnIOThread(net::URLFetcher* fetcher) {
340   DCHECK(network_task_runner_->BelongsToCurrentThread());
341   delete fetcher;
342 }
343
344 void HttpBridge::OnURLFetchComplete(const net::URLFetcher* source) {
345   DCHECK(network_task_runner_->BelongsToCurrentThread());
346   base::AutoLock lock(fetch_state_lock_);
347   if (fetch_state_.aborted)
348     return;
349
350   fetch_state_.end_time = base::Time::Now();
351   fetch_state_.request_completed = true;
352   fetch_state_.request_succeeded =
353       (net::URLRequestStatus::SUCCESS == source->GetStatus().status());
354   fetch_state_.http_response_code = source->GetResponseCode();
355   fetch_state_.error_code = source->GetStatus().error();
356
357   // Use a real (non-debug) log to facilitate troubleshooting in the wild.
358   VLOG(2) << "HttpBridge::OnURLFetchComplete for: "
359           << fetch_state_.url_poster->GetURL().spec();
360   VLOG(1) << "HttpBridge received response code: "
361           << fetch_state_.http_response_code;
362
363   source->GetResponseAsString(&fetch_state_.response_content);
364   fetch_state_.response_headers = source->GetResponseHeaders();
365   UpdateNetworkTime();
366
367   // End of the line for url_poster_. It lives only on the IO loop.
368   // We defer deletion because we're inside a callback from a component of the
369   // URLFetcher, so it seems most natural / "polite" to let the stack unwind.
370   base::MessageLoop::current()->DeleteSoon(FROM_HERE, fetch_state_.url_poster);
371   fetch_state_.url_poster = NULL;
372
373   // Wake the blocked syncer thread in MakeSynchronousPost.
374   // WARNING: DONT DO ANYTHING AFTER THIS CALL! |this| may be deleted!
375   http_post_completed_.Signal();
376 }
377
378 net::URLRequestContextGetter* HttpBridge::GetRequestContextGetterForTest()
379     const {
380   base::AutoLock lock(fetch_state_lock_);
381   return context_getter_for_request_.get();
382 }
383
384 void HttpBridge::UpdateNetworkTime() {
385   std::string sane_time_str;
386   if (!fetch_state_.request_succeeded || fetch_state_.start_time.is_null() ||
387       fetch_state_.end_time < fetch_state_.start_time ||
388       !fetch_state_.response_headers->EnumerateHeader(NULL, "Sane-Time-Millis",
389                                                       &sane_time_str)) {
390     return;
391   }
392
393   int64 sane_time_ms = 0;
394   if (base::StringToInt64(sane_time_str, &sane_time_ms)) {
395     network_time_update_callback_.Run(
396         base::Time::FromJsTime(sane_time_ms),
397         base::TimeDelta::FromMilliseconds(1),
398         fetch_state_.end_time - fetch_state_.start_time);
399   }
400 }
401
402 }  // namespace syncer