1// Copyright 2014 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#include "extensions/browser/blob_holder.h"
6
7#include <algorithm>
8#include <utility>
9
10#include "base/logging.h"
11#include "content/public/browser/blob_handle.h"
12#include "content/public/browser/browser_thread.h"
13#include "content/public/browser/render_process_host.h"
14
15namespace extensions {
16
17namespace {
18
19// Address to this variable used as the user data key.
20const int kBlobHolderUserDataKey = 0;
21}
22
23// static
24BlobHolder* BlobHolder::FromRenderProcessHost(
25    content::RenderProcessHost* render_process_host) {
26  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
27  DCHECK(render_process_host);
28  BlobHolder* existing = static_cast<BlobHolder*>(
29      render_process_host->GetUserData(&kBlobHolderUserDataKey));
30
31  if (existing)
32    return existing;
33
34  BlobHolder* new_instance = new BlobHolder(render_process_host);
35  render_process_host->SetUserData(&kBlobHolderUserDataKey, new_instance);
36  return new_instance;
37}
38
39BlobHolder::~BlobHolder() {
40  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
41}
42
43void BlobHolder::HoldBlobReference(scoped_ptr<content::BlobHandle> blob) {
44  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
45  DCHECK(!ContainsBlobHandle(blob.get()));
46
47  std::string uuid = blob->GetUUID();
48  held_blobs_.insert(make_pair(uuid, make_linked_ptr(blob.release())));
49}
50
51BlobHolder::BlobHolder(content::RenderProcessHost* render_process_host)
52    : render_process_host_(render_process_host) {
53  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
54}
55
56bool BlobHolder::ContainsBlobHandle(content::BlobHandle* handle) const {
57  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
58  for (BlobHandleMultimap::const_iterator it = held_blobs_.begin();
59       it != held_blobs_.end();
60       ++it) {
61    if (it->second.get() == handle)
62      return true;
63  }
64
65  return false;
66}
67
68void BlobHolder::DropBlobs(const std::vector<std::string>& blob_uuids) {
69  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
70  for (std::vector<std::string>::const_iterator uuid_it = blob_uuids.begin();
71       uuid_it != blob_uuids.end();
72       ++uuid_it) {
73    BlobHandleMultimap::iterator it = held_blobs_.find(*uuid_it);
74
75    if (it != held_blobs_.end()) {
76      held_blobs_.erase(it);
77    } else {
78      DLOG(ERROR) << "Tried to release a Blob we don't have ownership to."
79                  << "UUID: " << *uuid_it;
80      render_process_host_->ReceivedBadMessage();
81    }
82  }
83}
84
85}  // namespace extensions
86