Make USB permissions work in the new permission message system
[chromium-blink-merge.git] / content / browser / webui / url_data_manager_backend.cc
blob3bfb0e70bcd24e059427d7f1a8f4314c86a8cff4
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.
5 #include "content/browser/webui/url_data_manager_backend.h"
7 #include <set>
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/compiler_specific.h"
13 #include "base/debug/alias.h"
14 #include "base/lazy_instance.h"
15 #include "base/location.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/ref_counted_memory.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/profiler/scoped_tracker.h"
20 #include "base/single_thread_task_runner.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/trace_event/trace_event.h"
24 #include "content/browser/fileapi/chrome_blob_storage_context.h"
25 #include "content/browser/histogram_internals_request_job.h"
26 #include "content/browser/net/view_blob_internals_job_factory.h"
27 #include "content/browser/net/view_http_cache_job_factory.h"
28 #include "content/browser/resource_context_impl.h"
29 #include "content/browser/tcmalloc_internals_request_job.h"
30 #include "content/browser/webui/shared_resources_data_source.h"
31 #include "content/browser/webui/url_data_source_impl.h"
32 #include "content/public/browser/browser_context.h"
33 #include "content/public/browser/browser_thread.h"
34 #include "content/public/browser/content_browser_client.h"
35 #include "content/public/browser/render_process_host.h"
36 #include "content/public/browser/resource_request_info.h"
37 #include "content/public/common/url_constants.h"
38 #include "net/base/io_buffer.h"
39 #include "net/base/net_errors.h"
40 #include "net/http/http_response_headers.h"
41 #include "net/http/http_status_code.h"
42 #include "net/url_request/url_request.h"
43 #include "net/url_request/url_request_context.h"
44 #include "net/url_request/url_request_job.h"
45 #include "net/url_request/url_request_job_factory.h"
46 #include "url/url_util.h"
48 namespace content {
50 namespace {
52 // TODO(tsepez) remove unsafe-eval when bidichecker_packaged.js fixed.
53 const char kChromeURLContentSecurityPolicyHeaderBase[] =
54 "Content-Security-Policy: script-src chrome://resources "
55 "'self' 'unsafe-eval'; ";
57 const char kChromeURLXFrameOptionsHeader[] = "X-Frame-Options: DENY";
59 const int kNoRenderProcessId = -1;
61 bool SchemeIsInSchemes(const std::string& scheme,
62 const std::vector<std::string>& schemes) {
63 return std::find(schemes.begin(), schemes.end(), scheme) != schemes.end();
66 // Returns whether |url| passes some sanity checks and is a valid GURL.
67 bool CheckURLIsValid(const GURL& url) {
68 std::vector<std::string> additional_schemes;
69 DCHECK(url.SchemeIs(kChromeDevToolsScheme) || url.SchemeIs(kChromeUIScheme) ||
70 (GetContentClient()->browser()->GetAdditionalWebUISchemes(
71 &additional_schemes),
72 SchemeIsInSchemes(url.scheme(), additional_schemes)));
74 if (!url.is_valid()) {
75 NOTREACHED();
76 return false;
79 return true;
82 // Parse |url| to get the path which will be used to resolve the request. The
83 // path is the remaining portion after the scheme and hostname.
84 void URLToRequestPath(const GURL& url, std::string* path) {
85 const std::string& spec = url.possibly_invalid_spec();
86 const url::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
87 // + 1 to skip the slash at the beginning of the path.
88 int offset = parsed.CountCharactersBefore(url::Parsed::PATH, false) + 1;
90 if (offset < static_cast<int>(spec.size()))
91 path->assign(spec.substr(offset));
94 // Returns a value of 'Origin:' header for the |request| if the header is set.
95 // Otherwise returns an empty string.
96 std::string GetOriginHeaderValue(const net::URLRequest* request) {
97 std::string result;
98 if (request->extra_request_headers().GetHeader(
99 net::HttpRequestHeaders::kOrigin, &result))
100 return result;
101 net::HttpRequestHeaders headers;
102 if (request->GetFullRequestHeaders(&headers))
103 headers.GetHeader(net::HttpRequestHeaders::kOrigin, &result);
104 return result;
107 } // namespace
109 // URLRequestChromeJob is a net::URLRequestJob that manages running
110 // chrome-internal resource requests asynchronously.
111 // It hands off URL requests to ChromeURLDataManager, which asynchronously
112 // calls back once the data is available.
113 class URLRequestChromeJob : public net::URLRequestJob {
114 public:
115 // |is_incognito| set when job is generated from an incognito profile.
116 URLRequestChromeJob(net::URLRequest* request,
117 net::NetworkDelegate* network_delegate,
118 URLDataManagerBackend* backend,
119 bool is_incognito);
121 // net::URLRequestJob implementation.
122 void Start() override;
123 void Kill() override;
124 bool ReadRawData(net::IOBuffer* buf, int buf_size, int* bytes_read) override;
125 bool GetMimeType(std::string* mime_type) const override;
126 int GetResponseCode() const override;
127 void GetResponseInfo(net::HttpResponseInfo* info) override;
129 // Used to notify that the requested data's |mime_type| is ready.
130 void MimeTypeAvailable(const std::string& mime_type);
132 // Called by ChromeURLDataManager to notify us that the data blob is ready
133 // for us.
134 void DataAvailable(base::RefCountedMemory* bytes);
136 // Returns a weak pointer to the job.
137 base::WeakPtr<URLRequestChromeJob> AsWeakPtr();
139 void set_mime_type(const std::string& mime_type) {
140 mime_type_ = mime_type;
143 void set_allow_caching(bool allow_caching) {
144 allow_caching_ = allow_caching;
147 void set_add_content_security_policy(bool add_content_security_policy) {
148 add_content_security_policy_ = add_content_security_policy;
151 void set_content_security_policy_object_source(
152 const std::string& data) {
153 content_security_policy_object_source_ = data;
156 void set_content_security_policy_frame_source(
157 const std::string& data) {
158 content_security_policy_frame_source_ = data;
161 void set_deny_xframe_options(bool deny_xframe_options) {
162 deny_xframe_options_ = deny_xframe_options;
165 void set_send_content_type_header(bool send_content_type_header) {
166 send_content_type_header_ = send_content_type_header;
169 void set_access_control_allow_origin(const std::string& value) {
170 access_control_allow_origin_ = value;
173 // Returns true when job was generated from an incognito profile.
174 bool is_incognito() const {
175 return is_incognito_;
178 private:
179 ~URLRequestChromeJob() override;
181 // Helper for Start(), to let us start asynchronously.
182 // (This pattern is shared by most net::URLRequestJob implementations.)
183 void StartAsync(bool allowed);
185 // Called on the UI thread to check if this request is allowed.
186 static void CheckStoragePartitionMatches(
187 int render_process_id,
188 const GURL& url,
189 const base::WeakPtr<URLRequestChromeJob>& job);
191 // Do the actual copy from data_ (the data we're serving) into |buf|.
192 // Separate from ReadRawData so we can handle async I/O.
193 void CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read);
195 // The actual data we're serving. NULL until it's been fetched.
196 scoped_refptr<base::RefCountedMemory> data_;
197 // The current offset into the data that we're handing off to our
198 // callers via the Read interfaces.
199 int data_offset_;
201 // For async reads, we keep around a pointer to the buffer that
202 // we're reading into.
203 scoped_refptr<net::IOBuffer> pending_buf_;
204 int pending_buf_size_;
205 std::string mime_type_;
207 // If true, set a header in the response to prevent it from being cached.
208 bool allow_caching_;
210 // If true, set the Content Security Policy (CSP) header.
211 bool add_content_security_policy_;
213 // These are used with the CSP.
214 std::string content_security_policy_object_source_;
215 std::string content_security_policy_frame_source_;
217 // If true, sets the "X-Frame-Options: DENY" header.
218 bool deny_xframe_options_;
220 // If true, sets the "Content-Type: <mime-type>" header.
221 bool send_content_type_header_;
223 // If not empty, "Access-Control-Allow-Origin:" is set to the value of this
224 // string.
225 std::string access_control_allow_origin_;
227 // True when job is generated from an incognito profile.
228 const bool is_incognito_;
230 // The backend is owned by net::URLRequestContext and always outlives us.
231 URLDataManagerBackend* backend_;
233 base::WeakPtrFactory<URLRequestChromeJob> weak_factory_;
235 DISALLOW_COPY_AND_ASSIGN(URLRequestChromeJob);
238 URLRequestChromeJob::URLRequestChromeJob(net::URLRequest* request,
239 net::NetworkDelegate* network_delegate,
240 URLDataManagerBackend* backend,
241 bool is_incognito)
242 : net::URLRequestJob(request, network_delegate),
243 data_offset_(0),
244 pending_buf_size_(0),
245 allow_caching_(true),
246 add_content_security_policy_(true),
247 content_security_policy_object_source_("object-src 'none';"),
248 content_security_policy_frame_source_("frame-src 'none';"),
249 deny_xframe_options_(true),
250 send_content_type_header_(false),
251 is_incognito_(is_incognito),
252 backend_(backend),
253 weak_factory_(this) {
254 DCHECK(backend);
257 URLRequestChromeJob::~URLRequestChromeJob() {
258 CHECK(!backend_->HasPendingJob(this));
261 void URLRequestChromeJob::Start() {
262 int render_process_id, unused;
263 bool is_renderer_request = ResourceRequestInfo::GetRenderFrameForRequest(
264 request_, &render_process_id, &unused);
265 if (!is_renderer_request)
266 render_process_id = kNoRenderProcessId;
267 BrowserThread::PostTask(
268 BrowserThread::UI,
269 FROM_HERE,
270 base::Bind(&URLRequestChromeJob::CheckStoragePartitionMatches,
271 render_process_id, request_->url(),
272 weak_factory_.GetWeakPtr()));
273 TRACE_EVENT_ASYNC_BEGIN1("browser", "DataManager:Request", this, "URL",
274 request_->url().possibly_invalid_spec());
277 void URLRequestChromeJob::Kill() {
278 weak_factory_.InvalidateWeakPtrs();
279 backend_->RemoveRequest(this);
280 URLRequestJob::Kill();
283 bool URLRequestChromeJob::GetMimeType(std::string* mime_type) const {
284 *mime_type = mime_type_;
285 return !mime_type_.empty();
288 int URLRequestChromeJob::GetResponseCode() const {
289 return net::HTTP_OK;
292 void URLRequestChromeJob::GetResponseInfo(net::HttpResponseInfo* info) {
293 DCHECK(!info->headers.get());
294 // Set the headers so that requests serviced by ChromeURLDataManager return a
295 // status code of 200. Without this they return a 0, which makes the status
296 // indistiguishable from other error types. Instant relies on getting a 200.
297 info->headers = new net::HttpResponseHeaders("HTTP/1.1 200 OK");
299 // Determine the least-privileged content security policy header, if any,
300 // that is compatible with a given WebUI URL, and append it to the existing
301 // response headers.
302 if (add_content_security_policy_) {
303 std::string base = kChromeURLContentSecurityPolicyHeaderBase;
304 base.append(content_security_policy_object_source_);
305 base.append(content_security_policy_frame_source_);
306 info->headers->AddHeader(base);
309 if (deny_xframe_options_)
310 info->headers->AddHeader(kChromeURLXFrameOptionsHeader);
312 if (!allow_caching_)
313 info->headers->AddHeader("Cache-Control: no-cache");
315 if (send_content_type_header_ && !mime_type_.empty()) {
316 std::string content_type =
317 base::StringPrintf("%s:%s", net::HttpRequestHeaders::kContentType,
318 mime_type_.c_str());
319 info->headers->AddHeader(content_type);
322 if (!access_control_allow_origin_.empty()) {
323 info->headers->AddHeader("Access-Control-Allow-Origin: " +
324 access_control_allow_origin_);
325 info->headers->AddHeader("Vary: Origin");
329 void URLRequestChromeJob::MimeTypeAvailable(const std::string& mime_type) {
330 set_mime_type(mime_type);
331 NotifyHeadersComplete();
334 void URLRequestChromeJob::DataAvailable(base::RefCountedMemory* bytes) {
335 TRACE_EVENT_ASYNC_END0("browser", "DataManager:Request", this);
336 if (bytes) {
337 // The request completed, and we have all the data.
338 // Clear any IO pending status.
339 SetStatus(net::URLRequestStatus());
341 data_ = bytes;
342 int bytes_read;
343 if (pending_buf_.get()) {
344 CHECK(pending_buf_->data());
345 CompleteRead(pending_buf_.get(), pending_buf_size_, &bytes_read);
346 pending_buf_ = NULL;
347 NotifyReadComplete(bytes_read);
349 } else {
350 // The request failed.
351 NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED,
352 net::ERR_FAILED));
356 base::WeakPtr<URLRequestChromeJob> URLRequestChromeJob::AsWeakPtr() {
357 return weak_factory_.GetWeakPtr();
360 bool URLRequestChromeJob::ReadRawData(net::IOBuffer* buf, int buf_size,
361 int* bytes_read) {
362 if (!data_.get()) {
363 SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0));
364 DCHECK(!pending_buf_.get());
365 CHECK(buf->data());
366 pending_buf_ = buf;
367 pending_buf_size_ = buf_size;
368 return false; // Tell the caller we're still waiting for data.
371 // Otherwise, the data is available.
372 CompleteRead(buf, buf_size, bytes_read);
373 return true;
376 void URLRequestChromeJob::CompleteRead(net::IOBuffer* buf, int buf_size,
377 int* bytes_read) {
378 int remaining = static_cast<int>(data_->size()) - data_offset_;
379 if (buf_size > remaining)
380 buf_size = remaining;
381 if (buf_size > 0) {
382 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455423 is
383 // fixed.
384 tracked_objects::ScopedTracker tracking_profile(
385 FROM_HERE_WITH_EXPLICIT_FUNCTION(
386 "455423 URLRequestChromeJob::CompleteRead memcpy"));
387 memcpy(buf->data(), data_->front() + data_offset_, buf_size);
388 data_offset_ += buf_size;
390 *bytes_read = buf_size;
393 void URLRequestChromeJob::CheckStoragePartitionMatches(
394 int render_process_id,
395 const GURL& url,
396 const base::WeakPtr<URLRequestChromeJob>& job) {
397 // The embedder could put some webui pages in separate storage partition.
398 // RenderProcessHostImpl::IsSuitableHost would guard against top level pages
399 // being in the same process. We do an extra check to guard against an
400 // exploited renderer pretending to add them as a subframe. We skip this check
401 // for resources.
402 bool allowed = false;
403 std::vector<std::string> hosts;
404 GetContentClient()->
405 browser()->GetAdditionalWebUIHostsToIgnoreParititionCheck(&hosts);
406 if (url.SchemeIs(kChromeUIScheme) &&
407 (url.SchemeIs(kChromeUIScheme) ||
408 std::find(hosts.begin(), hosts.end(), url.host()) != hosts.end())) {
409 allowed = true;
410 } else if (render_process_id == kNoRenderProcessId) {
411 // Request was not issued by renderer.
412 allowed = true;
413 } else {
414 RenderProcessHost* process = RenderProcessHost::FromID(render_process_id);
415 if (process) {
416 StoragePartition* partition = BrowserContext::GetStoragePartitionForSite(
417 process->GetBrowserContext(), url);
418 allowed = partition == process->GetStoragePartition();
422 BrowserThread::PostTask(
423 BrowserThread::IO,
424 FROM_HERE,
425 base::Bind(&URLRequestChromeJob::StartAsync, job, allowed));
428 void URLRequestChromeJob::StartAsync(bool allowed) {
429 if (!request_)
430 return;
432 if (!allowed || !backend_->StartRequest(request_, this)) {
433 NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED,
434 net::ERR_INVALID_URL));
438 namespace {
440 // Gets mime type for data that is available from |source| by |path|.
441 // After that, notifies |job| that mime type is available. This method
442 // should be called on the UI thread, but notification is performed on
443 // the IO thread.
444 void GetMimeTypeOnUI(URLDataSourceImpl* source,
445 const std::string& path,
446 const base::WeakPtr<URLRequestChromeJob>& job) {
447 DCHECK_CURRENTLY_ON(BrowserThread::UI);
448 std::string mime_type = source->source()->GetMimeType(path);
449 BrowserThread::PostTask(
450 BrowserThread::IO, FROM_HERE,
451 base::Bind(&URLRequestChromeJob::MimeTypeAvailable, job, mime_type));
454 } // namespace
456 namespace {
458 class ChromeProtocolHandler
459 : public net::URLRequestJobFactory::ProtocolHandler {
460 public:
461 // |is_incognito| should be set for incognito profiles.
462 ChromeProtocolHandler(ResourceContext* resource_context,
463 bool is_incognito,
464 AppCacheServiceImpl* appcache_service,
465 ChromeBlobStorageContext* blob_storage_context)
466 : resource_context_(resource_context),
467 is_incognito_(is_incognito),
468 appcache_service_(appcache_service),
469 blob_storage_context_(blob_storage_context) {}
470 ~ChromeProtocolHandler() override {}
472 net::URLRequestJob* MaybeCreateJob(
473 net::URLRequest* request,
474 net::NetworkDelegate* network_delegate) const override {
475 DCHECK(request);
477 // Check for chrome://view-http-cache/*, which uses its own job type.
478 if (ViewHttpCacheJobFactory::IsSupportedURL(request->url()))
479 return ViewHttpCacheJobFactory::CreateJobForRequest(request,
480 network_delegate);
482 // Next check for chrome://blob-internals/, which uses its own job type.
483 if (ViewBlobInternalsJobFactory::IsSupportedURL(request->url())) {
484 return ViewBlobInternalsJobFactory::CreateJobForRequest(
485 request, network_delegate, blob_storage_context_->context());
488 #if defined(USE_TCMALLOC)
489 // Next check for chrome://tcmalloc/, which uses its own job type.
490 if (request->url().SchemeIs(kChromeUIScheme) &&
491 request->url().host() == kChromeUITcmallocHost) {
492 return new TcmallocInternalsRequestJob(request, network_delegate);
494 #endif
496 // Next check for chrome://histograms/, which uses its own job type.
497 if (request->url().SchemeIs(kChromeUIScheme) &&
498 request->url().host() == kChromeUIHistogramHost) {
499 return new HistogramInternalsRequestJob(request, network_delegate);
502 // Fall back to using a custom handler
503 return new URLRequestChromeJob(
504 request, network_delegate,
505 GetURLDataManagerForResourceContext(resource_context_), is_incognito_);
508 bool IsSafeRedirectTarget(const GURL& location) const override {
509 return false;
512 private:
513 // These members are owned by ProfileIOData, which owns this ProtocolHandler.
514 content::ResourceContext* const resource_context_;
516 // True when generated from an incognito profile.
517 const bool is_incognito_;
518 AppCacheServiceImpl* appcache_service_;
519 ChromeBlobStorageContext* blob_storage_context_;
521 DISALLOW_COPY_AND_ASSIGN(ChromeProtocolHandler);
524 } // namespace
526 URLDataManagerBackend::URLDataManagerBackend()
527 : next_request_id_(0) {
528 URLDataSource* shared_source = new SharedResourcesDataSource();
529 URLDataSourceImpl* source_impl =
530 new URLDataSourceImpl(shared_source->GetSource(), shared_source);
531 AddDataSource(source_impl);
534 URLDataManagerBackend::~URLDataManagerBackend() {
535 for (DataSourceMap::iterator i = data_sources_.begin();
536 i != data_sources_.end(); ++i) {
537 i->second->backend_ = NULL;
539 data_sources_.clear();
542 // static
543 net::URLRequestJobFactory::ProtocolHandler*
544 URLDataManagerBackend::CreateProtocolHandler(
545 content::ResourceContext* resource_context,
546 bool is_incognito,
547 AppCacheServiceImpl* appcache_service,
548 ChromeBlobStorageContext* blob_storage_context) {
549 DCHECK(resource_context);
550 return new ChromeProtocolHandler(
551 resource_context, is_incognito, appcache_service, blob_storage_context);
554 void URLDataManagerBackend::AddDataSource(
555 URLDataSourceImpl* source) {
556 DCHECK_CURRENTLY_ON(BrowserThread::IO);
557 DataSourceMap::iterator i = data_sources_.find(source->source_name());
558 if (i != data_sources_.end()) {
559 if (!source->source()->ShouldReplaceExistingSource())
560 return;
561 i->second->backend_ = NULL;
563 data_sources_[source->source_name()] = source;
564 source->backend_ = this;
567 bool URLDataManagerBackend::HasPendingJob(
568 URLRequestChromeJob* job) const {
569 for (PendingRequestMap::const_iterator i = pending_requests_.begin();
570 i != pending_requests_.end(); ++i) {
571 if (i->second == job)
572 return true;
574 return false;
577 bool URLDataManagerBackend::StartRequest(const net::URLRequest* request,
578 URLRequestChromeJob* job) {
579 if (!CheckURLIsValid(request->url()))
580 return false;
582 URLDataSourceImpl* source = GetDataSourceFromURL(request->url());
583 if (!source)
584 return false;
586 if (!source->source()->ShouldServiceRequest(request))
587 return false;
589 std::string path;
590 URLToRequestPath(request->url(), &path);
591 source->source()->WillServiceRequest(request, &path);
593 // Save this request so we know where to send the data.
594 RequestID request_id = next_request_id_++;
595 pending_requests_.insert(std::make_pair(request_id, job));
597 job->set_allow_caching(source->source()->AllowCaching());
598 job->set_add_content_security_policy(
599 source->source()->ShouldAddContentSecurityPolicy());
600 job->set_content_security_policy_object_source(
601 source->source()->GetContentSecurityPolicyObjectSrc());
602 job->set_content_security_policy_frame_source(
603 source->source()->GetContentSecurityPolicyFrameSrc());
604 job->set_deny_xframe_options(
605 source->source()->ShouldDenyXFrameOptions());
606 job->set_send_content_type_header(
607 source->source()->ShouldServeMimeTypeAsContentTypeHeader());
609 std::string origin = GetOriginHeaderValue(request);
610 if (!origin.empty()) {
611 std::string header =
612 source->source()->GetAccessControlAllowOriginForOrigin(origin);
613 DCHECK(header.empty() || header == origin || header == "*" ||
614 header == "null");
615 job->set_access_control_allow_origin(header);
618 // Look up additional request info to pass down.
619 int render_process_id = -1;
620 int render_frame_id = -1;
621 ResourceRequestInfo::GetRenderFrameForRequest(request,
622 &render_process_id,
623 &render_frame_id);
625 // Forward along the request to the data source.
626 base::MessageLoop* target_message_loop =
627 source->source()->MessageLoopForRequestPath(path);
628 if (!target_message_loop) {
629 job->MimeTypeAvailable(source->source()->GetMimeType(path));
630 // Eliminate potentially dangling pointer to avoid future use.
631 job = NULL;
633 // The DataSource is agnostic to which thread StartDataRequest is called
634 // on for this path. Call directly into it from this thread, the IO
635 // thread.
636 source->source()->StartDataRequest(
637 path, render_process_id, render_frame_id,
638 base::Bind(&URLDataSourceImpl::SendResponse, source, request_id));
639 } else {
640 // URLRequestChromeJob should receive mime type before data. This
641 // is guaranteed because request for mime type is placed in the
642 // message loop before request for data. And correspondingly their
643 // replies are put on the IO thread in the same order.
644 target_message_loop->task_runner()->PostTask(
645 FROM_HERE,
646 base::Bind(&GetMimeTypeOnUI, scoped_refptr<URLDataSourceImpl>(source),
647 path, job->AsWeakPtr()));
649 // The DataSource wants StartDataRequest to be called on a specific thread,
650 // usually the UI thread, for this path.
651 target_message_loop->task_runner()->PostTask(
652 FROM_HERE, base::Bind(&URLDataManagerBackend::CallStartRequest,
653 make_scoped_refptr(source), path,
654 render_process_id, render_frame_id, request_id));
656 return true;
659 URLDataSourceImpl* URLDataManagerBackend::GetDataSourceFromURL(
660 const GURL& url) {
661 // The input usually looks like: chrome://source_name/extra_bits?foo
662 // so do a lookup using the host of the URL.
663 DataSourceMap::iterator i = data_sources_.find(url.host());
664 if (i != data_sources_.end())
665 return i->second.get();
667 // No match using the host of the URL, so do a lookup using the scheme for
668 // URLs on the form source_name://extra_bits/foo .
669 i = data_sources_.find(url.scheme() + "://");
670 if (i != data_sources_.end())
671 return i->second.get();
673 // No matches found, so give up.
674 return NULL;
677 void URLDataManagerBackend::CallStartRequest(
678 scoped_refptr<URLDataSourceImpl> source,
679 const std::string& path,
680 int render_process_id,
681 int render_frame_id,
682 int request_id) {
683 if (BrowserThread::CurrentlyOn(BrowserThread::UI) &&
684 render_process_id != -1 &&
685 !RenderProcessHost::FromID(render_process_id)) {
686 // Make the request fail if its initiating renderer is no longer valid.
687 // This can happen when the IO thread posts this task just before the
688 // renderer shuts down.
689 source->SendResponse(request_id, NULL);
690 return;
692 source->source()->StartDataRequest(
693 path,
694 render_process_id,
695 render_frame_id,
696 base::Bind(&URLDataSourceImpl::SendResponse, source, request_id));
699 void URLDataManagerBackend::RemoveRequest(URLRequestChromeJob* job) {
700 // Remove the request from our list of pending requests.
701 // If/when the source sends the data that was requested, the data will just
702 // be thrown away.
703 for (PendingRequestMap::iterator i = pending_requests_.begin();
704 i != pending_requests_.end(); ++i) {
705 if (i->second == job) {
706 pending_requests_.erase(i);
707 return;
712 void URLDataManagerBackend::DataAvailable(RequestID request_id,
713 base::RefCountedMemory* bytes) {
714 // Forward this data on to the pending net::URLRequest, if it exists.
715 PendingRequestMap::iterator i = pending_requests_.find(request_id);
716 if (i != pending_requests_.end()) {
717 URLRequestChromeJob* job = i->second;
718 pending_requests_.erase(i);
719 job->DataAvailable(bytes);
723 namespace {
725 class DevToolsJobFactory
726 : public net::URLRequestJobFactory::ProtocolHandler {
727 public:
728 // |is_incognito| should be set for incognito profiles.
729 DevToolsJobFactory(content::ResourceContext* resource_context,
730 bool is_incognito);
731 ~DevToolsJobFactory() override;
733 net::URLRequestJob* MaybeCreateJob(
734 net::URLRequest* request,
735 net::NetworkDelegate* network_delegate) const override;
737 private:
738 // |resource_context_| and |network_delegate_| are owned by ProfileIOData,
739 // which owns this ProtocolHandler.
740 content::ResourceContext* const resource_context_;
742 // True when generated from an incognito profile.
743 const bool is_incognito_;
745 DISALLOW_COPY_AND_ASSIGN(DevToolsJobFactory);
748 DevToolsJobFactory::DevToolsJobFactory(
749 content::ResourceContext* resource_context,
750 bool is_incognito)
751 : resource_context_(resource_context),
752 is_incognito_(is_incognito) {
753 DCHECK(resource_context_);
756 DevToolsJobFactory::~DevToolsJobFactory() {}
758 net::URLRequestJob*
759 DevToolsJobFactory::MaybeCreateJob(
760 net::URLRequest* request, net::NetworkDelegate* network_delegate) const {
761 return new URLRequestChromeJob(
762 request, network_delegate,
763 GetURLDataManagerForResourceContext(resource_context_), is_incognito_);
766 } // namespace
768 net::URLRequestJobFactory::ProtocolHandler*
769 CreateDevToolsProtocolHandler(content::ResourceContext* resource_context,
770 bool is_incognito) {
771 return new DevToolsJobFactory(resource_context, is_incognito);
774 } // namespace content