summaryrefslogtreecommitdiffstats
path: root/chrome/browser/content_settings/host_content_settings_map.cc
blob: 3d15073c40ece187724b2e385ef29fceae11819d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/content_settings/host_content_settings_map.h"

#include <list>

#include "base/command_line.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/content_settings/content_settings_details.h"
#include "chrome/browser/content_settings/content_settings_extension_provider.h"
#include "chrome/browser/content_settings/content_settings_observable_provider.h"
#include "chrome/browser/content_settings/content_settings_policy_provider.h"
#include "chrome/browser/content_settings/content_settings_pref_provider.h"
#include "chrome/browser/content_settings/content_settings_provider.h"
#include "chrome/browser/content_settings/content_settings_utils.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "content/browser/user_metrics.h"
#include "content/common/notification_service.h"
#include "content/common/notification_source.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/base/static_cookie_policy.h"

namespace {

// Returns true if we should allow all content types for this URL.  This is
// true for various internal objects like chrome:// URLs, so UI and other
// things users think of as "not webpages" don't break.
static bool ShouldAllowAllContent(const GURL& url) {
  return url.SchemeIs(chrome::kChromeDevToolsScheme) ||
         url.SchemeIs(chrome::kChromeInternalScheme) ||
         url.SchemeIs(chrome::kChromeUIScheme) ||
         url.SchemeIs(chrome::kExtensionScheme);
}

typedef linked_ptr<content_settings::DefaultProviderInterface>
    DefaultContentSettingsProviderPtr;
typedef std::vector<DefaultContentSettingsProviderPtr>::iterator
    DefaultProviderIterator;
typedef std::vector<DefaultContentSettingsProviderPtr>::const_iterator
    ConstDefaultProviderIterator;

typedef linked_ptr<content_settings::ProviderInterface> ProviderPtr;
typedef std::vector<ProviderPtr>::iterator ProviderIterator;
typedef std::vector<ProviderPtr>::const_iterator ConstProviderIterator;

typedef content_settings::ProviderInterface::Rules Rules;

typedef std::pair<std::string, std::string> StringPair;

const char* kProviderNames[] = {
  "policy",
  "extension",
  "preference"
};

}  // namespace

HostContentSettingsMap::HostContentSettingsMap(
    PrefService* prefs,
    ExtensionService* extension_service,
    bool incognito)
    : prefs_(prefs),
      is_off_the_record_(incognito),
      updating_preferences_(false),
      block_third_party_cookies_(false),
      is_block_third_party_cookies_managed_(false) {
  // The order in which the default content settings providers are created is
  // critical, as providers that are further down in the list (i.e. added later)
  // override providers further up.
  content_settings::PrefDefaultProvider* default_provider =
      new content_settings::PrefDefaultProvider(prefs_, is_off_the_record_);
  default_provider->AddObserver(this);
  default_content_settings_providers_.push_back(
      make_linked_ptr(default_provider));

  content_settings::PolicyDefaultProvider* policy_default_provider =
      new content_settings::PolicyDefaultProvider(prefs_);
  policy_default_provider->AddObserver(this);
  default_content_settings_providers_.push_back(
      make_linked_ptr(policy_default_provider));

  // TODO(markusheintz): Discuss whether it is sensible to move migration code
  // to PrefContentSettingsProvider.
  MigrateObsoleteCookiePref();

  // Read misc. global settings.
  block_third_party_cookies_ =
      prefs_->GetBoolean(prefs::kBlockThirdPartyCookies);
  if (block_third_party_cookies_) {
    UserMetrics::RecordAction(
        UserMetricsAction("ThirdPartyCookieBlockingEnabled"));
  } else {
    UserMetrics::RecordAction(
        UserMetricsAction("ThirdPartyCookieBlockingDisabled"));
  }
  is_block_third_party_cookies_managed_ =
      prefs_->IsManagedPreference(prefs::kBlockThirdPartyCookies);

  // User defined non default content settings are provided by the PrefProvider.
  // The order in which the content settings providers are created is critical,
  // as providers that are further up in the list (i.e. added earlier) override
  // providers further down.
  content_settings::ObservableProvider* provider =
      new content_settings::PolicyProvider(prefs_, policy_default_provider);
  provider->AddObserver(this);
  content_settings_providers_.push_back(make_linked_ptr(provider));

  if (extension_service) {
    // |extension_service| can be NULL in unit tests.
    provider = new content_settings::ExtensionProvider(
        extension_service->GetExtensionContentSettingsStore(),
        is_off_the_record_);
    provider->AddObserver(this);
    content_settings_providers_.push_back(make_linked_ptr(provider));
  }
  provider = new content_settings::PrefProvider(prefs_, is_off_the_record_);
  provider->AddObserver(this);
  content_settings_providers_.push_back(make_linked_ptr(provider));

  pref_change_registrar_.Init(prefs_);
  pref_change_registrar_.Add(prefs::kBlockThirdPartyCookies, this);
}

