- add sources.
[platform/framework/web/crosswalk.git] / src / sync / internal_api / public / http_bridge.h
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 #ifndef SYNC_INTERNAL_API_PUBLIC_HTTP_BRIDGE_H_
6 #define SYNC_INTERNAL_API_PUBLIC_HTTP_BRIDGE_H_
7
8 #include <string>
9
10 #include "base/basictypes.h"
11 #include "base/callback.h"
12 #include "base/compiler_specific.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/synchronization/lock.h"
16 #include "base/synchronization/waitable_event.h"
17 #include "net/base/network_time_notifier.h"
18 #include "net/url_request/url_fetcher_delegate.h"
19 #include "net/url_request/url_request_context.h"
20 #include "net/url_request/url_request_context_getter.h"
21 #include "sync/base/sync_export.h"
22 #include "sync/internal_api/public/base/cancelation_observer.h"
23 #include "sync/internal_api/public/http_post_provider_factory.h"
24 #include "sync/internal_api/public/http_post_provider_interface.h"
25 #include "url/gurl.h"
26
27 class HttpBridgeTest;
28
29 namespace base {
30 class MessageLoop;
31 }
32
33 namespace net {
34 class HttpResponseHeaders;
35 class HttpUserAgentSettings;
36 class URLFetcher;
37 }
38
39 namespace syncer {
40
41 class CancelationSignal;
42
43 // Callback for updating the network time.
44 // Params:
45 // const base::Time& network_time - the new network time.
46 // const base::TimeDelta& resolution - how precise the reading is.
47 // const base::TimeDelta& latency - the http request's latency.
48 typedef base::Callback<void(const base::Time&,
49                             const base::TimeDelta&,
50                             const base::TimeDelta&)> NetworkTimeUpdateCallback;
51
52 // A bridge between the syncer and Chromium HTTP layers.
53 // Provides a way for the sync backend to use Chromium directly for HTTP
54 // requests rather than depending on a third party provider (e.g libcurl).
55 // This is a one-time use bridge. Create one for each request you want to make.
56 // It is RefCountedThreadSafe because it can PostTask to the io loop, and thus
57 // needs to stick around across context switches, etc.
58 class SYNC_EXPORT_PRIVATE HttpBridge
59     : public base::RefCountedThreadSafe<HttpBridge>,
60       public HttpPostProviderInterface,
61       public net::URLFetcherDelegate {
62  public:
63   // A request context used for HTTP requests bridged from the sync backend.
64   // A bridged RequestContext has a dedicated in-memory cookie store and does
65   // not use a cache. Thus the same type can be used for incognito mode.
66   class RequestContext : public net::URLRequestContext {
67    public:
68     // |baseline_context| is used to obtain the accept-language
69     // and proxy service information for bridged requests.
70     // Typically |baseline_context| should be the net::URLRequestContext of the
71     // currently active profile.
72     RequestContext(
73         net::URLRequestContext* baseline_context,
74         const scoped_refptr<base::SingleThreadTaskRunner>&
75             network_task_runner,
76         const std::string& user_agent);
77
78     // The destructor MUST be called on the IO thread.
79     virtual ~RequestContext();
80
81    private:
82     net::URLRequestContext* const baseline_context_;
83     const scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
84     scoped_ptr<net::HttpUserAgentSettings> http_user_agent_settings_;
85
86     DISALLOW_COPY_AND_ASSIGN(RequestContext);
87   };
88
89   // Lazy-getter for RequestContext objects.
90   class SYNC_EXPORT_PRIVATE RequestContextGetter
91       : public net::URLRequestContextGetter {
92    public:
93     RequestContextGetter(
94         net::URLRequestContextGetter* baseline_context_getter,
95         const std::string& user_agent);
96
97     // net::URLRequestContextGetter implementation.
98     virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE;
99     virtual scoped_refptr<base::SingleThreadTaskRunner>
100         GetNetworkTaskRunner() const OVERRIDE;
101
102    protected:
103     virtual ~RequestContextGetter();
104
105    private:
106     scoped_refptr<net::URLRequestContextGetter> baseline_context_getter_;
107     const scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
108     // User agent to apply to the net::URLRequestContext.
109     const std::string user_agent_;
110
111     // Lazily initialized by GetURLRequestContext().
112     scoped_ptr<RequestContext> context_;
113
114     DISALLOW_COPY_AND_ASSIGN(RequestContextGetter);
115   };
116
117   HttpBridge(RequestContextGetter* context,
118              const NetworkTimeUpdateCallback& network_time_update_callback);
119
120   // HttpPostProvider implementation.
121   virtual void SetExtraRequestHeaders(const char* headers) OVERRIDE;
122   virtual void SetURL(const char* url, int port) OVERRIDE;
123   virtual void SetPostPayload(const char* content_type, int content_length,
124                               const char* content) OVERRIDE;
125   virtual bool MakeSynchronousPost(int* error_code,
126                                    int* response_code) OVERRIDE;
127   virtual void Abort() OVERRIDE;
128
129   // WARNING: these response content methods are used to extract plain old data
130   // and not null terminated strings, so you should make sure you have read
131   // GetResponseContentLength() characters when using GetResponseContent. e.g
132   // string r(b->GetResponseContent(), b->GetResponseContentLength()).
133   virtual int GetResponseContentLength() const OVERRIDE;
134   virtual const char* GetResponseContent() const OVERRIDE;
135   virtual const std::string GetResponseHeaderValue(
136       const std::string& name) const OVERRIDE;
137
138   // net::URLFetcherDelegate implementation.
139   virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE;
140
141   net::URLRequestContextGetter* GetRequestContextGetterForTest() const;
142
143  protected:
144   friend class base::RefCountedThreadSafe<HttpBridge>;
145
146   virtual ~HttpBridge();
147
148   // Protected virtual so the unit test can override to shunt network requests.
149   virtual void MakeAsynchronousPost();
150
151  private:
152   friend class SyncHttpBridgeTest;
153   friend class ::HttpBridgeTest;
154
155   // Called on the IO loop to issue the network request. The extra level
156   // of indirection is so that the unit test can override this behavior but we
157   // still have a function to statically pass to PostTask.
158   void CallMakeAsynchronousPost() { MakeAsynchronousPost(); }
159
160   // Used to destroy a fetcher when the bridge is Abort()ed, to ensure that
161   // a reference to |this| is held while flushing any pending fetch completion
162   // callbacks coming from the IO thread en route to finally destroying the
163   // fetcher.
164   void DestroyURLFetcherOnIOThread(net::URLFetcher* fetcher);
165
166   void UpdateNetworkTime();
167
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
170   // the network.
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_;
174
175   // The URL to POST to.
176   GURL url_for_request_;
177
178   // POST payload information.
179   std::string content_type_;
180   std::string request_content_;
181   std::string extra_headers_;
182
183   // A waitable event we use to provide blocking semantics to
184   // MakeSynchronousPost. We block created_on_loop_ while the IO loop fetches
185   // network request.
186   base::WaitableEvent http_post_completed_;
187
188   struct URLFetchState {
189     URLFetchState();
190     ~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;
197
198     // Start and finish time of request. Set immediately before sending
199     // request and after receiving response.
200     base::Time start_time;
201     base::Time end_time;
202
203     // Used to support 'Abort' functionality.
204     bool aborted;
205
206     // Cached response data.
207     bool request_completed;
208     bool request_succeeded;
209     int http_response_code;
210     int error_code;
211     std::string response_content;
212     scoped_refptr<net::HttpResponseHeaders> response_headers;
213   };
214
215   // This lock synchronizes use of state involved in the flow to fetch a URL
216   // using URLFetcher, including |fetch_state_| and
217   // |context_getter_for_request_| on any thread, for example, this flow needs
218   // to be synchronized to gracefully clean up URLFetcher and return
219   // appropriate values in |error_code|.
220   mutable base::Lock fetch_state_lock_;
221   URLFetchState fetch_state_;
222
223   // Gets a customized net::URLRequestContext for bridged requests. See
224   // RequestContext definition for details.
225   scoped_refptr<RequestContextGetter> context_getter_for_request_;
226
227   const scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
228
229   // Callback for updating network time.
230   NetworkTimeUpdateCallback network_time_update_callback_;
231
232   DISALLOW_COPY_AND_ASSIGN(HttpBridge);
233 };
234
235 class SYNC_EXPORT HttpBridgeFactory : public HttpPostProviderFactory,
236                                       public CancelationObserver {
237  public:
238   HttpBridgeFactory(
239       net::URLRequestContextGetter* baseline_context_getter,
240       const NetworkTimeUpdateCallback& network_time_update_callback,
241       CancelationSignal* cancelation_signal);
242   virtual ~HttpBridgeFactory();
243
244   // HttpPostProviderFactory:
245   virtual void Init(const std::string& user_agent) OVERRIDE;
246   virtual HttpPostProviderInterface* Create() OVERRIDE;
247   virtual void Destroy(HttpPostProviderInterface* http) OVERRIDE;
248
249   // CancelationObserver implementation:
250   virtual void OnSignalReceived() OVERRIDE;
251
252  private:
253   // Protects |request_context_getter_| and |baseline_request_context_getter_|.
254   base::Lock context_getter_lock_;
255
256   // This request context is the starting point for the request_context_getter_
257   // that we eventually use to make requests.  During shutdown we must drop all
258   // references to it before the ProfileSyncService's Shutdown() call is
259   // complete.
260   scoped_refptr<net::URLRequestContextGetter> baseline_request_context_getter_;
261
262   // This request context is built on top of the baseline context and shares
263   // common components. Takes a reference to the
264   // baseline_request_context_getter_.  It's mostly used on sync thread when
265   // creating connection but is released as soon as possible during shutdown.
266   // Protected by |context_getter_lock_|.
267   scoped_refptr<HttpBridge::RequestContextGetter> request_context_getter_;
268
269   NetworkTimeUpdateCallback network_time_update_callback_;
270
271   CancelationSignal* const cancelation_signal_;
272
273   DISALLOW_COPY_AND_ASSIGN(HttpBridgeFactory);
274 };
275
276 }  //  namespace syncer
277
278 #endif  // SYNC_INTERNAL_API_PUBLIC_HTTP_BRIDGE_H_