summaryrefslogtreecommitdiffstats
path: root/chrome/browser/extensions/extension_cookies_api.cc
blob: 22b29dacb6ba617e3adbce0c7af3ef4ab1a6a34c (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
// 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.

// Implements the Chrome Extensions Cookies API.

#include "chrome/browser/extensions/extension_cookies_api.h"

#include "base/json/json_writer.h"
#include "base/task.h"
#include "base/values.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/extensions/extension_cookies_api_constants.h"
#include "chrome/browser/extensions/extension_cookies_helpers.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/notification_service.h"
#include "net/base/cookie_monster.h"

namespace keys = extension_cookies_api_constants;

// static
ExtensionCookiesEventRouter* ExtensionCookiesEventRouter::GetInstance() {
  return Singleton<ExtensionCookiesEventRouter>::get();
}

void ExtensionCookiesEventRouter::Init() {
  if (registrar_.IsEmpty()) {
    registrar_.Add(this,
                   NotificationType::COOKIE_CHANGED,
                   NotificationService::AllSources());
  }
}

void ExtensionCookiesEventRouter::Observe(NotificationType type,
                                          const NotificationSource& source,
                                          const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::COOKIE_CHANGED:
      CookieChanged(
          Source<Profile>(source).ptr(),
          Details<ChromeCookieDetails>(details).ptr());
      break;

    default:
      NOTREACHED();
  }
}

void ExtensionCookiesEventRouter::CookieChanged(
    Profile* profile,
    ChromeCookieDetails* details) {
  ListValue args;
  DictionaryValue* dict = new DictionaryValue();
  dict->SetBoolean(keys::kRemovedKey, details->removed);
  dict->Set(
      keys::kCookieKey,
      extension_cookies_helpers::CreateCookieValue(*details->cookie,
          extension_cookies_helpers::GetStoreIdFromProfile(profile)));
  args.Append(dict);

  std::string json_args;
  base::JSONWriter::Write(&args, false, &json_args);
  GURL cookie_domain =
      extension_cookies_helpers::GetURLFromCanonicalCookie(*details->cookie);
  DispatchEvent(profile, keys::kOnChanged, json_args, cookie_domain);
}

void ExtensionCookiesEventRouter::DispatchEvent(Profile* profile,
                                                const char* event_name,
                                                const std::string& json_args,
                                                GURL& cookie_domain) {
  if (profile && profile->GetExtensionEventRouter()) {
    profile->GetExtensionEventRouter()->DispatchEventToRenderers(
        event_name, json_args, profile, cookie_domain);
  }
}

bool CookiesFunction::ParseUrl(const DictionaryValue* details, GURL* url,
                               bool check_host_permissions) {
  DCHECK(details && url);
  std::string url_string;
  // Get the URL string or return false.
  EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kUrlKey, &url_string));
  *url = GURL(url_string);
  if (!url->is_valid()) {
    error_ = ExtensionErrorUtils::FormatErrorMessage(
        keys::kInvalidUrlError, url_string);
    return false;
  }
  // Check against host permissions if needed.
  if (check_host_permissions &&
      !GetExtension()->HasHostPermission(*url)) {
    error_ = ExtensionErrorUtils::FormatErrorMessage(
        keys::kNoHostPermissionsError, url->spec());
    return false;
  }
  return true;
}

