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 #ifndef SYNC_INTERNAL_API_PUBLIC_HTTP_BRIDGE_H_
6 #define SYNC_INTERNAL_API_PUBLIC_HTTP_BRIDGE_H_
10 #include "base/basictypes.h"
11 #include "base/compiler_specific.h"
12 #include "base/gtest_prod_util.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/synchronization/lock.h"
15 #include "base/synchronization/waitable_event.h"
16 #include "base/timer/timer.h"
17 #include "net/url_request/url_fetcher_delegate.h"
18 #include "net/url_request/url_request_context.h"
19 #include "net/url_request/url_request_context_getter.h"
20 #include "sync/base/sync_export.h"
21 #include "sync/internal_api/public/base/cancelation_observer.h"
22 #include "sync/internal_api/public/http_post_provider_factory.h"
23 #include "sync/internal_api/public/http_post_provider_interface.h"
24 #include "sync/internal_api/public/network_time_update_callback.h"
34 class HttpResponseHeaders
;
35 class HttpUserAgentSettings
;
37 class URLRequestJobFactory
;
42 class CancelationSignal
;
44 // A bridge between the syncer and Chromium HTTP layers.
45 // Provides a way for the sync backend to use Chromium directly for HTTP
46 // requests rather than depending on a third party provider (e.g libcurl).
47 // This is a one-time use bridge. Create one for each request you want to make.
48 // It is RefCountedThreadSafe because it can PostTask to the io loop, and thus
49 // needs to stick around across context switches, etc.
50 class SYNC_EXPORT_PRIVATE HttpBridge
51 : public base::RefCountedThreadSafe
<HttpBridge
>,
52 public HttpPostProviderInterface
,
53 public net::URLFetcherDelegate
{
55 // A request context used for HTTP requests bridged from the sync backend.
56 // A bridged RequestContext has a dedicated in-memory cookie store and does
57 // not use a cache. Thus the same type can be used for incognito mode.
58 class RequestContext
: public net::URLRequestContext
{
60 // |baseline_context| is used to obtain the accept-language
61 // and proxy service information for bridged requests.
62 // Typically |baseline_context| should be the net::URLRequestContext of the
63 // currently active profile.
65 net::URLRequestContext
* baseline_context
,
66 const scoped_refptr
<base::SingleThreadTaskRunner
>&
68 const std::string
& user_agent
);
70 // The destructor MUST be called on the IO thread.
71 ~RequestContext() override
;
74 const scoped_refptr
<base::SingleThreadTaskRunner
> network_task_runner_
;
75 scoped_ptr
<net::HttpUserAgentSettings
> http_user_agent_settings_
;
76 scoped_ptr
<net::URLRequestJobFactory
> job_factory_
;
78 DISALLOW_COPY_AND_ASSIGN(RequestContext
);
81 // Lazy-getter for RequestContext objects.
82 class SYNC_EXPORT_PRIVATE RequestContextGetter
83 : public net::URLRequestContextGetter
{
86 net::URLRequestContextGetter
* baseline_context_getter
,
87 const std::string
& user_agent
);
89 // net::URLRequestContextGetter implementation.
90 net::URLRequestContext
* GetURLRequestContext() override
;
91 scoped_refptr
<base::SingleThreadTaskRunner
> GetNetworkTaskRunner()
95 ~RequestContextGetter() override
;
98 scoped_refptr
<net::URLRequestContextGetter
> baseline_context_getter_
;
99 const scoped_refptr
<base::SingleThreadTaskRunner
> network_task_runner_
;
100 // User agent to apply to the net::URLRequestContext.
101 const std::string user_agent_
;
103 // Lazily initialized by GetURLRequestContext().
104 scoped_ptr
<RequestContext
> context_
;
106 DISALLOW_COPY_AND_ASSIGN(RequestContextGetter
);
109 HttpBridge(RequestContextGetter
* context
,
110 const NetworkTimeUpdateCallback
& network_time_update_callback
);
112 // HttpPostProvider implementation.
113 void SetExtraRequestHeaders(const char* headers
) override
;
114 void SetURL(const char* url
, int port
) override
;
115 void SetPostPayload(const char* content_type
,
117 const char* content
) override
;
118 bool MakeSynchronousPost(int* error_code
, int* response_code
) override
;
119 void Abort() override
;
121 // WARNING: these response content methods are used to extract plain old data
122 // and not null terminated strings, so you should make sure you have read
123 // GetResponseContentLength() characters when using GetResponseContent. e.g
124 // string r(b->GetResponseContent(), b->GetResponseContentLength()).
125 int GetResponseContentLength() const override
;
126 const char* GetResponseContent() const override
;
127 const std::string
GetResponseHeaderValue(
128 const std::string
& name
) const override
;
130 // net::URLFetcherDelegate implementation.
131 void OnURLFetchComplete(const net::URLFetcher
* source
) override
;
132 void OnURLFetchDownloadProgress(const net::URLFetcher
* source
,
133 int64 current
, int64 total
) override
;
134 void OnURLFetchUploadProgress(const net::URLFetcher
* source
,
135 int64 current
, int64 total
) override
;
137 net::URLRequestContextGetter
* GetRequestContextGetterForTest() const;
140 friend class base::RefCountedThreadSafe
<HttpBridge
>;
142 ~HttpBridge() override
;
144 // Protected virtual so the unit test can override to shunt network requests.
145 virtual void MakeAsynchronousPost();
148 friend class SyncHttpBridgeTest
;
149 friend class ::HttpBridgeTest
;
151 // Called on the IO loop to issue the network request. The extra level
152 // of indirection is so that the unit test can override this behavior but we
153 // still have a function to statically pass to PostTask.
154 void CallMakeAsynchronousPost() { MakeAsynchronousPost(); }
156 // Used to destroy a fetcher when the bridge is Abort()ed, to ensure that
157 // a reference to |this| is held while flushing any pending fetch completion
158 // callbacks coming from the IO thread en route to finally destroying the
160 void DestroyURLFetcherOnIOThread(net::URLFetcher
* fetcher
,
161 base::Timer
* fetch_timer
);
163 void UpdateNetworkTime();
165 // Helper method to abort the request if we timed out.
166 void OnURLFetchTimedOut();
168 // The message loop of the thread we were created on. This is the thread that
169 // will block on MakeSynchronousPost while the IO thread fetches data from
171 // This should be the main syncer thread (SyncerThread) which is what blocks
172 // on network IO through curl_easy_perform.
173 base::MessageLoop
* const created_on_loop_
;
175 // The URL to POST to.
176 GURL url_for_request_
;
178 // POST payload information.
179 std::string content_type_
;
180 std::string request_content_
;
181 std::string extra_headers_
;
183 // A waitable event we use to provide blocking semantics to
184 // MakeSynchronousPost. We block created_on_loop_ while the IO loop fetches
186 base::WaitableEvent http_post_completed_
;
188 struct URLFetchState
{
191 // Our hook into the network layer is a URLFetcher. USED ONLY ON THE IO
192 // LOOP, so we can block created_on_loop_ while the fetch is in progress.
193 // NOTE: This is not a scoped_ptr for a reason. It must be deleted on the
194 // same thread that created it, which isn't the same thread |this| gets
195 // deleted on. We must manually delete url_poster_ on the IO loop.
196 net::URLFetcher
* url_poster
;
198 // Start and finish time of request. Set immediately before sending
199 // request and after receiving response.
200 base::Time start_time
;
203 // Used to support 'Abort' functionality.
206 // Cached response data.
207 bool request_completed
;
208 bool request_succeeded
;
209 int http_response_code
;
211 std::string response_content
;
212 scoped_refptr
<net::HttpResponseHeaders
> response_headers
;
214 // Timer to ensure http requests aren't stalled. Reset every time upload or
215 // download progress is made.
216 scoped_ptr
<base::Timer
> http_request_timeout_timer
;
219 // This lock synchronizes use of state involved in the flow to fetch a URL
220 // using URLFetcher, including |fetch_state_| and
221 // |context_getter_for_request_| on any thread, for example, this flow needs
222 // to be synchronized to gracefully clean up URLFetcher and return
223 // appropriate values in |error_code|.
224 mutable base::Lock fetch_state_lock_
;
225 URLFetchState fetch_state_
;
227 // Gets a customized net::URLRequestContext for bridged requests. See
228 // RequestContext definition for details.
229 scoped_refptr
<RequestContextGetter
> context_getter_for_request_
;
231 const scoped_refptr
<base::SingleThreadTaskRunner
> network_task_runner_
;
233 // Callback for updating network time.
234 NetworkTimeUpdateCallback network_time_update_callback_
;
236 DISALLOW_COPY_AND_ASSIGN(HttpBridge
);
239 class SYNC_EXPORT HttpBridgeFactory
: public HttpPostProviderFactory
,
240 public CancelationObserver
{
243 const scoped_refptr
<net::URLRequestContextGetter
>&
244 baseline_context_getter
,
245 const NetworkTimeUpdateCallback
& network_time_update_callback
,
246 CancelationSignal
* cancelation_signal
);
247 ~HttpBridgeFactory() override
;
249 // HttpPostProviderFactory:
250 void Init(const std::string
& user_agent
) override
;
251 HttpPostProviderInterface
* Create() override
;
252 void Destroy(HttpPostProviderInterface
* http
) override
;
254 // CancelationObserver implementation:
255 void OnSignalReceived() override
;
258 // Protects |request_context_getter_| and |baseline_request_context_getter_|.
259 base::Lock context_getter_lock_
;
261 // This request context is the starting point for the request_context_getter_
262 // that we eventually use to make requests. During shutdown we must drop all
263 // references to it before the ProfileSyncService's Shutdown() call is
265 scoped_refptr
<net::URLRequestContextGetter
> baseline_request_context_getter_
;
267 // This request context is built on top of the baseline context and shares
268 // common components. Takes a reference to the
269 // baseline_request_context_getter_. It's mostly used on sync thread when
270 // creating connection but is released as soon as possible during shutdown.
271 // Protected by |context_getter_lock_|.
272 scoped_refptr
<HttpBridge::RequestContextGetter
> request_context_getter_
;
274 NetworkTimeUpdateCallback network_time_update_callback_
;
276 CancelationSignal
* const cancelation_signal_
;
278 DISALLOW_COPY_AND_ASSIGN(HttpBridgeFactory
);
281 } // namespace syncer
283 #endif // SYNC_INTERNAL_API_PUBLIC_HTTP_BRIDGE_H_