electron/atom/browser/net/atom_network_delegate.cc

548 lines
18 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"
#include <memory>
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"
#include "atom/browser/login_handler.h"
2015-12-01 04:52:22 +00:00
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/options_switches.h"
#include "base/command_line.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 "base/task/post_task.h"
#include "content/public/browser/browser_task_traits.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"
#include "content/public/browser/resource_request_info.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
2015-12-01 04:52:22 +00:00
#include "net/url_request/url_request.h"
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);
auto* info = content::ResourceRequestInfo::ForRequest(request);
if (info) {
details->SetString("resourceType",
2018-04-18 01:55:30 +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) {
auto dict = std::make_unique<base::DictionaryValue>();
2015-12-01 04:52:22 +00:00
net::HttpRequestHeaders::Iterator it(headers);
while (it.GetNext())
dict->SetKey(it.name(), base::Value(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;
auto dict = std::make_unique<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->FindKey(key)) {
2015-12-11 12:40:39 +00:00
base::ListValue* values = nullptr;
if (dict->GetList(key, &values))
values->AppendString(value);
} else {
auto values = std::make_unique<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|.
2018-04-18 01:55:30 +00:00
template <typename Arg>
void FillDetailsObject(base::DictionaryValue* details, Arg arg) {
ToDictionary(details, arg);
}
2018-04-18 01:55:30 +00:00
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();
2018-04-18 01:55:30 +00:00
for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd();
it.Advance()) {
if (it.value().is_string()) {
std::string value = it.value().GetString();
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)) {
auto* headers = container.first;
*headers = new net::HttpResponseHeaders("");
2016-04-08 08:33:57 +00:00
(*headers)->ReplaceStatusLine(status_line);
2018-04-18 01:55:30 +00:00
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::SimpleListenerInfo::SimpleListenerInfo(
URLPatterns patterns_,
SimpleListener listener_)
: url_patterns(patterns_), listener(listener_) {}
AtomNetworkDelegate::SimpleListenerInfo::SimpleListenerInfo() = default;
AtomNetworkDelegate::SimpleListenerInfo::~SimpleListenerInfo() = default;
AtomNetworkDelegate::ResponseListenerInfo::ResponseListenerInfo(
URLPatterns patterns_,
ResponseListener listener_)
: url_patterns(patterns_), listener(listener_) {}
AtomNetworkDelegate::ResponseListenerInfo::ResponseListenerInfo() = default;
AtomNetworkDelegate::ResponseListenerInfo::~ResponseListenerInfo() = default;
AtomNetworkDelegate::AtomNetworkDelegate() {
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kIgnoreConnectionsLimit)) {
std::string value =
command_line->GetSwitchValueASCII(switches::kIgnoreConnectionsLimit);
ignore_connections_limit_domains_ = base::SplitString(
value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
}
}
2015-12-01 04:52:22 +00:00
2018-04-18 01:55:30 +00:00
AtomNetworkDelegate::~AtomNetworkDelegate() {}
2015-12-01 04:52:22 +00:00
2018-04-18 01:55:30 +00:00
void AtomNetworkDelegate::SetSimpleListenerInIO(SimpleEvent type,
URLPatterns patterns,
SimpleListener callback) {
if (callback.is_null())
simple_listeners_.erase(type);
else
2018-04-18 01:55:30 +00:00
simple_listeners_[type] = {std::move(patterns), std::move(callback)};
}
2015-12-09 19:16:03 +00:00
2018-04-18 01:55:30 +00:00
void AtomNetworkDelegate::SetResponseListenerInIO(ResponseEvent type,
URLPatterns patterns,
ResponseListener callback) {
if (callback.is_null())
response_listeners_.erase(type);
else
2018-04-18 01:55:30 +00:00
response_listeners_[type] = {std::move(patterns), std::move(callback)};
2015-12-01 04:52:22 +00:00
}
int AtomNetworkDelegate::OnBeforeURLRequest(
net::URLRequest* request,
net::CompletionOnceCallback callback,
2015-12-01 04:52:22 +00:00
GURL* new_url) {
if (!base::ContainsKey(response_listeners_, kOnBeforeRequest)) {
for (const auto& domain : ignore_connections_limit_domains_) {
if (request->url().DomainIs(domain)) {
// Allow unlimited concurrent connections.
request->SetPriority(net::MAXIMUM_PRIORITY);
request->SetLoadFlags(request->load_flags() | net::LOAD_IGNORE_LIMITS);
break;
}
}
return net::OK;
}
2015-12-11 13:02:44 +00:00
return HandleResponseEvent(kOnBeforeRequest, request, std::move(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,
net::CompletionOnceCallback callback,
2015-12-01 04:52:22 +00:00
net::HttpRequestHeaders* headers) {
2016-11-30 07:30:03 +00:00
if (!base::ContainsKey(response_listeners_, kOnBeforeSendHeaders))
return net::OK;
2015-12-11 13:02:44 +00:00
return HandleResponseEvent(kOnBeforeSendHeaders, request, std::move(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) {
if (!base::ContainsKey(simple_listeners_, kOnSendHeaders))
2015-12-11 13:02:44 +00:00
return;
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,
net::CompletionOnceCallback 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))
return net::OK;
2015-12-11 13:02:44 +00:00
2015-12-12 05:49:58 +00:00
return HandleResponseEvent(
kOnHeadersReceived, request, std::move(callback),
2016-04-08 08:33:57 +00:00
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) {
if (!base::ContainsKey(simple_listeners_, kOnBeforeRedirect))
2015-12-11 13:02:44 +00:00
return;
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,
int net_error) {
if (!base::ContainsKey(simple_listeners_, kOnResponseStarted))
2015-12-11 13:02:44 +00:00
return;
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,
int net_error) {
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, net_error);
2015-12-11 13:02:44 +00:00
return;
}
if (request->response_headers() &&
net::HttpResponseHeaders::IsRedirectResponseCode(
request->response_headers()->response_code())) {
2015-12-11 13:02:44 +00:00
// Redirect event.
return;
}
2015-12-03 22:24:26 +00:00
if (!base::ContainsKey(simple_listeners_, kOnCompleted))
2015-12-11 13:02:44 +00:00
return;
2015-12-12 05:49:58 +00:00
HandleSimpleEvent(kOnCompleted, request, request->response_headers(),
request->was_cached());
}
void AtomNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) {
const auto& it = login_handler_map_.find(request->identifier());
if (it != login_handler_map_.end()) {
it->second->NotifyRequestDestroyed();
it->second = nullptr;
login_handler_map_.erase(it);
}
callbacks_.erase(request->identifier());
}
net::NetworkDelegate::AuthRequiredResponse AtomNetworkDelegate::OnAuthRequired(
net::URLRequest* request,
const net::AuthChallengeInfo& auth_info,
AuthCallback callback,
net::AuthCredentials* credentials) {
auto* resource_request_info =
content::ResourceRequestInfo::ForRequest(request);
if (!resource_request_info)
return AUTH_REQUIRED_RESPONSE_NO_ACTION;
login_handler_map_.emplace(
request->identifier(),
new LoginHandler(request, auth_info, std::move(callback), credentials,
resource_request_info));
return AUTH_REQUIRED_RESPONSE_IO_PENDING;
}
bool AtomNetworkDelegate::OnCanGetCookies(const net::URLRequest& request,
const net::CookieList& cookie_list,
bool allowed_from_caller) {
return true;
}
bool AtomNetworkDelegate::OnCanSetCookie(
const net::URLRequest& request,
const net::CanonicalCookie& cookie_line,
net::CookieOptions* options,
bool allowed_from_caller) {
return true;
}
bool AtomNetworkDelegate::OnCanAccessFile(
const net::URLRequest& request,
const base::FilePath& original_path,
const base::FilePath& absolute_path) const {
return true;
}
bool AtomNetworkDelegate::OnForcePrivacyMode(
const GURL& url,
const GURL& first_party_for_cookies) const {
return false;
}
bool AtomNetworkDelegate::OnCancelURLRequestWithPolicyViolatingReferrerHeader(
const net::URLRequest& request,
const GURL& target_url,
const GURL& referrer_url) const {
return false;
}
// TODO(deepak1556) : Enable after hooking into the reporting service
// https://crbug.com/704259
bool AtomNetworkDelegate::OnCanQueueReportingReport(
const url::Origin& origin) const {
return false;
}
void AtomNetworkDelegate::OnCanSendReportingReports(
std::set<url::Origin> origins,
base::OnceCallback<void(std::set<url::Origin>)> result_callback) const {}
bool AtomNetworkDelegate::OnCanSetReportingClient(const url::Origin& origin,
const GURL& endpoint) const {
return false;
}
bool AtomNetworkDelegate::OnCanUseReportingClient(const url::Origin& origin,
const GURL& endpoint) const {
return false;
}
2018-04-18 01:55:30 +00:00
void AtomNetworkDelegate::OnErrorOccurred(net::URLRequest* request,
bool started,
int net_error) {
if (!base::ContainsKey(simple_listeners_, kOnErrorOccurred))
return;
2015-12-12 05:49:58 +00:00
HandleSimpleEvent(kOnErrorOccurred, request, request->was_cached(),
request->status());
}
2018-04-18 01:55:30 +00:00
template <typename Out, typename... Args>
2015-12-12 05:49:58 +00:00
int AtomNetworkDelegate::HandleResponseEvent(
ResponseEvent type,
net::URLRequest* request,
net::CompletionOnceCallback callback,
2015-12-12 05:49:58 +00:00
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
auto details = std::make_unique<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.
callbacks_[request->identifier()] = std::move(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);
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(RunResponseListener, info.listener, std::move(details),
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
}
2018-04-18 01:55:30 +00:00
template <typename... Args>
void AtomNetworkDelegate::HandleSimpleEvent(SimpleEvent type,
net::URLRequest* request,
Args... args) {
2015-12-12 05:49:58 +00:00
const auto& info = simple_listeners_[type];
2015-12-11 13:02:44 +00:00
if (!MatchesFilterCondition(request, info.url_patterns))
return;
auto details = std::make_unique<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);
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(RunSimpleListener, info.listener, std::move(details),
render_process_id, render_frame_id));
2015-12-01 04:52:22 +00:00
}
2018-04-18 01:55:30 +00:00
template <typename T>
2015-12-22 15:46:25 +00:00
void AtomNetworkDelegate::OnListenerResultInIO(
2018-04-18 01:55:30 +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);
std::move(callbacks_[id]).Run(cancel ? net::ERR_BLOCKED_BY_CLIENT : net::OK);
2015-12-22 15:46:25 +00:00
}
2018-04-18 01:55:30 +00:00
template <typename T>
2015-12-22 15:46:25 +00:00
void AtomNetworkDelegate::OnListenerResultInUI(
2018-04-18 01:55:30 +00:00
uint64_t id,
T out,
const base::DictionaryValue& response) {
auto copy = base::DictionaryValue::From(
base::Value::ToUniquePtrValue(response.Clone()));
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&AtomNetworkDelegate::OnListenerResultInIO<T>,
base::Unretained(this), id, out, std::move(copy)));
2015-12-22 15:46:25 +00:00
}
2015-12-01 04:52:22 +00:00
} // namespace atom