electron/atom/browser/net/atom_network_delegate.cc

448 lines
15 KiB
C++
Raw Normal View History

2015-12-01 04:52:22 +00:00
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/net/atom_network_delegate.h"
2016-04-08 08:33:57 +00:00
#include <utility>
2017-09-12 12:17:11 +00:00
#include "atom/browser/api/atom_api_web_contents.h"
2015-12-01 04:52:22 +00:00
#include "atom/common/native_mate_converters/net_converter.h"
2015-12-11 13:02:44 +00:00
#include "base/stl_util.h"
2015-12-11 12:40:39 +00:00
#include "base/strings/string_util.h"
#include "brightray/browser/net/devtools_network_transaction.h"
2015-12-01 04:52:22 +00:00
#include "content/public/browser/browser_thread.h"
2017-09-12 12:17:11 +00:00
#include "content/public/browser/render_frame_host.h"
2015-12-01 04:52:22 +00:00
#include "net/url_request/url_request.h"
using brightray::DevToolsNetworkTransaction;
2015-12-01 04:52:22 +00:00
using content::BrowserThread;
namespace atom {
2015-12-11 12:40:39 +00:00
const char* ResourceTypeToString(content::ResourceType type) {
2015-12-03 22:24:26 +00:00
switch (type) {
case content::RESOURCE_TYPE_MAIN_FRAME:
2015-12-09 19:16:03 +00:00
return "mainFrame";
2015-12-03 22:24:26 +00:00
case content::RESOURCE_TYPE_SUB_FRAME:
2015-12-09 19:16:03 +00:00
return "subFrame";
2015-12-03 22:24:26 +00:00
case content::RESOURCE_TYPE_STYLESHEET:
return "stylesheet";
case content::RESOURCE_TYPE_SCRIPT:
return "script";
case content::RESOURCE_TYPE_IMAGE:
return "image";
case content::RESOURCE_TYPE_OBJECT:
return "object";
case content::RESOURCE_TYPE_XHR:
2015-12-09 19:16:03 +00:00
return "xhr";
2015-12-03 22:24:26 +00:00
default:
return "other";
}
}
2017-12-10 11:59:50 +00:00
int32_t GetWebContentsID(int process_id, int frame_id) {
auto* webContents = content::WebContents::FromRenderFrameHost(
content::RenderFrameHost::FromID(process_id, frame_id));
return atom::api::WebContents::GetIDFromWrappedClass(webContents);
}
namespace {
2015-12-03 22:24:26 +00:00
using ResponseHeadersContainer =
std::pair<scoped_refptr<net::HttpResponseHeaders>*, const std::string&>;
void RunSimpleListener(const AtomNetworkDelegate::SimpleListener& listener,
2017-12-10 11:59:50 +00:00
std::unique_ptr<base::DictionaryValue> details,
int render_process_id,
int render_frame_id) {
int32_t id = GetWebContentsID(render_process_id, render_frame_id);
// id must be greater than zero
if (id)
details->SetInteger("webContentsId", id);
return listener.Run(*(details.get()));
}
void RunResponseListener(
const AtomNetworkDelegate::ResponseListener& listener,
2016-05-23 01:59:39 +00:00
std::unique_ptr<base::DictionaryValue> details,
2017-12-10 11:59:50 +00:00
int render_process_id,
int render_frame_id,
const AtomNetworkDelegate::ResponseCallback& callback) {
2017-12-10 11:59:50 +00:00
int32_t id = GetWebContentsID(render_process_id, render_frame_id);
// id must be greater than zero
if (id)
details->SetInteger("webContentsId", id);
return listener.Run(*(details.get()), callback);
2015-12-09 19:16:03 +00:00
}
// Test whether the URL of |request| matches |patterns|.
2015-12-11 13:02:44 +00:00
bool MatchesFilterCondition(net::URLRequest* request,
const URLPatterns& patterns) {
if (patterns.empty())
return true;
2015-12-03 22:24:26 +00:00
2015-12-11 13:02:44 +00:00
for (const auto& pattern : patterns) {
if (pattern.MatchesURL(request->url()))
return true;
}
return false;
2015-12-03 22:24:26 +00:00
}
// Overloaded by multiple types to fill the |details| object.
void ToDictionary(base::DictionaryValue* details, net::URLRequest* request) {
FillRequestDetails(details, request);
2015-12-11 12:40:39 +00:00
details->SetInteger("id", request->identifier());
details->SetDouble("timestamp", base::Time::Now().ToDoubleT() * 1000);
2017-09-13 12:40:29 +00:00
const auto* info = content::ResourceRequestInfo::ForRequest(request);
if (info) {
details->SetString("resourceType",
2017-09-13 12:40:29 +00:00
ResourceTypeToString(info->GetResourceType()));
} else {
details->SetString("resourceType", "other");
}
2015-12-01 04:52:22 +00:00
}
void ToDictionary(base::DictionaryValue* details,
const net::HttpRequestHeaders& headers) {
2016-05-23 01:59:39 +00:00
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
2015-12-01 04:52:22 +00:00
net::HttpRequestHeaders::Iterator it(headers);
while (it.GetNext())
dict->SetStringWithoutPathExpansion(it.name(), it.value());
2016-03-08 14:28:53 +00:00
details->Set("requestHeaders", std::move(dict));
2015-12-01 04:52:22 +00:00
}
void ToDictionary(base::DictionaryValue* details,
const net::HttpResponseHeaders* headers) {
2015-12-11 12:40:39 +00:00
if (!headers)
return;
2016-05-23 01:59:39 +00:00
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
2016-04-27 18:43:50 +00:00
size_t iter = 0;
2015-12-11 12:40:39 +00:00
std::string key;
std::string value;
while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
if (dict->HasKey(key)) {
base::ListValue* values = nullptr;
if (dict->GetList(key, &values))
values->AppendString(value);
} else {
2016-05-23 01:59:39 +00:00
std::unique_ptr<base::ListValue> values(new base::ListValue);
2015-12-11 12:40:39 +00:00
values->AppendString(value);
2016-03-08 14:28:53 +00:00
dict->Set(key, std::move(values));
2015-12-11 12:40:39 +00:00
}
2015-12-01 04:52:22 +00:00
}
2016-03-08 14:28:53 +00:00
details->Set("responseHeaders", std::move(dict));
2015-12-11 12:40:39 +00:00
details->SetString("statusLine", headers->GetStatusLine());
details->SetInteger("statusCode", headers->response_code());
}
void ToDictionary(base::DictionaryValue* details, const GURL& location) {
2015-12-11 12:40:39 +00:00
details->SetString("redirectURL", location.spec());
}
void ToDictionary(base::DictionaryValue* details,
const net::HostPortPair& host_port) {
2015-12-11 12:40:39 +00:00
if (host_port.host().empty())
details->SetString("ip", host_port.host());
}
void ToDictionary(base::DictionaryValue* details, bool from_cache) {
2015-12-11 12:40:39 +00:00
details->SetBoolean("fromCache", from_cache);
}
void ToDictionary(base::DictionaryValue* details,
const net::URLRequestStatus& status) {
2015-12-11 12:40:39 +00:00
details->SetString("error", net::ErrorToString(status.error()));
2015-12-01 04:52:22 +00:00
}
// Helper function to fill |details| with arbitrary |args|.
template<typename Arg>
void FillDetailsObject(base::DictionaryValue* details, Arg arg) {
ToDictionary(details, arg);
}
template<typename Arg, typename... Args>
void FillDetailsObject(base::DictionaryValue* details, Arg arg, Args... args) {
ToDictionary(details, arg);
FillDetailsObject(details, args...);
}
// Fill the native types with the result from the response object.
void ReadFromResponseObject(const base::DictionaryValue& response,
GURL* new_location) {
std::string url;
if (response.GetString("redirectURL", &url))
*new_location = GURL(url);
2015-12-01 04:52:22 +00:00
}
void ReadFromResponseObject(const base::DictionaryValue& response,
net::HttpRequestHeaders* headers) {
const base::DictionaryValue* dict;
if (response.GetDictionary("requestHeaders", &dict)) {
headers->Clear();
for (base::DictionaryValue::Iterator it(*dict);
!it.IsAtEnd();
it.Advance()) {
std::string value;
if (it.value().GetAsString(&value))
headers->SetHeader(it.key(), value);
}
}
2015-12-01 04:52:22 +00:00
}
void ReadFromResponseObject(const base::DictionaryValue& response,
2016-04-08 08:33:57 +00:00
const ResponseHeadersContainer& container) {
const base::DictionaryValue* dict;
2016-04-08 08:33:57 +00:00
std::string status_line;
if (!response.GetString("statusLine", &status_line))
status_line = container.second;
if (response.GetDictionary("responseHeaders", &dict)) {
2016-04-08 08:33:57 +00:00
auto headers = container.first;
*headers = new net::HttpResponseHeaders("");
2016-04-08 08:33:57 +00:00
(*headers)->ReplaceStatusLine(status_line);
for (base::DictionaryValue::Iterator it(*dict);
!it.IsAtEnd();
it.Advance()) {
2015-12-12 03:31:19 +00:00
const base::ListValue* list;
if (it.value().GetAsList(&list)) {
(*headers)->RemoveHeader(it.key());
2015-12-12 03:31:19 +00:00
for (size_t i = 0; i < list->GetSize(); ++i) {
std::string value;
if (list->GetString(i, &value))
(*headers)->AddHeader(it.key() + " : " + value);
}
}
2015-12-04 01:54:01 +00:00
}
}
}
2015-12-01 04:52:22 +00:00
} // namespace
AtomNetworkDelegate::AtomNetworkDelegate() {
}
AtomNetworkDelegate::~AtomNetworkDelegate() {
}
void AtomNetworkDelegate::SetSimpleListenerInIO(
SimpleEvent type,
const URLPatterns& patterns,
const SimpleListener& callback) {
if (callback.is_null())
simple_listeners_.erase(type);
else
simple_listeners_[type] = { patterns, callback };
}
2015-12-09 19:16:03 +00:00
void AtomNetworkDelegate::SetResponseListenerInIO(
ResponseEvent type,
const URLPatterns& patterns,
const ResponseListener& callback) {
if (callback.is_null())
response_listeners_.erase(type);
else
response_listeners_[type] = { patterns, callback };
2015-12-01 04:52:22 +00:00
}
void AtomNetworkDelegate::SetDevToolsNetworkEmulationClientId(
const std::string& client_id) {
client_id_ = client_id;
}
2015-12-01 04:52:22 +00:00
int AtomNetworkDelegate::OnBeforeURLRequest(
net::URLRequest* request,
const net::CompletionCallback& callback,
GURL* new_url) {
2016-11-30 07:30:03 +00:00
if (!base::ContainsKey(response_listeners_, kOnBeforeRequest))
2015-12-11 13:02:44 +00:00
return brightray::NetworkDelegate::OnBeforeURLRequest(
request, callback, new_url);
2015-12-12 05:49:58 +00:00
return HandleResponseEvent(kOnBeforeRequest, request, callback, new_url);
2015-12-01 04:52:22 +00:00
}
2016-09-06 08:24:37 +00:00
int AtomNetworkDelegate::OnBeforeStartTransaction(
2015-12-01 04:52:22 +00:00
net::URLRequest* request,
const net::CompletionCallback& callback,
net::HttpRequestHeaders* headers) {
if (!client_id_.empty())
headers->SetHeader(
DevToolsNetworkTransaction::kDevToolsEmulateNetworkConditionsClientId,
client_id_);
2016-11-30 07:30:03 +00:00
if (!base::ContainsKey(response_listeners_, kOnBeforeSendHeaders))
2016-09-06 08:24:37 +00:00
return brightray::NetworkDelegate::OnBeforeStartTransaction(
2015-12-11 13:02:44 +00:00
request, callback, headers);
2015-12-12 05:49:58 +00:00
return HandleResponseEvent(
kOnBeforeSendHeaders, request, callback, headers, *headers);
2015-12-01 04:52:22 +00:00
}
2016-09-06 08:24:37 +00:00
void AtomNetworkDelegate::OnStartTransaction(
2015-12-01 04:52:22 +00:00
net::URLRequest* request,
const net::HttpRequestHeaders& headers) {
2016-11-30 07:30:03 +00:00
if (!base::ContainsKey(simple_listeners_, kOnSendHeaders)) {
2016-09-06 08:24:37 +00:00
brightray::NetworkDelegate::OnStartTransaction(request, headers);
2015-12-11 13:02:44 +00:00
return;
2015-12-01 04:52:22 +00:00
}
2015-12-11 13:02:44 +00:00
2015-12-12 05:49:58 +00:00
HandleSimpleEvent(kOnSendHeaders, request, headers);
2015-12-01 04:52:22 +00:00
}
int AtomNetworkDelegate::OnHeadersReceived(
net::URLRequest* request,
const net::CompletionCallback& callback,
2015-12-12 05:49:58 +00:00
const net::HttpResponseHeaders* original,
scoped_refptr<net::HttpResponseHeaders>* override,
GURL* allowed) {
2016-11-30 07:30:03 +00:00
if (!base::ContainsKey(response_listeners_, kOnHeadersReceived))
2015-12-11 13:02:44 +00:00
return brightray::NetworkDelegate::OnHeadersReceived(
2015-12-12 05:49:58 +00:00
request, callback, original, override, allowed);
2015-12-11 13:02:44 +00:00
2015-12-12 05:49:58 +00:00
return HandleResponseEvent(
2016-04-08 08:33:57 +00:00
kOnHeadersReceived, request, callback,
std::make_pair(override, original->GetStatusLine()), original);
2015-12-01 04:52:22 +00:00
}
void AtomNetworkDelegate::OnBeforeRedirect(net::URLRequest* request,
2015-12-11 12:40:39 +00:00
const GURL& new_location) {
2016-11-30 07:30:03 +00:00
if (!base::ContainsKey(simple_listeners_, kOnBeforeRedirect)) {
2015-12-09 19:16:03 +00:00
brightray::NetworkDelegate::OnBeforeRedirect(request, new_location);
2015-12-11 13:02:44 +00:00
return;
2015-12-01 04:52:22 +00:00
}
2015-12-11 13:02:44 +00:00
2015-12-12 05:49:58 +00:00
HandleSimpleEvent(kOnBeforeRedirect, request, new_location,
request->response_headers(), request->GetSocketAddress(),
request->was_cached());
2015-12-01 04:52:22 +00:00
}
void AtomNetworkDelegate::OnResponseStarted(net::URLRequest* request) {
2016-11-30 07:30:03 +00:00
if (!base::ContainsKey(simple_listeners_, kOnResponseStarted)) {
2015-12-09 19:16:03 +00:00
brightray::NetworkDelegate::OnResponseStarted(request);
2015-12-11 13:02:44 +00:00
return;
2015-12-01 04:52:22 +00:00
}
2015-12-11 13:02:44 +00:00
if (request->status().status() != net::URLRequestStatus::SUCCESS)
return;
2015-12-12 05:49:58 +00:00
HandleSimpleEvent(kOnResponseStarted, request, request->response_headers(),
request->was_cached());
2015-12-01 04:52:22 +00:00
}
void AtomNetworkDelegate::OnCompleted(net::URLRequest* request, bool started) {
2015-12-22 15:46:25 +00:00
// OnCompleted may happen before other events.
callbacks_.erase(request->identifier());
2015-12-11 13:02:44 +00:00
if (request->status().status() == net::URLRequestStatus::FAILED ||
request->status().status() == net::URLRequestStatus::CANCELED) {
// Error event.
OnErrorOccurred(request, started);
2015-12-11 13:02:44 +00:00
return;
} else if (request->response_headers() &&
net::HttpResponseHeaders::IsRedirectResponseCode(
request->response_headers()->response_code())) {
// Redirect event.
brightray::NetworkDelegate::OnCompleted(request, started);
return;
}
2015-12-03 22:24:26 +00:00
2016-11-30 07:30:03 +00:00
if (!base::ContainsKey(simple_listeners_, kOnCompleted)) {
2015-12-09 19:16:03 +00:00
brightray::NetworkDelegate::OnCompleted(request, started);
2015-12-11 13:02:44 +00:00
return;
2015-12-03 22:24:26 +00:00
}
2015-12-11 13:02:44 +00:00
2015-12-12 05:49:58 +00:00
HandleSimpleEvent(kOnCompleted, request, request->response_headers(),
request->was_cached());
}
void AtomNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) {
callbacks_.erase(request->identifier());
}
void AtomNetworkDelegate::OnErrorOccurred(
net::URLRequest* request, bool started) {
2016-11-30 07:30:03 +00:00
if (!base::ContainsKey(simple_listeners_, kOnErrorOccurred)) {
brightray::NetworkDelegate::OnCompleted(request, started);
return;
}
2015-12-12 05:49:58 +00:00
HandleSimpleEvent(kOnErrorOccurred, request, request->was_cached(),
request->status());
}
template<typename Out, typename... Args>
int AtomNetworkDelegate::HandleResponseEvent(
ResponseEvent type,
net::URLRequest* request,
const net::CompletionCallback& callback,
Out out,
Args... args) {
const auto& info = response_listeners_[type];
2015-12-11 13:02:44 +00:00
if (!MatchesFilterCondition(request, info.url_patterns))
2015-12-12 05:49:58 +00:00
return net::OK;
2015-12-11 13:02:44 +00:00
2016-05-23 01:59:39 +00:00
std::unique_ptr<base::DictionaryValue> details(new base::DictionaryValue);
2015-12-12 05:49:58 +00:00
FillDetailsObject(details.get(), request, args...);
2015-12-11 13:02:44 +00:00
2017-12-10 11:59:50 +00:00
int render_process_id, render_frame_id;
content::ResourceRequestInfo::GetRenderFrameForRequest(
request, &render_process_id, &render_frame_id);
// The |request| could be destroyed before the |callback| is called.
2015-12-22 15:46:25 +00:00
callbacks_[request->identifier()] = callback;
2015-12-12 05:49:58 +00:00
ResponseCallback response =
2015-12-22 15:46:25 +00:00
base::Bind(&AtomNetworkDelegate::OnListenerResultInUI<Out>,
base::Unretained(this), request->identifier(), out);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
2015-12-12 05:49:58 +00:00
base::Bind(RunResponseListener, info.listener, base::Passed(&details),
2017-12-10 11:59:50 +00:00
render_process_id, render_frame_id, response));
2015-12-12 05:49:58 +00:00
return net::ERR_IO_PENDING;
2015-12-03 22:24:26 +00:00
}
2015-12-12 05:49:58 +00:00
template<typename...Args>
void AtomNetworkDelegate::HandleSimpleEvent(
SimpleEvent type, net::URLRequest* request, Args... args) {
const auto& info = simple_listeners_[type];
2015-12-11 13:02:44 +00:00
if (!MatchesFilterCondition(request, info.url_patterns))
return;
2016-05-23 01:59:39 +00:00
std::unique_ptr<base::DictionaryValue> details(new base::DictionaryValue);
2015-12-12 05:49:58 +00:00
FillDetailsObject(details.get(), request, args...);
2015-12-11 13:02:44 +00:00
2017-12-10 11:59:50 +00:00
int render_process_id, render_frame_id;
content::ResourceRequestInfo::GetRenderFrameForRequest(
request, &render_process_id, &render_frame_id);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
2017-12-10 11:59:50 +00:00
base::Bind(RunSimpleListener, info.listener, base::Passed(&details),
render_process_id, render_frame_id));
2015-12-01 04:52:22 +00:00
}
2015-12-22 15:46:25 +00:00
template<typename T>
void AtomNetworkDelegate::OnListenerResultInIO(
2016-05-23 01:59:39 +00:00
uint64_t id, T out, std::unique_ptr<base::DictionaryValue> response) {
2015-12-22 15:46:25 +00:00
// The request has been destroyed.
2016-11-30 07:30:03 +00:00
if (!base::ContainsKey(callbacks_, id))
2015-12-22 15:46:25 +00:00
return;
ReadFromResponseObject(*response, out);
2015-12-22 15:46:25 +00:00
bool cancel = false;
response->GetBoolean("cancel", &cancel);
callbacks_[id].Run(cancel ? net::ERR_BLOCKED_BY_CLIENT : net::OK);
}
template<typename T>
void AtomNetworkDelegate::OnListenerResultInUI(
uint64_t id, T out, const base::DictionaryValue& response) {
2016-05-23 01:59:39 +00:00
std::unique_ptr<base::DictionaryValue> copy = response.CreateDeepCopy();
2015-12-22 15:46:25 +00:00
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&AtomNetworkDelegate::OnListenerResultInIO<T>,
base::Unretained(this), id, out, base::Passed(&copy)));
}
2015-12-01 04:52:22 +00:00
} // namespace atom