profile_io_data.h revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
1// Copyright (c) 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 CHROME_BROWSER_PROFILES_PROFILE_IO_DATA_H_
6#define CHROME_BROWSER_PROFILES_PROFILE_IO_DATA_H_
7
8#include <string>
9
10#include "base/basictypes.h"
11#include "base/callback_forward.h"
12#include "base/files/file_path.h"
13#include "base/memory/ref_counted.h"
14#include "base/memory/scoped_ptr.h"
15#include "base/memory/weak_ptr.h"
16#include "base/prefs/pref_member.h"
17#include "base/synchronization/lock.h"
18#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
19#include "chrome/browser/io_thread.h"
20#include "chrome/browser/net/chrome_url_request_context.h"
21#include "chrome/browser/profiles/storage_partition_descriptor.h"
22#include "chrome/common/content_settings_types.h"
23#include "content/public/browser/content_browser_client.h"
24#include "content/public/browser/resource_context.h"
25#include "net/cookies/cookie_monster.h"
26#include "net/http/http_network_session.h"
27#include "net/url_request/url_request_job_factory.h"
28
29class ChromeHttpUserAgentSettings;
30class ChromeNetworkDelegate;
31class CookieSettings;
32class HostContentSettingsMap;
33class ManagedModeURLFilter;
34class MediaDeviceIDSalt;
35class Profile;
36class ProtocolHandlerRegistry;
37class SigninNamesOnIOThread;
38
39namespace extensions {
40class InfoMap;
41}
42
43namespace net {
44class CookieStore;
45class FraudulentCertificateReporter;
46class FtpTransactionFactory;
47class HttpServerProperties;
48class HttpTransactionFactory;
49class ServerBoundCertService;
50class ProxyConfigService;
51class ProxyService;
52class SSLConfigService;
53class TransportSecurityPersister;
54class TransportSecurityState;
55class URLRequestJobFactoryImpl;
56}  // namespace net
57
58namespace policy {
59class PolicyCertVerifier;
60class PolicyHeaderIOHelper;
61class URLBlacklistManager;
62}  // namespace policy
63
64// Conceptually speaking, the ProfileIOData represents data that lives on the IO
65// thread that is owned by a Profile, such as, but not limited to, network
66// objects like CookieMonster, HttpTransactionFactory, etc.  Profile owns
67// ProfileIOData, but will make sure to delete it on the IO thread (except
68// possibly in unit tests where there is no IO thread).
69class ProfileIOData {
70 public:
71  virtual ~ProfileIOData();
72
73  static ProfileIOData* FromResourceContext(content::ResourceContext* rc);
74
75  // Returns true if |scheme| is handled in Chrome, or by default handlers in
76  // net::URLRequest.
77  static bool IsHandledProtocol(const std::string& scheme);
78
79  // Returns true if |url| is handled in Chrome, or by default handlers in
80  // net::URLRequest.
81  static bool IsHandledURL(const GURL& url);
82
83  // Utility to install additional WebUI handlers into the |job_factory|.
84  // Ownership of the handlers is transfered from |protocol_handlers|
85  // to the |job_factory|.
86  static void InstallProtocolHandlers(
87      net::URLRequestJobFactoryImpl* job_factory,
88      content::ProtocolHandlerMap* protocol_handlers);
89
90  // Called by Profile.
91  content::ResourceContext* GetResourceContext() const;
92
93  // Initializes the ProfileIOData object and primes the RequestContext
94  // generation. Must be called prior to any of the Get*() methods other than
95  // GetResouceContext or GetMetricsEnabledStateOnIOThread.
96  void Init(content::ProtocolHandlerMap* protocol_handlers) const;
97
98  ChromeURLRequestContext* GetMainRequestContext() const;
99  ChromeURLRequestContext* GetMediaRequestContext() const;
100  ChromeURLRequestContext* GetExtensionsRequestContext() const;
101  ChromeURLRequestContext* GetIsolatedAppRequestContext(
102      ChromeURLRequestContext* main_context,
103      const StoragePartitionDescriptor& partition_descriptor,
104      scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
105          protocol_handler_interceptor,
106      content::ProtocolHandlerMap* protocol_handlers) const;
107  ChromeURLRequestContext* GetIsolatedMediaRequestContext(
108      ChromeURLRequestContext* app_context,
109      const StoragePartitionDescriptor& partition_descriptor) const;
110
111  // These are useful when the Chrome layer is called from the content layer
112  // with a content::ResourceContext, and they want access to Chrome data for
113  // that profile.
114  extensions::InfoMap* GetExtensionInfoMap() const;
115  CookieSettings* GetCookieSettings() const;
116  HostContentSettingsMap* GetHostContentSettingsMap() const;
117
118  IntegerPrefMember* session_startup_pref() const {
119    return &session_startup_pref_;
120  }
121
122  SigninNamesOnIOThread* signin_names() const {
123    return signin_names_.get();
124  }
125
126  StringPrefMember* google_services_account_id() const {
127    return &google_services_user_account_id_;
128  }
129
130  StringPrefMember* google_services_username() const {
131    return &google_services_username_;
132  }
133
134  StringPrefMember* google_services_username_pattern() const {
135    return &google_services_username_pattern_;
136  }
137
138  BooleanPrefMember* reverse_autologin_enabled() const {
139    return &reverse_autologin_enabled_;
140  }
141
142  const std::string& reverse_autologin_pending_email() const {
143    return reverse_autologin_pending_email_;
144  }
145
146  void set_reverse_autologin_pending_email(const std::string& email) {
147    reverse_autologin_pending_email_ = email;
148  }
149
150  StringListPrefMember* one_click_signin_rejected_email_list() const {
151    return &one_click_signin_rejected_email_list_;
152  }
153
154  ChromeURLRequestContext* extensions_request_context() const {
155    return extensions_request_context_.get();
156  }
157
158  BooleanPrefMember* safe_browsing_enabled() const {
159    return &safe_browsing_enabled_;
160  }
161
162  BooleanPrefMember* printing_enabled() const {
163    return &printing_enabled_;
164  }
165
166  BooleanPrefMember* sync_disabled() const {
167    return &sync_disabled_;
168  }
169
170  BooleanPrefMember* signin_allowed() const {
171    return &signin_allowed_;
172  }
173
174  BooleanPrefMember* network_prediction_enabled() const {
175    return &network_prediction_enabled_;
176  }
177
178  content::ResourceContext::SaltCallback GetMediaDeviceIDSalt() const;
179
180  net::TransportSecurityState* transport_security_state() const {
181    return transport_security_state_.get();
182  }
183
184#if defined(OS_CHROMEOS)
185  std::string username_hash() const {
186    return username_hash_;
187  }
188#endif
189
190  bool is_incognito() const {
191    return is_incognito_;
192  }
193
194#if defined(ENABLE_CONFIGURATION_POLICY)
195  policy::PolicyHeaderIOHelper* policy_header_helper() const {
196    return policy_header_helper_.get();
197  }
198#endif
199
200#if defined(ENABLE_MANAGED_USERS)
201  const ManagedModeURLFilter* managed_mode_url_filter() const {
202    return managed_mode_url_filter_.get();
203  }
204#endif
205
206  // Initialize the member needed to track the metrics enabled state. This is
207  // only to be called on the UI thread.
208  void InitializeMetricsEnabledStateOnUIThread();
209
210  // Returns whether or not metrics reporting is enabled in the browser instance
211  // on which this profile resides. This is safe for use from the IO thread, and
212  // should only be called from there.
213  bool GetMetricsEnabledStateOnIOThread() const;
214
215  void set_client_cert_store_factory_for_testing(
216    const base::Callback<scoped_ptr<net::ClientCertStore>()>& factory) {
217      client_cert_store_factory_ = factory;
218  }
219
220 protected:
221  // A URLRequestContext for media that owns its HTTP factory, to ensure
222  // it is deleted.
223  class MediaRequestContext : public ChromeURLRequestContext {
224   public:
225    MediaRequestContext();
226
227    void SetHttpTransactionFactory(
228        scoped_ptr<net::HttpTransactionFactory> http_factory);
229
230   private:
231    virtual ~MediaRequestContext();
232
233    scoped_ptr<net::HttpTransactionFactory> http_factory_;
234  };
235
236  // A URLRequestContext for apps that owns its cookie store and HTTP factory,
237  // to ensure they are deleted.
238  class AppRequestContext : public ChromeURLRequestContext {
239   public:
240    AppRequestContext();
241
242    void SetCookieStore(net::CookieStore* cookie_store);
243    void SetHttpTransactionFactory(
244        scoped_ptr<net::HttpTransactionFactory> http_factory);
245    void SetJobFactory(scoped_ptr<net::URLRequestJobFactory> job_factory);
246
247   private:
248    virtual ~AppRequestContext();
249
250    scoped_refptr<net::CookieStore> cookie_store_;
251    scoped_ptr<net::HttpTransactionFactory> http_factory_;
252    scoped_ptr<net::URLRequestJobFactory> job_factory_;
253  };
254
255  // Created on the UI thread, read on the IO thread during ProfileIOData lazy
256  // initialization.
257  struct ProfileParams {
258    ProfileParams();
259    ~ProfileParams();
260
261    base::FilePath path;
262    IOThread* io_thread;
263    scoped_refptr<CookieSettings> cookie_settings;
264    scoped_refptr<HostContentSettingsMap> host_content_settings_map;
265    scoped_refptr<net::SSLConfigService> ssl_config_service;
266    scoped_refptr<net::CookieMonster::Delegate> cookie_monster_delegate;
267    scoped_refptr<extensions::InfoMap> extension_info_map;
268
269    // This pointer exists only as a means of conveying a url job factory
270    // pointer from the protocol handler registry on the UI thread to the
271    // the URLRequestContext on the IO thread. The consumer MUST take
272    // ownership of the object by calling release() on this pointer.
273    scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
274        protocol_handler_interceptor;
275
276    // We need to initialize the ProxyConfigService from the UI thread
277    // because on linux it relies on initializing things through gconf,
278    // and needs to be on the main thread.
279    scoped_ptr<net::ProxyConfigService> proxy_config_service;
280
281#if defined(ENABLE_MANAGED_USERS)
282    scoped_refptr<const ManagedModeURLFilter> managed_mode_url_filter;
283#endif
284
285#if defined(OS_CHROMEOS)
286    std::string username_hash;
287#endif
288
289    // The profile this struct was populated from. It's passed as a void* to
290    // ensure it's not accidently used on the IO thread. Before using it on the
291    // UI thread, call ProfileManager::IsValidProfile to ensure it's alive.
292    void* profile;
293  };
294
295  explicit ProfileIOData(bool is_incognito);
296
297  static std::string GetSSLSessionCacheShard();
298
299  void InitializeOnUIThread(Profile* profile);
300  void ApplyProfileParamsToContext(ChromeURLRequestContext* context) const;
301
302  scoped_ptr<net::URLRequestJobFactory> SetUpJobFactoryDefaults(
303      scoped_ptr<net::URLRequestJobFactoryImpl> job_factory,
304      scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
305          protocol_handler_interceptor,
306      net::NetworkDelegate* network_delegate,
307      net::FtpTransactionFactory* ftp_transaction_factory) const;
308
309  // Called when the profile is destroyed.
310  void ShutdownOnUIThread();
311
312  // A ServerBoundCertService object is created by a derived class of
313  // ProfileIOData, and the derived class calls this method to set the
314  // server_bound_cert_service_ member and transfers ownership to the base
315  // class.
316  void set_server_bound_cert_service(
317      net::ServerBoundCertService* server_bound_cert_service) const;
318
319  ChromeNetworkDelegate* network_delegate() const {
320    return network_delegate_.get();
321  }
322
323  net::FraudulentCertificateReporter* fraudulent_certificate_reporter() const {
324    return fraudulent_certificate_reporter_.get();
325  }
326
327  net::ProxyService* proxy_service() const {
328    return proxy_service_.get();
329  }
330
331  base::WeakPtr<net::HttpServerProperties> http_server_properties() const;
332
333  void set_http_server_properties(
334      scoped_ptr<net::HttpServerProperties> http_server_properties) const;
335
336  ChromeURLRequestContext* main_request_context() const {
337    return main_request_context_.get();
338  }
339
340  bool initialized() const {
341    return initialized_;
342  }
343
344  // Destroys the ResourceContext first, to cancel any URLRequests that are
345  // using it still, before we destroy the member variables that those
346  // URLRequests may be accessing.
347  void DestroyResourceContext();
348
349  // Fills in fields of params using values from main_request_context_ and the
350  // IOThread associated with profile_params.
351  void PopulateNetworkSessionParams(
352      const ProfileParams* profile_params,
353      net::HttpNetworkSession::Params* params) const;
354
355  void SetCookieSettingsForTesting(CookieSettings* cookie_settings);
356
357  void set_signin_names_for_testing(SigninNamesOnIOThread* signin_names);
358
359 private:
360  class ResourceContext : public content::ResourceContext {
361   public:
362    explicit ResourceContext(ProfileIOData* io_data);
363    virtual ~ResourceContext();
364
365    // ResourceContext implementation:
366    virtual net::HostResolver* GetHostResolver() OVERRIDE;
367    virtual net::URLRequestContext* GetRequestContext() OVERRIDE;
368    virtual scoped_ptr<net::ClientCertStore> CreateClientCertStore() OVERRIDE;
369    virtual void CreateKeygenHandler(
370        uint32 key_size_in_bits,
371        const std::string& challenge_string,
372        const GURL& url,
373        const base::Callback<void(scoped_ptr<net::KeygenHandler>)>& callback)
374        OVERRIDE;
375    virtual bool AllowMicAccess(const GURL& origin) OVERRIDE;
376    virtual bool AllowCameraAccess(const GURL& origin) OVERRIDE;
377    virtual SaltCallback GetMediaDeviceIDSalt() OVERRIDE;
378
379   private:
380    friend class ProfileIOData;
381
382    // Helper method that returns true if |type| is allowed for |origin|, false
383    // otherwise.
384    bool AllowContentAccess(const GURL& origin, ContentSettingsType type);
385
386    ProfileIOData* const io_data_;
387
388    net::HostResolver* host_resolver_;
389    net::URLRequestContext* request_context_;
390  };
391
392  typedef std::map<StoragePartitionDescriptor,
393                   ChromeURLRequestContext*,
394                   StoragePartitionDescriptorLess>
395      URLRequestContextMap;
396
397  // --------------------------------------------
398  // Virtual interface for subtypes to implement:
399  // --------------------------------------------
400
401  // Does the actual initialization of the ProfileIOData subtype. Subtypes
402  // should use the static helper functions above to implement this.
403  virtual void InitializeInternal(
404      ProfileParams* profile_params,
405      content::ProtocolHandlerMap* protocol_handlers) const = 0;
406
407  // Initializes the RequestContext for extensions.
408  virtual void InitializeExtensionsRequestContext(
409      ProfileParams* profile_params) const = 0;
410  // Does an on-demand initialization of a RequestContext for the given
411  // isolated app.
412  virtual ChromeURLRequestContext* InitializeAppRequestContext(
413      ChromeURLRequestContext* main_context,
414      const StoragePartitionDescriptor& details,
415      scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
416          protocol_handler_interceptor,
417      content::ProtocolHandlerMap* protocol_handlers) const = 0;
418
419  // Does an on-demand initialization of a media RequestContext for the given
420  // isolated app.
421  virtual ChromeURLRequestContext* InitializeMediaRequestContext(
422      ChromeURLRequestContext* original_context,
423      const StoragePartitionDescriptor& details) const = 0;
424
425  // These functions are used to transfer ownership of the lazily initialized
426  // context from ProfileIOData to the URLRequestContextGetter.
427  virtual ChromeURLRequestContext*
428      AcquireMediaRequestContext() const = 0;
429  virtual ChromeURLRequestContext*
430      AcquireIsolatedAppRequestContext(
431          ChromeURLRequestContext* main_context,
432          const StoragePartitionDescriptor& partition_descriptor,
433          scoped_ptr<ProtocolHandlerRegistry::JobInterceptorFactory>
434              protocol_handler_interceptor,
435          content::ProtocolHandlerMap* protocol_handlers) const = 0;
436  virtual ChromeURLRequestContext*
437      AcquireIsolatedMediaRequestContext(
438          ChromeURLRequestContext* app_context,
439          const StoragePartitionDescriptor& partition_descriptor) const = 0;
440
441  // The order *DOES* matter for the majority of these member variables, so
442  // don't move them around unless you know what you're doing!
443  // General rules:
444  //   * ResourceContext references the URLRequestContexts, so
445  //   URLRequestContexts must outlive ResourceContext, hence ResourceContext
446  //   should be destroyed first.
447  //   * URLRequestContexts reference a whole bunch of members, so
448  //   URLRequestContext needs to be destroyed before them.
449  //   * Therefore, ResourceContext should be listed last, and then the
450  //   URLRequestContexts, and then the URLRequestContext members.
451  //   * Note that URLRequestContext members have a directed dependency graph
452  //   too, so they must themselves be ordered correctly.
453
454  // Tracks whether or not we've been lazily initialized.
455  mutable bool initialized_;
456
457  // Data from the UI thread from the Profile, used to initialize ProfileIOData.
458  // Deleted after lazy initialization.
459  mutable scoped_ptr<ProfileParams> profile_params_;
460
461  // Provides access to the email addresses of all signed in profiles.
462  mutable scoped_ptr<SigninNamesOnIOThread> signin_names_;
463
464  // Used for testing.
465  mutable base::Callback<scoped_ptr<net::ClientCertStore>()>
466      client_cert_store_factory_;
467
468  mutable StringPrefMember google_services_user_account_id_;
469  mutable StringPrefMember google_services_username_;
470  mutable StringPrefMember google_services_username_pattern_;
471  mutable BooleanPrefMember reverse_autologin_enabled_;
472
473  // During the reverse autologin request chain processing, this member saves
474  // the email of the google account that is being signed into.
475  std::string reverse_autologin_pending_email_;
476
477  mutable StringListPrefMember one_click_signin_rejected_email_list_;
478
479  mutable scoped_refptr<MediaDeviceIDSalt> media_device_id_salt_;
480
481  // Member variables which are pointed to by the various context objects.
482  mutable BooleanPrefMember enable_referrers_;
483  mutable BooleanPrefMember enable_do_not_track_;
484  mutable BooleanPrefMember force_safesearch_;
485  mutable BooleanPrefMember safe_browsing_enabled_;
486  mutable BooleanPrefMember printing_enabled_;
487  mutable BooleanPrefMember sync_disabled_;
488  mutable BooleanPrefMember signin_allowed_;
489  mutable BooleanPrefMember network_prediction_enabled_;
490  // TODO(marja): Remove session_startup_pref_ if no longer needed.
491  mutable IntegerPrefMember session_startup_pref_;
492  mutable BooleanPrefMember quick_check_enabled_;
493
494  // The state of metrics reporting in the browser that this profile runs on.
495  // Unfortunately, since ChromeOS has a separate representation of this state,
496  // we need to make one available based on the platform.
497#if defined(OS_CHROMEOS)
498  bool enable_metrics_;
499#else
500  BooleanPrefMember enable_metrics_;
501#endif
502
503#if defined(ENABLE_CONFIGURATION_POLICY)
504  // Pointed to by NetworkDelegate.
505  mutable scoped_ptr<policy::URLBlacklistManager> url_blacklist_manager_;
506  mutable scoped_ptr<policy::PolicyHeaderIOHelper> policy_header_helper_;
507#endif
508
509  // Pointed to by URLRequestContext.
510  mutable scoped_refptr<extensions::InfoMap> extension_info_map_;
511  mutable scoped_ptr<net::ServerBoundCertService> server_bound_cert_service_;
512  mutable scoped_ptr<ChromeNetworkDelegate> network_delegate_;
513  mutable scoped_ptr<net::FraudulentCertificateReporter>
514      fraudulent_certificate_reporter_;
515  mutable scoped_ptr<net::ProxyService> proxy_service_;
516  mutable scoped_ptr<net::TransportSecurityState> transport_security_state_;
517  mutable scoped_ptr<net::HttpServerProperties>
518      http_server_properties_;
519#if defined(OS_CHROMEOS)
520  mutable scoped_ptr<policy::PolicyCertVerifier> cert_verifier_;
521  mutable std::string username_hash_;
522#endif
523
524  mutable scoped_ptr<net::TransportSecurityPersister>
525      transport_security_persister_;
526
527  // These are only valid in between LazyInitialize() and their accessor being
528  // called.
529  mutable scoped_ptr<ChromeURLRequestContext> main_request_context_;
530  mutable scoped_ptr<ChromeURLRequestContext> extensions_request_context_;
531  // One URLRequestContext per isolated app for main and media requests.
532  mutable URLRequestContextMap app_request_context_map_;
533  mutable URLRequestContextMap isolated_media_request_context_map_;
534
535  mutable scoped_ptr<ResourceContext> resource_context_;
536
537  mutable scoped_refptr<CookieSettings> cookie_settings_;
538
539  mutable scoped_refptr<HostContentSettingsMap> host_content_settings_map_;
540
541  mutable scoped_ptr<ChromeHttpUserAgentSettings>
542      chrome_http_user_agent_settings_;
543
544#if defined(ENABLE_MANAGED_USERS)
545  mutable scoped_refptr<const ManagedModeURLFilter> managed_mode_url_filter_;
546#endif
547
548  // TODO(jhawkins): Remove once crbug.com/102004 is fixed.
549  bool initialized_on_UI_thread_;
550
551  bool is_incognito_;
552
553  DISALLOW_COPY_AND_ASSIGN(ProfileIOData);
554};
555
556#endif  // CHROME_BROWSER_PROFILES_PROFILE_IO_DATA_H_
557