bool CookiesFunction::ParseStoreContext(const DictionaryValue* details,
                                        URLRequestContextGetter** context,
                                        std::string* store_id) {
  DCHECK(details && (context || store_id));
  Profile* store_profile = NULL;
  if (details->HasKey(keys::kStoreIdKey)) {
    // The store ID was explicitly specified in the details dictionary.
    // Retrieve its corresponding cookie store.
    std::string store_id_value;
    // Get the store ID string or return false.
    EXTENSION_FUNCTION_VALIDATE(
        details->GetString(keys::kStoreIdKey, &store_id_value));
    store_profile = extension_cookies_helpers::ChooseProfileFromStoreId(
        store_id_value, profile(), include_incognito());
    if (!store_profile) {
      error_ = ExtensionErrorUtils::FormatErrorMessage(
          keys::kInvalidStoreIdError, store_id_value);
      return false;
    }
  } else {
    // The store ID was not specified; use the current execution context's
    // cookie store by default.
    // GetCurrentBrowser() already takes into account incognito settings.
    Browser* current_browser = GetCurrentBrowser();
    if (!current_browser) {
      error_ = keys::kNoCookieStoreFoundError;
      return false;
    }
    store_profile = current_browser->profile();
  }
  DCHECK(store_profile);

  if (context)
    *context = store_profile->GetRequestContext();
  if (store_id)
    *store_id = extension_cookies_helpers::GetStoreIdFromProfile(store_profile);

  return true;
}

GetCookieFunction::GetCookieFunction() {}

GetCookieFunction::~GetCookieFunction() {}

bool GetCookieFunction::RunImpl() {
  // Return false if the arguments are malformed.
  DictionaryValue* details;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details));
  DCHECK(details);

  // Read/validate input parameters.
  if (!ParseUrl(details, &url_, true))
    return false;

  // Get the cookie name string or return false.
  EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kNameKey, &name_));

  URLRequestContextGetter* store_context = NULL;
  if (!ParseStoreContext(details, &store_context, &store_id_))
    return false;

  DCHECK(store_context && !store_id_.empty());
  store_context_ = store_context;

  bool rv = BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      NewRunnableMethod(this, &GetCookieFunction::GetCookieOnIOThread));
  DCHECK(rv);

  // Will finish asynchronously.
  return true;
}

void GetCookieFunction::GetCookieOnIOThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  net::CookieStore* cookie_store = store_context_->GetCookieStore();
  net::CookieList cookie_list =
      extension_cookies_helpers::GetCookieListFromStore(cookie_store, url_);
  net::CookieList::iterator it;
  for (it = cookie_list.begin(); it != cookie_list.end(); ++it) {
    // Return the first matching cookie. Relies on the fact that the
    // CookieMonster returns them in canonical order (longest path, then
    // earliest creation time).
    if (it->Name() == name_) {
      result_.reset(
          extension_cookies_helpers::CreateCookieValue(*it, store_id_));
      break;
    }
  }

  // The cookie doesn't exist; return null.
  if (it == cookie_list.end())
    result_.reset(Value::CreateNullValue());

  bool rv = BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(this, &GetCookieFunction::RespondOnUIThread));
  DCHECK(rv);
}

void GetCookieFunction::RespondOnUIThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  SendResponse(true);
}

GetAllCookiesFunction::GetAllCookiesFunction() : details_(NULL) {}

GetAllCookiesFunction::~GetAllCookiesFunction() {}

bool GetAllCookiesFunction::RunImpl() {
  // Return false if the arguments are malformed.
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details_));
  DCHECK(details_);

  // Read/validate input parameters.
  if (details_->HasKey(keys::kUrlKey) && !ParseUrl(details_, &url_, false))
    return false;

  URLRequestContextGetter* store_context = NULL;
  if (!ParseStoreContext(details_, &store_context, &store_id_))
    return false;
  DCHECK(store_context);
  store_context_ = store_context;

  bool rv = BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      NewRunnableMethod(this, &GetAllCookiesFunction::GetAllCookiesOnIOThread));
  DCHECK(rv);

  // Will finish asynchronously.
  return true;
}

void GetAllCookiesFunction::GetAllCookiesOnIOThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  net::CookieStore* cookie_store = store_context_->GetCookieStore();
  net::CookieList cookie_list =
      extension_cookies_helpers::GetCookieListFromStore(cookie_store, url_);

  const Extension* extension = GetExtension();
  if (extension) {
    ListValue* matching_list = new ListValue();
    extension_cookies_helpers::AppendMatchingCookiesToList(
        cookie_list, store_id_, url_, details_,
        GetExtension(), matching_list);
    result_.reset(matching_list);
  }
  bool rv = BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(this, &GetAllCookiesFunction::RespondOnUIThread));
  DCHECK(rv);
}