// static
void HostContentSettingsMap::RegisterUserPrefs(PrefService* prefs) {
  prefs->RegisterBooleanPref(prefs::kBlockThirdPartyCookies,
                             false,
                             PrefService::SYNCABLE_PREF);
  prefs->RegisterIntegerPref(prefs::kContentSettingsWindowLastTabIndex,
                             0,
                             PrefService::UNSYNCABLE_PREF);

  // Obsolete prefs, for migration:
  prefs->RegisterIntegerPref(prefs::kCookieBehavior,
                             net::StaticCookiePolicy::ALLOW_ALL_COOKIES,
                             PrefService::UNSYNCABLE_PREF);

  // Register the prefs for the content settings providers.
  content_settings::PrefDefaultProvider::RegisterUserPrefs(prefs);
  content_settings::PolicyDefaultProvider::RegisterUserPrefs(prefs);
  content_settings::PrefProvider::RegisterUserPrefs(prefs);
  content_settings::PolicyProvider::RegisterUserPrefs(prefs);
}

ContentSetting HostContentSettingsMap::GetDefaultContentSetting(
    ContentSettingsType content_type) const {
  ContentSetting setting = CONTENT_SETTING_DEFAULT;
  for (ConstDefaultProviderIterator provider =
           default_content_settings_providers_.begin();
       provider != default_content_settings_providers_.end(); ++provider) {
    ContentSetting provided_setting =
        (*provider)->ProvideDefaultSetting(content_type);
    if (provided_setting != CONTENT_SETTING_DEFAULT)
      setting = provided_setting;
  }
  // The method GetDefaultContentSetting always has to return an explicit
  // value that is to be used as default. We here rely on the
  // PrefContentSettingProvider to always provide a value.
  CHECK_NE(CONTENT_SETTING_DEFAULT, setting);
  return setting;
}

ContentSettings HostContentSettingsMap::GetDefaultContentSettings() const {
  ContentSettings output(CONTENT_SETTING_DEFAULT);
  for (int i = 0; i < CONTENT_SETTINGS_NUM_TYPES; ++i)
    output.settings[i] = GetDefaultContentSetting(ContentSettingsType(i));
  return output;
}

ContentSetting HostContentSettingsMap::GetCookieContentSetting(
    const GURL& url,
    const GURL& first_party_url,
    bool setting_cookie) const {
  if (ShouldAllowAllContent(first_party_url))
    return CONTENT_SETTING_ALLOW;

  // First get any host-specific settings.
  ContentSetting setting = GetNonDefaultContentSetting(url,
      first_party_url, CONTENT_SETTINGS_TYPE_COOKIES, "");

  // If no explicit exception has been made and third-party cookies are blocked
  // by default, apply that rule.
  if (setting == CONTENT_SETTING_DEFAULT && BlockThirdPartyCookies()) {
    bool strict = CommandLine::ForCurrentProcess()->HasSwitch(
        switches::kBlockReadingThirdPartyCookies);
    net::StaticCookiePolicy policy(strict ?
        net::StaticCookiePolicy::BLOCK_ALL_THIRD_PARTY_COOKIES :
        net::StaticCookiePolicy::BLOCK_SETTING_THIRD_PARTY_COOKIES);
    int rv;
    if (setting_cookie)
      rv = policy.CanSetCookie(url, first_party_url);
    else
      rv = policy.CanGetCookies(url, first_party_url);
    DCHECK_NE(net::ERR_IO_PENDING, rv);
    if (rv != net::OK)
      setting = CONTENT_SETTING_BLOCK;
  }

  // If no other policy has changed the setting, use the default.
  if (setting == CONTENT_SETTING_DEFAULT)
    setting = GetDefaultContentSetting(CONTENT_SETTINGS_TYPE_COOKIES);

  return setting;
}

