cc: Make a FakeResourceProvider and use it in tests to construct.
[chromium-blink-merge.git] / content / browser / webui / url_data_manager_backend.cc
blob1c171c2645e555d66c2511c5f9b136543036e14e
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/memory/ref_counted.h"
16 #include "base/memory/ref_counted_memory.h"
17 #include "base/memory/weak_ptr.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/profiler/scoped_tracker.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/trace_event/trace_event.h"
23 #include "content/browser/appcache/view_appcache_internals_job.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 base::SupportsWeakPtr<URLRequestChromeJob> {
115 public:
116 // |is_incognito| set when job is generated from an incognito profile.
117 URLRequestChromeJob(net::URLRequest* request,
118 net::NetworkDelegate* network_delegate,
119 URLDataManagerBackend* backend,
120 bool is_incognito);
122 // net::URLRequestJob implementation.
123 void Start() override;
124 void Kill() override;
125 bool ReadRawData(net::IOBuffer* buf, int buf_size, int* bytes_read) override;
126 bool GetMimeType(std::string* mime_type) const override;
127 int GetResponseCode() const override;
128 void GetResponseInfo(net::HttpResponseInfo* info) override;
130 // Used to notify that the requested data's |mime_type| is ready.
131 void MimeTypeAvailable(const std::string& mime_type);
133 // Called by ChromeURLDataManager to notify us that the data blob is ready
134 // for us.
135 void DataAvailable(base::RefCountedMemory* bytes);
137 void set_mime_type(const std::string& mime_type) {
138 mime_type_ = mime_type;
141 void set_allow_caching(bool allow_caching) {
142 allow_caching_ = allow_caching;
145 void set_add_content_security_policy(bool add_content_security_policy) {
146 add_content_security_policy_ = add_content_security_policy;
149 void set_content_security_policy_object_source(
150 const std::string& data) {
151 content_security_policy_object_source_ = data;
154 void set_content_security_policy_frame_source(
155 const std::string& data) {
156 content_security_policy_frame_source_ = data;
159 void set_deny_xframe_options(bool deny_xframe_options) {
160 deny_xframe_options_ = deny_xframe_options;
163 void set_send_content_type_header(bool send_content_type_header) {
164 send_content_type_header_ = send_content_type_header;
167 void set_access_control_allow_origin(const std::string& value) {
168 access_control_allow_origin_ = value;
171 // Returns true when job was generated from an incognito profile.
172 bool is_incognito() const {
173 return is_incognito_;
176 private:
177 ~URLRequestChromeJob() override;
179 // Helper for Start(), to let us start asynchronously.
180 // (This pattern is shared by most net::URLRequestJob implementations.)
181 void StartAsync(bool allowed);
183 // Called on the UI thread to check if this request is allowed.
184 static void CheckStoragePartitionMatches(
185 int render_process_id,
186 const GURL& url,
187 const base::WeakPtr<URLRequestChromeJob>& job);
189 // Do the actual copy from data_ (the data we're serving) into |buf|.
190 // Separate from ReadRawData so we can handle async I/O.
191 void CompleteRead(net::IOBuffer* buf, int buf_size, int* bytes_read);
193 // The actual data we're serving. NULL until it's been fetched.
194 scoped_refptr<base::RefCountedMemory> data_;
195 // The current offset into the data that we're handing off to our
196 // callers via the Read interfaces.
197 int data_offset_;
199 // For async reads, we keep around a pointer to the buffer that
200 // we're reading into.
201 scoped_refptr<net::IOBuffer> pending_buf_;
202 int pending_buf_size_;
203 std::string mime_type_;
205 // If true, set a header in the response to prevent it from being cached.
206 bool allow_caching_;
208 // If true, set the Content Security Policy (CSP) header.
209 bool add_content_security_policy_;
211 // These are used with the CSP.
212 std::string content_security_policy_object_source_;
213 std::string content_security_policy_frame_source_;
215 // If true, sets the "X-Frame-Options: DENY" header.
216 bool deny_xframe_options_;
218 // If true, sets the "Content-Type: <mime-type>" header.
219 bool send_content_type_header_;
221 // If not empty, "Access-Control-Allow-Origin:" is set to the value of this
222 // string.
223 std::string access_control_allow_origin_;
225 // True when job is generated from an incognito profile.
226 const bool is_incognito_;
228 // The backend is owned by net::URLRequestContext and always outlives us.
229 URLDataManagerBackend* backend_;
231 base::WeakPtrFactory<URLRequestChromeJob> weak_factory_;
233 DISALLOW_COPY_AND_ASSIGN(URLRequestChromeJob);
236 URLRequestChromeJob::URLRequestChromeJob(net::URLRequest* request,
237 net::NetworkDelegate* network_delegate,
238 URLDataManagerBackend* backend,
239 bool is_incognito)
240 : net::URLRequestJob(request, network_delegate),
241 data_offset_(0),
242 pending_buf_size_(0),
243 allow_caching_(true),
244 add_content_security_policy_(true),
245 content_security_policy_object_source_("object-src 'none';"),
246 content_security_policy_frame_source_("frame-src 'none';"),
247 deny_xframe_options_(true),
248 send_content_type_header_(false),
249 is_incognito_(is_incognito),
250 backend_(backend),
251 weak_factory_(this) {
252 DCHECK(backend);
255 URLRequestChromeJob::~URLRequestChromeJob() {
256 CHECK(!backend_->HasPendingJob(this));
259 void URLRequestChromeJob::Start() {
260 int render_process_id, unused;
261 bool is_renderer_request = ResourceRequestInfo::GetRenderFrameForRequest(
262 request_, &render_process_id, &unused);
263 if (!is_renderer_request)
264 render_process_id = kNoRenderProcessId;
265 BrowserThread::PostTask(
266 BrowserThread::UI,
267 FROM_HERE,
268 base::Bind(&URLRequestChromeJob::CheckStoragePartitionMatches,
269 render_process_id, request_->url(), AsWeakPtr()));
270 TRACE_EVENT_ASYNC_BEGIN1("browser", "DataManager:Request", this, "URL",
271 request_->url().possibly_invalid_spec());
274 void URLRequestChromeJob::Kill() {
275 backend_->RemoveRequest(this);
278 bool URLRequestChromeJob::GetMimeType(std::string* mime_type) const {
279 *mime_type = mime_type_;
280 return !mime_type_.empty();
283 int URLRequestChromeJob::GetResponseCode() const {
284 return net::HTTP_OK;
287 void URLRequestChromeJob::GetResponseInfo(net::HttpResponseInfo* info) {
288 DCHECK(!info->headers.get());
289 // Set the headers so that requests serviced by ChromeURLDataManager return a
290 // status code of 200. Without this they return a 0, which makes the status
291 // indistiguishable from other error types. Instant relies on getting a 200.
292 info->headers = new net::HttpResponseHeaders("HTTP/1.1 200 OK");
294 // Determine the least-privileged content security policy header, if any,
295 // that is compatible with a given WebUI URL, and append it to the existing
296 // response headers.
297 if (add_content_security_policy_) {
298 std::string base = kChromeURLContentSecurityPolicyHeaderBase;
299 base.append(content_security_policy_object_source_);
300 base.append(content_security_policy_frame_source_);
301 info->headers->AddHeader(base);
304 if (deny_xframe_options_)
305 info->headers->AddHeader(kChromeURLXFrameOptionsHeader);
307 if (!allow_caching_)
308 info->headers->AddHeader("Cache-Control: no-cache");
310 if (send_content_type_header_ && !mime_type_.empty()) {
311 std::string content_type =
312 base::StringPrintf("%s:%s", net::HttpRequestHeaders::kContentType,
313 mime_type_.c_str());
314 info->headers->AddHeader(content_type);
317 if (!access_control_allow_origin_.empty()) {
318 info->headers->AddHeader("Access-Control-Allow-Origin: " +
319 access_control_allow_origin_);
320 info->headers->AddHeader("Vary: Origin");
324 void URLRequestChromeJob::MimeTypeAvailable(const std::string& mime_type) {
325 set_mime_type(mime_type);
326 NotifyHeadersComplete();
329 void URLRequestChromeJob::DataAvailable(base::RefCountedMemory* bytes) {
330 TRACE_EVENT_ASYNC_END0("browser", "DataManager:Request", this);
331 if (bytes) {
332 // The request completed, and we have all the data.
333 // Clear any IO pending status.
334 SetStatus(net::URLRequestStatus());
336 data_ = bytes;
337 int bytes_read;
338 if (pending_buf_.get()) {
339 CHECK(pending_buf_->data());
340 CompleteRead(pending_buf_.get(), pending_buf_size_, &bytes_read);
341 pending_buf_ = NULL;
342 NotifyReadComplete(bytes_read);
344 } else {
345 // The request failed.
346 NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED,
347 net::ERR_FAILED));
351 bool URLRequestChromeJob::ReadRawData(net::IOBuffer* buf, int buf_size,
352 int* bytes_read) {
353 if (!data_.get()) {
354 SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0));
355 DCHECK(!pending_buf_.get());
356 CHECK(buf->data());
357 pending_buf_ = buf;
358 pending_buf_size_ = buf_size;
359 return false; // Tell the caller we're still waiting for data.
362 // Otherwise, the data is available.
363 CompleteRead(buf, buf_size, bytes_read);
364 return true;
367 void URLRequestChromeJob::CompleteRead(net::IOBuffer* buf, int buf_size,
368 int* bytes_read) {
369 int remaining = static_cast<int>(data_->size()) - data_offset_;
370 if (buf_size > remaining)
371 buf_size = remaining;
372 if (buf_size > 0) {
373 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455423 is
374 // fixed.
375 tracked_objects::ScopedTracker tracking_profile(
376 FROM_HERE_WITH_EXPLICIT_FUNCTION(
377 "455423 URLRequestChromeJob::CompleteRead memcpy"));
378 memcpy(buf->data(), data_->front() + data_offset_, buf_size);
379 data_offset_ += buf_size;
381 *bytes_read = buf_size;
384 void URLRequestChromeJob::CheckStoragePartitionMatches(
385 int render_process_id,
386 const GURL& url,
387 const base::WeakPtr<URLRequestChromeJob>& job) {
388 // The embedder could put some webui pages in separate storage partition.
389 // RenderProcessHostImpl::IsSuitableHost would guard against top level pages
390 // being in the same process. We do an extra check to guard against an
391 // exploited renderer pretending to add them as a subframe. We skip this check
392 // for resources.
393 bool allowed = false;
394 std::vector<std::string> hosts;
395 GetContentClient()->
396 browser()->GetAdditionalWebUIHostsToIgnoreParititionCheck(&hosts);
397 if (url.SchemeIs(kChromeUIScheme) &&
398 (url.SchemeIs(kChromeUIScheme) ||
399 std::find(hosts.begin(), hosts.end(), url.host()) != hosts.end())) {
400 allowed = true;
401 } else if (render_process_id == kNoRenderProcessId) {
402 // Request was not issued by renderer.
403 allowed = true;
404 } else {
405 RenderProcessHost* process = RenderProcessHost::FromID(render_process_id);
406 if (process) {
407 StoragePartition* partition = BrowserContext::GetStoragePartitionForSite(
408 process->GetBrowserContext(), url);
409 allowed = partition == process->GetStoragePartition();
413 BrowserThread::PostTask(
414 BrowserThread::IO,
415 FROM_HERE,
416 base::Bind(&URLRequestChromeJob::StartAsync, job, allowed));
419 void URLRequestChromeJob::StartAsync(bool allowed) {
420 if (!request_)
421 return;
423 if (!allowed || !backend_->StartRequest(request_, this)) {
424 NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED,
425 net::ERR_INVALID_URL));
429 namespace {
431 // Gets mime type for data that is available from |source| by |path|.
432 // After that, notifies |job| that mime type is available. This method
433 // should be called on the UI thread, but notification is performed on
434 // the IO thread.
435 void GetMimeTypeOnUI(URLDataSourceImpl* source,
436 const std::string& path,
437 const base::WeakPtr<URLRequestChromeJob>& job) {
438 DCHECK_CURRENTLY_ON(BrowserThread::UI);
439 std::string mime_type = source->source()->GetMimeType(path);
440 BrowserThread::PostTask(
441 BrowserThread::IO, FROM_HERE,
442 base::Bind(&URLRequestChromeJob::MimeTypeAvailable, job, mime_type));
445 } // namespace
447 namespace {
449 class ChromeProtocolHandler
450 : public net::URLRequestJobFactory::ProtocolHandler {
451 public:
452 // |is_incognito| should be set for incognito profiles.
453 ChromeProtocolHandler(ResourceContext* resource_context,
454 bool is_incognito,
455 AppCacheServiceImpl* appcache_service,
456 ChromeBlobStorageContext* blob_storage_context)
457 : resource_context_(resource_context),
458 is_incognito_(is_incognito),
459 appcache_service_(appcache_service),
460 blob_storage_context_(blob_storage_context) {}
461 ~ChromeProtocolHandler() override {}
463 net::URLRequestJob* MaybeCreateJob(
464 net::URLRequest* request,
465 net::NetworkDelegate* network_delegate) const override {
466 DCHECK(request);
468 // Check for chrome://view-http-cache/*, which uses its own job type.
469 if (ViewHttpCacheJobFactory::IsSupportedURL(request->url()))
470 return ViewHttpCacheJobFactory::CreateJobForRequest(request,
471 network_delegate);
473 // Next check for chrome://appcache-internals/, which uses its own job type.
474 if (request->url().SchemeIs(kChromeUIScheme) &&
475 request->url().host() == kChromeUIAppCacheInternalsHost) {
476 return ViewAppCacheInternalsJobFactory::CreateJobForRequest(
477 request, network_delegate, appcache_service_);
480 // Next check for chrome://blob-internals/, which uses its own job type.
481 if (ViewBlobInternalsJobFactory::IsSupportedURL(request->url())) {
482 return ViewBlobInternalsJobFactory::CreateJobForRequest(
483 request, network_delegate, blob_storage_context_->context());
486 #if defined(USE_TCMALLOC)
487 // Next check for chrome://tcmalloc/, which uses its own job type.
488 if (request->url().SchemeIs(kChromeUIScheme) &&
489 request->url().host() == kChromeUITcmallocHost) {
490 return new TcmallocInternalsRequestJob(request, network_delegate);
492 #endif
494 // Next check for chrome://histograms/, which uses its own job type.
495 if (request->url().SchemeIs(kChromeUIScheme) &&
496 request->url().host() == kChromeUIHistogramHost) {
497 return new HistogramInternalsRequestJob(request, network_delegate);
500 // Fall back to using a custom handler
501 return new URLRequestChromeJob(
502 request, network_delegate,
503 GetURLDataManagerForResourceContext(resource_context_), is_incognito_);
506 bool IsSafeRedirectTarget(const GURL& location) const override {
507 return false;
510 private:
511 // These members are owned by ProfileIOData, which owns this ProtocolHandler.
512 content::ResourceContext* const resource_context_;
514 // True when generated from an incognito profile.
515 const bool is_incognito_;
516 AppCacheServiceImpl* appcache_service_;
517 ChromeBlobStorageContext* blob_storage_context_;
519 DISALLOW_COPY_AND_ASSIGN(ChromeProtocolHandler);
522 } // namespace
524 URLDataManagerBackend::URLDataManagerBackend()
525 : next_request_id_(0) {
526 URLDataSource* shared_source = new SharedResourcesDataSource();
527 URLDataSourceImpl* source_impl =
528 new URLDataSourceImpl(shared_source->GetSource(), shared_source);
529 AddDataSource(source_impl);
532 URLDataManagerBackend::~URLDataManagerBackend() {
533 for (DataSourceMap::iterator i = data_sources_.begin();
534 i != data_sources_.end(); ++i) {
535 i->second->backend_ = NULL;
537 data_sources_.clear();
540 // static
541 net::URLRequestJobFactory::ProtocolHandler*
542 URLDataManagerBackend::CreateProtocolHandler(
543 content::ResourceContext* resource_context,
544 bool is_incognito,
545 AppCacheServiceImpl* appcache_service,
546 ChromeBlobStorageContext* blob_storage_context) {
547 DCHECK(resource_context);
548 return new ChromeProtocolHandler(
549 resource_context, is_incognito, appcache_service, blob_storage_context);
552 void URLDataManagerBackend::AddDataSource(
553 URLDataSourceImpl* source) {
554 DCHECK_CURRENTLY_ON(BrowserThread::IO);
555 DataSourceMap::iterator i = data_sources_.find(source->source_name());
556 if (i != data_sources_.end()) {
557 if (!source->source()->ShouldReplaceExistingSource())
558 return;
559 i->second->backend_ = NULL;
561 data_sources_[source->source_name()] = source;
562 source->backend_ = this;
565 bool URLDataManagerBackend::HasPendingJob(
566 URLRequestChromeJob* job) const {
567 for (PendingRequestMap::const_iterator i = pending_requests_.begin();
568 i != pending_requests_.end(); ++i) {
569 if (i->second == job)
570 return true;
572 return false;
575 bool URLDataManagerBackend::StartRequest(const net::URLRequest* request,
576 URLRequestChromeJob* job) {
577 if (!CheckURLIsValid(request->url()))
578 return false;
580 URLDataSourceImpl* source = GetDataSourceFromURL(request->url());
581 if (!source)
582 return false;
584 if (!source->source()->ShouldServiceRequest(request))
585 return false;
587 std::string path;
588 URLToRequestPath(request->url(), &path);
589 source->source()->WillServiceRequest(request, &path);
591 // Save this request so we know where to send the data.
592 RequestID request_id = next_request_id_++;
593 pending_requests_.insert(std::make_pair(request_id, job));
595 job->set_allow_caching(source->source()->AllowCaching());
596 job->set_add_content_security_policy(
597 source->source()->ShouldAddContentSecurityPolicy());
598 job->set_content_security_policy_object_source(
599 source->source()->GetContentSecurityPolicyObjectSrc());
600 job->set_content_security_policy_frame_source(
601 source->source()->GetContentSecurityPolicyFrameSrc());
602 job->set_deny_xframe_options(
603 source->source()->ShouldDenyXFrameOptions());
604 job->set_send_content_type_header(
605 source->source()->ShouldServeMimeTypeAsContentTypeHeader());
607 std::string origin = GetOriginHeaderValue(request);
608 if (!origin.empty()) {
609 std::string header =
610 source->source()->GetAccessControlAllowOriginForOrigin(origin);
611 DCHECK(header.empty() || header == origin || header == "*" ||
612 header == "null");
613 job->set_access_control_allow_origin(header);
616 // Look up additional request info to pass down.
617 int render_process_id = -1;
618 int render_frame_id = -1;
619 ResourceRequestInfo::GetRenderFrameForRequest(request,
620 &render_process_id,
621 &render_frame_id);
623 // Forward along the request to the data source.
624 base::MessageLoop* target_message_loop =
625 source->source()->MessageLoopForRequestPath(path);
626 if (!target_message_loop) {
627 job->MimeTypeAvailable(source->source()->GetMimeType(path));
628 // Eliminate potentially dangling pointer to avoid future use.
629 job = NULL;
631 // The DataSource is agnostic to which thread StartDataRequest is called
632 // on for this path. Call directly into it from this thread, the IO
633 // thread.
634 source->source()->StartDataRequest(
635 path, render_process_id, render_frame_id,
636 base::Bind(&URLDataSourceImpl::SendResponse, source, request_id));
637 } else {
638 // URLRequestChromeJob should receive mime type before data. This
639 // is guaranteed because request for mime type is placed in the
640 // message loop before request for data. And correspondingly their
641 // replies are put on the IO thread in the same order.
642 target_message_loop->PostTask(
643 FROM_HERE,
644 base::Bind(&GetMimeTypeOnUI,
645 scoped_refptr<URLDataSourceImpl>(source),
646 path, job->AsWeakPtr()));
648 // The DataSource wants StartDataRequest to be called on a specific thread,
649 // usually the UI thread, for this path.
650 target_message_loop->PostTask(
651 FROM_HERE,
652 base::Bind(&URLDataManagerBackend::CallStartRequest,
653 make_scoped_refptr(source), path, render_process_id,
654 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