void GetAllCookiesFunction::RespondOnUIThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  SendResponse(true);
}

SetCookieFunction::SetCookieFunction()
    : secure_(false),
      http_only_(false),
      success_(false) {
}

SetCookieFunction::~SetCookieFunction() {
}

bool SetCookieFunction::RunImpl() {
  // Return false if the arguments are malformed.
  DictionaryValue* details;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details));
  DCHECK(details);

  // Read/validate input parameters.
  if (!ParseUrl(details, &url_, true))
      return false;
  // The macros below return false if argument types are not as expected.
  if (details->HasKey(keys::kNameKey))
    EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kNameKey, &name_));
  if (details->HasKey(keys::kValueKey))
    EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kValueKey, &value_));
  if (details->HasKey(keys::kDomainKey))
    EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kDomainKey, &domain_));
  if (details->HasKey(keys::kPathKey))
    EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kPathKey, &path_));

  if (details->HasKey(keys::kSecureKey)) {
    EXTENSION_FUNCTION_VALIDATE(
        details->GetBoolean(keys::kSecureKey, &secure_));
  }
  if (details->HasKey(keys::kHttpOnlyKey)) {
    EXTENSION_FUNCTION_VALIDATE(
        details->GetBoolean(keys::kHttpOnlyKey, &http_only_));
  }
  if (details->HasKey(keys::kExpirationDateKey)) {
    Value* expiration_date_value;
    EXTENSION_FUNCTION_VALIDATE(details->Get(keys::kExpirationDateKey,
                                             &expiration_date_value));
    double expiration_date;
    if (expiration_date_value->IsType(Value::TYPE_INTEGER)) {
      int expiration_date_int;
      EXTENSION_FUNCTION_VALIDATE(
          expiration_date_value->GetAsInteger(&expiration_date_int));
      expiration_date = static_cast<double>(expiration_date_int);
    } else {
      EXTENSION_FUNCTION_VALIDATE(
          expiration_date_value->GetAsDouble(&expiration_date));
    }
    // Time::FromDoubleT converts double time 0 to empty Time object. So we need
    // to do special handling here.
    expiration_time_ = (expiration_date == 0) ?
        base::Time::UnixEpoch() : base::Time::FromDoubleT(expiration_date);
  }

  URLRequestContextGetter* store_context = NULL;
  if (!ParseStoreContext(details, &store_context, NULL))
    return false;
  DCHECK(store_context);
  store_context_ = store_context;

  bool rv = BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      NewRunnableMethod(this, &SetCookieFunction::SetCookieOnIOThread));
  DCHECK(rv);

  // Will finish asynchronously.
  return true;
}

void SetCookieFunction::SetCookieOnIOThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  net::CookieMonster* cookie_monster =
      store_context_->GetCookieStore()->GetCookieMonster();
  success_ = cookie_monster->SetCookieWithDetails(
      url_, name_, value_, domain_, path_, expiration_time_,
      secure_, http_only_);

  // Pull the newly set cookie.
  net::CookieList cookie_list =
      extension_cookies_helpers::GetCookieListFromStore(cookie_monster, url_);
  net::CookieList::iterator it;
  for (it = cookie_list.begin(); it != cookie_list.end(); ++it) {
    // Return the first matching cookie. Relies on the fact that the
    // CookieMonster returns them in canonical order (longest path, then
    // earliest creation time).
    if (it->Name() == name_) {
      result_.reset(
          extension_cookies_helpers::CreateCookieValue(*it, store_id_));
      break;
    }
  }

  bool rv = BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      NewRunnableMethod(this, &SetCookieFunction::RespondOnUIThread));
  DCHECK(rv);
}

void SetCookieFunction::RespondOnUIThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!success_) {
    error_ = ExtensionErrorUtils::FormatErrorMessage(
        keys::kCookieSetFailedError, name_);
  }
  SendResponse(success_);
}