ContentSetting HostContentSettingsMap::GetContentSetting(
    const GURL& primary_url,
    const GURL& secondary_url,
    ContentSettingsType content_type,
    const std::string& resource_identifier) const {
  DCHECK_NE(CONTENT_SETTINGS_TYPE_COOKIES, content_type);
  DCHECK_NE(content_settings::RequiresResourceIdentifier(content_type),
            resource_identifier.empty());
  return GetContentSettingInternal(
      primary_url, secondary_url, content_type, resource_identifier);
}

ContentSetting HostContentSettingsMap::GetContentSettingInternal(
      const GURL& primary_url,
      const GURL& secondary_url,
      ContentSettingsType content_type,
      const std::string& resource_identifier) const {
  ContentSetting setting = GetNonDefaultContentSetting(
      primary_url, secondary_url, content_type, resource_identifier);
  if (setting == CONTENT_SETTING_DEFAULT)
    return GetDefaultContentSetting(content_type);
  return setting;
}

ContentSetting HostContentSettingsMap::GetNonDefaultContentSetting(
      const GURL& primary_url,
      const GURL& secondary_url,
      ContentSettingsType content_type,
      const std::string& resource_identifier) const {
  if (ShouldAllowAllContent(secondary_url))
    return CONTENT_SETTING_ALLOW;

  // Iterate through the list of providers and break when the first non default
  // setting is found.
  ContentSetting provided_setting(CONTENT_SETTING_DEFAULT);
  for (ConstProviderIterator provider = content_settings_providers_.begin();
       provider != content_settings_providers_.end();
       ++provider) {
    provided_setting = (*provider)->GetContentSetting(
        primary_url, secondary_url, content_type, resource_identifier);
    if (provided_setting != CONTENT_SETTING_DEFAULT)
      return provided_setting;
  }
  return provided_setting;
}

ContentSettings HostContentSettingsMap::GetContentSettings(
      const GURL& primary_url,
      const GURL& secondary_url) const {
  ContentSettings output = GetNonDefaultContentSettings(
      primary_url, secondary_url);

  // If we require a resource identifier, set the content settings to default,
  // otherwise make the defaults explicit.
  for (int j = 0; j < CONTENT_SETTINGS_NUM_TYPES; ++j) {
    // A managed default content setting has the highest priority and hence
    // will overwrite any previously set value.
    if (output.settings[j] == CONTENT_SETTING_DEFAULT &&
        j != CONTENT_SETTINGS_TYPE_PLUGINS) {
      output.settings[j] = GetDefaultContentSetting(ContentSettingsType(j));
    }
  }
  return output;
}

ContentSettings HostContentSettingsMap::GetNonDefaultContentSettings(
    const GURL& primary_url,
    const GURL& secondary_url) const {
  if (ShouldAllowAllContent(secondary_url))
    return ContentSettings(CONTENT_SETTING_ALLOW);

  ContentSettings output(CONTENT_SETTING_DEFAULT);
  for (int j = 0; j < CONTENT_SETTINGS_NUM_TYPES; ++j) {
    output.settings[j] = GetNonDefaultContentSetting(
        primary_url,
        secondary_url,
        ContentSettingsType(j),
        "");
  }
  return output;
}

void HostContentSettingsMap::GetSettingsForOneType(
    ContentSettingsType content_type,
    const std::string& resource_identifier,
    SettingsForOneType* settings) const {
  DCHECK_NE(content_settings::RequiresResourceIdentifier(content_type),
            resource_identifier.empty());
  DCHECK(settings);

  settings->clear();
  for (size_t i = 0; i < content_settings_providers_.size(); ++i) {
    // Get rules from the content settings provider.
    Rules rules;
    content_settings_providers_[i]->GetAllContentSettingsRules(
        content_type, resource_identifier, &rules);

    // Sort rules according to their primary-secondary pattern string pairs
    // using a map.
    std::map<StringPair, PatternSettingSourceTuple> settings_map;
    for (Rules::iterator rule = rules.begin();
         rule != rules.end();
         ++rule) {
      StringPair sort_key(rule->primary_pattern.ToString(),
                          rule->secondary_pattern.ToString());
      settings_map[sort_key] = PatternSettingSourceTuple(
          rule->primary_pattern,
          rule->secondary_pattern,
          rule->content_setting,
          kProviderNames[i]);
    }

    // TODO(markusheintz): Only the rules that are applied should be added.
    for (std::map<StringPair, PatternSettingSourceTuple>::iterator i(
             settings_map.begin());
         i != settings_map.end();
         ++i) {
      settings->push_back(i->second);
    }
  }
}