namespace {

class RemoveCookieTask : public Task {
 public:
  RemoveCookieTask(const GURL& url,
                   const std::string& name,
                   const scoped_refptr<URLRequestContextGetter>& context_getter)
      : url_(url),
        name_(name),
        context_getter_(context_getter) {}

  virtual void Run() {
    net::CookieStore* cookie_store = context_getter_->GetCookieStore();
    cookie_store->DeleteCookie(url_, name_);
  }

 private:
  const GURL url_;
  const std::string name_;
  const scoped_refptr<URLRequestContextGetter> context_getter_;

  DISALLOW_COPY_AND_ASSIGN(RemoveCookieTask);
};

}  // namespace

bool RemoveCookieFunction::RunImpl() {
  // Return false if the arguments are malformed.
  DictionaryValue* details;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details));
  DCHECK(details);

  // Read/validate input parameters.
  GURL url;
  if (!ParseUrl(details, &url, true))
    return false;

  std::string name;
  // Get the cookie name string or return false.
  EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kNameKey, &name));

  URLRequestContextGetter* store_context = NULL;
  std::string store_id;
  if (!ParseStoreContext(details, &store_context, &store_id))
    return false;
  DCHECK(store_context);

  // We don't bother to synchronously wait for the result here, because
  // CookieMonster is only ever accessed on the IO thread, so any other accesses
  // should happen after this.
  bool rv = BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      new RemoveCookieTask(url, name, make_scoped_refptr(store_context)));
  DCHECK(rv);

  DictionaryValue* resultDictionary = new DictionaryValue();
  resultDictionary->SetString(keys::kNameKey, name);
  resultDictionary->SetString(keys::kUrlKey, url.spec());
  resultDictionary->SetString(keys::kStoreIdKey, store_id);
  result_.reset(resultDictionary);

  return true;
}

void RemoveCookieFunction::Run() {
  SendResponse(RunImpl());
}

bool GetAllCookieStoresFunction::RunImpl() {
  Profile* original_profile = profile();
  DCHECK(original_profile);
  scoped_ptr<ListValue> original_tab_ids(new ListValue());
  Profile* incognito_profile = NULL;
  scoped_ptr<ListValue> incognito_tab_ids;
  if (include_incognito() && profile()->HasOffTheRecordProfile()) {
    incognito_profile = profile()->GetOffTheRecordProfile();
    if (incognito_profile)
      incognito_tab_ids.reset(new ListValue());
  }
  DCHECK(original_profile != incognito_profile);

  // Iterate through all browser instances, and for each browser,
  // add its tab IDs to either the regular or incognito tab ID list depending
  // whether the browser is regular or incognito.
  for (BrowserList::const_iterator iter = BrowserList::begin();
       iter != BrowserList::end(); ++iter) {
    Browser* browser = *iter;
    if (browser->profile() == original_profile) {
      extension_cookies_helpers::AppendToTabIdList(browser,
                                                   original_tab_ids.get());
    } else if (incognito_tab_ids.get() &&
               browser->profile() == incognito_profile) {
      extension_cookies_helpers::AppendToTabIdList(browser,
                                                   incognito_tab_ids.get());
    }
  }
  // Return a list of all cookie stores with at least one open tab.
  ListValue* cookie_store_list = new ListValue();
  if (original_tab_ids->GetSize() > 0) {
    cookie_store_list->Append(
        extension_cookies_helpers::CreateCookieStoreValue(
            original_profile, original_tab_ids.release()));
  }
  if (incognito_tab_ids.get() && incognito_tab_ids->GetSize() > 0) {
    cookie_store_list->Append(
        extension_cookies_helpers::CreateCookieStoreValue(
            incognito_profile, incognito_tab_ids.release()));
  }
  result_.reset(cookie_store_list);
  return true;
}

void GetAllCookieStoresFunction::Run() {
  SendResponse(RunImpl());
}