void HostContentSettingsMap::SetDefaultContentSetting(
    ContentSettingsType content_type,
    ContentSetting setting) {
  DCHECK(IsSettingAllowedForType(setting, content_type));
  for (DefaultProviderIterator provider =
           default_content_settings_providers_.begin();
       provider != default_content_settings_providers_.end(); ++provider) {
    (*provider)->UpdateDefaultSetting(content_type, setting);
  }
}

void HostContentSettingsMap::SetContentSetting(
    const ContentSettingsPattern& primary_pattern,
    const ContentSettingsPattern& secondary_pattern,
    ContentSettingsType content_type,
    const std::string& resource_identifier,
    ContentSetting setting) {
  DCHECK(IsSettingAllowedForType(setting, content_type));
  DCHECK_NE(content_settings::RequiresResourceIdentifier(content_type),
            resource_identifier.empty());
  for (ProviderIterator provider = content_settings_providers_.begin();
       provider != content_settings_providers_.end();
       ++provider) {
    (*provider)->SetContentSetting(
        primary_pattern,
        secondary_pattern,
        content_type,
        resource_identifier,
        setting);
  }
}

void HostContentSettingsMap::AddExceptionForURL(
    const GURL& primary_url,
    const GURL& secondary_url,
    ContentSettingsType content_type,
    const std::string& resource_identifier,
    ContentSetting setting) {
  // TODO(markusheintz): Until the UI supports pattern pairs, both urls must
  // match.
  DCHECK(primary_url == secondary_url);

  // Make sure there is no entry that would override the pattern we are about
  // to insert for exactly this URL.
  SetContentSetting(ContentSettingsPattern::FromURLNoWildcard(primary_url),
                    ContentSettingsPattern::Wildcard(),
                    content_type,
                    resource_identifier,
                    CONTENT_SETTING_DEFAULT);

  SetContentSetting(ContentSettingsPattern::FromURL(primary_url),
                    ContentSettingsPattern::Wildcard(),
                    content_type,
                    resource_identifier,
                    setting);
}

void HostContentSettingsMap::ClearSettingsForOneType(
    ContentSettingsType content_type) {
  for (ProviderIterator provider = content_settings_providers_.begin();
       provider != content_settings_providers_.end();
       ++provider) {
    (*provider)->ClearAllContentSettingsRules(content_type);
  }
}

// static
bool HostContentSettingsMap::IsSettingAllowedForType(
    ContentSetting setting, ContentSettingsType content_type) {
  // Intents content settings are hidden behind a switch for now.
  if (content_type == CONTENT_SETTINGS_TYPE_INTENTS &&
      !CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableWebIntents))
    return false;

  // DEFAULT, ALLOW and BLOCK are always allowed.
  if (setting == CONTENT_SETTING_DEFAULT ||
      setting == CONTENT_SETTING_ALLOW ||
      setting == CONTENT_SETTING_BLOCK) {
    return true;
  }
  switch (content_type) {
    case CONTENT_SETTINGS_TYPE_COOKIES:
      return (setting == CONTENT_SETTING_SESSION_ONLY);
    case CONTENT_SETTINGS_TYPE_PLUGINS:
      return (setting == CONTENT_SETTING_ASK &&
              CommandLine::ForCurrentProcess()->HasSwitch(
                  switches::kEnableClickToPlay));
    case CONTENT_SETTINGS_TYPE_GEOLOCATION:
    case CONTENT_SETTINGS_TYPE_NOTIFICATIONS:
    case CONTENT_SETTINGS_TYPE_INTENTS:
      return (setting == CONTENT_SETTING_ASK);
    default:
      return false;
  }
}

void HostContentSettingsMap::SetBlockThirdPartyCookies(bool block) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(prefs_);

  // This setting may not be directly modified for OTR sessions.  Instead, it
  // is synced to the main profile's setting.
  if (is_off_the_record_) {
    NOTREACHED();
    return;
  }

  // If the preference block-third-party-cookies is managed then do not allow to
  // change it.
  if (prefs_->IsManagedPreference(prefs::kBlockThirdPartyCookies)) {
    NOTREACHED();
    return;
  }

  {
    base::AutoLock auto_lock(lock_);
    block_third_party_cookies_ = block;
  }

  prefs_->SetBoolean(prefs::kBlockThirdPartyCookies, block);
}

void HostContentSettingsMap::OnContentSettingChanged(
    ContentSettingsPattern primary_pattern,
    ContentSettingsPattern secondary_pattern,
    ContentSettingsType content_type,
    std::string resource_identifier) {
  const ContentSettingsDetails details(primary_pattern,
                                       secondary_pattern,
                                       content_type,
                                       resource_identifier);
  NotificationService::current()->Notify(
      chrome::NOTIFICATION_CONTENT_SETTINGS_CHANGED,
      Source<HostContentSettingsMap>(this),
      Details<const ContentSettingsDetails>(&details));
}

void HostContentSettingsMap::Observe(int type,
                                     const NotificationSource& source,
                                     const NotificationDetails& details) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (type == chrome::NOTIFICATION_PREF_CHANGED) {
    DCHECK_EQ(prefs_, Source<PrefService>(source).ptr());
    if (updating_preferences_)
      return;

    std::string* name = Details<std::string>(details).ptr();
    if (*name == prefs::kBlockThirdPartyCookies) {
      base::AutoLock auto_lock(lock_);
      block_third_party_cookies_ = prefs_->GetBoolean(
          prefs::kBlockThirdPartyCookies);
      is_block_third_party_cookies_managed_ =
          prefs_->IsManagedPreference(
              prefs::kBlockThirdPartyCookies);
    } else {
      NOTREACHED() << "Unexpected preference observed";
      return;
    }
  } else {
    NOTREACHED() << "Unexpected notification";
  }
}

HostContentSettingsMap::~HostContentSettingsMap() {
  DCHECK(!prefs_);
}

bool HostContentSettingsMap::IsDefaultContentSettingManaged(
    ContentSettingsType content_type) const {
  for (ConstDefaultProviderIterator provider =
           default_content_settings_providers_.begin();
       provider != default_content_settings_providers_.end(); ++provider) {
    if ((*provider)->DefaultSettingIsManaged(content_type))
      return true;
  }
  return false;
}

void HostContentSettingsMap::ShutdownOnUIThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DCHECK(prefs_);
  pref_change_registrar_.RemoveAll();
  prefs_ = NULL;
  for (ProviderIterator it = content_settings_providers_.begin();
       it != content_settings_providers_.end();
       ++it) {
    (*it)->ShutdownOnUIThread();
  }
  for (DefaultProviderIterator it = default_content_settings_providers_.begin();
       it != default_content_settings_providers_.end();
       ++it) {
    (*it)->ShutdownOnUIThread();
  }
}

void HostContentSettingsMap::MigrateObsoleteCookiePref() {
  if (prefs_->HasPrefPath(prefs::kCookieBehavior)) {
    int cookie_behavior = prefs_->GetInteger(prefs::kCookieBehavior);
    prefs_->ClearPref(prefs::kCookieBehavior);
    if (!prefs_->HasPrefPath(prefs::kDefaultContentSettings)) {
        SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_COOKIES,
            (cookie_behavior == net::StaticCookiePolicy::BLOCK_ALL_COOKIES) ?
                CONTENT_SETTING_BLOCK : CONTENT_SETTING_ALLOW);
    }
    if (!prefs_->HasPrefPath(prefs::kBlockThirdPartyCookies)) {
      SetBlockThirdPartyCookies(cookie_behavior ==
          net::StaticCookiePolicy::BLOCK_SETTING_THIRD_PARTY_COOKIES);
    }
  }
}