1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/nearby_sharing/instantmessaging/receive_messages_express.h"
#include <sstream>
#include <string_view>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/metrics/histogram_functions.h"
#include "base/notimplemented.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/nearby_sharing/instantmessaging/constants.h"
#include "chrome/browser/nearby_sharing/instantmessaging/proto/instantmessaging.pb.h"
#include "chrome/browser/nearby_sharing/instantmessaging/token_fetcher.h"
#include "chrome/browser/nearby_sharing/webrtc_request_builder.h"
#include "chromeos/ash/components/nearby/common/client/nearby_http_result.h"
#include "components/cross_device/logging/logging.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "net/base/load_flags.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "url/gurl.h"
namespace {
const base::TimeDelta kFastPathReadyTimeout = base::Milliseconds(2500);
// Timeout for the receive messages stream, from when the stream first opens.
// This timeout applies to the Tachyon signaling process, so once we establish
// the peer-to-peer connection this stream and timeout will be canceled. There
// are other timeouts in the WebRTC medium that will cancel the signaling
// process sooner than 60s, so this is just a failsafe to make sure we clean up
// the ReceiveMessagesExpress if something goes wrong.
const base::TimeDelta kStreamTimeout = base::Seconds(60);
const net::NetworkTrafficAnnotationTag kTrafficAnnotation =
net::DefineNetworkTrafficAnnotation("receive_messages_express", R"(
semantics {
sender: "ReceiveMessagesExpress"
description:
"Receives messages sent from another device via a Gaia "
"authenticated Google messaging backend."
trigger:
"Peer uses any Chrome cross-device sharing feature and selects "
"this devices to send the data to."
data: "WebRTC session description protocol messages are exchanged "
"between devices to set up a peer to peer connection as documented "
"in https://tools.ietf.org/html/rfc4566 and "
"https://www.w3.org/TR/webrtc/#session-description-model. No user "
"data is sent in the request."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"This feature is only enabled for signed-in users who enable "
"Nearby sharing or Phone Hub."
chrome_policy {
NearbyShareAllowed {
policy_options {mode: MANDATORY}
NearbyShareAllowed: 0
},
PhoneHubAllowed {
policy_options {mode: MANDATORY}
PhoneHubAllowed: 0
}
}
})");
std::optional<ash::nearby::NearbyHttpStatus> HttpStatusFromUrlLoader(
const network::SimpleURLLoader* loader) {
if (!loader)
return std::nullopt;
return ash::nearby::NearbyHttpStatus(loader->NetError(),
loader->ResponseInfo());
}
void LogReceiveResult(
bool success,
const std::optional<ash::nearby::NearbyHttpStatus>& http_status,
const std::string& request_id) {
std::stringstream ss;
ss << "Instant messaging receive express "
<< (success ? "succeeded" : "failed") << " for request " << request_id;
base::UmaHistogramBoolean(
"Nearby.Connections.InstantMessaging.ReceiveExpress.Result", success);
if (http_status) {
ss << " HTTP status: " << *http_status;
if (!success) {
base::UmaHistogramSparse(
"Nearby.Connections.InstantMessaging.ReceiveExpress.Result."
"FailureReason",
http_status->GetResultCodeForMetrics());
}
}
if (success) {
CD_LOG(INFO, Feature::NS) << ss.str();
} else {
CD_LOG(ERROR, Feature::NS) << ss.str();
}
}
} // namespace
// static
void ReceiveMessagesExpress::StartReceiveSession(
const std::string& self_id,
sharing::mojom::LocationHintPtr location_hint,
mojo::PendingRemote<sharing::mojom::IncomingMessagesListener>
incoming_messages_listener,
StartReceivingMessagesCallback callback,
signin::IdentityManager* identity_manager,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) {
chrome_browser_nearby_sharing_instantmessaging::ReceiveMessagesExpressRequest
request = BuildReceiveRequest(self_id, std::move(location_hint));
CD_LOG(INFO, Feature::NS) << __func__ << ": self_id=" << self_id
<< ", request id=" << request.header().request_id();
auto receive_messages_express = base::WrapUnique(
new ReceiveMessagesExpress(std::move(incoming_messages_listener),
identity_manager, url_loader_factory));
// Created a mojo pipe for the session that can be used to stop receiving.
mojo::PendingRemote<sharing::mojom::ReceiveMessagesSession> pending_remote;
mojo::PendingReceiver<sharing::mojom::ReceiveMessagesSession>
pending_receiver = pending_remote.InitWithNewPipeAndPassReceiver();
receive_messages_express->StartReceivingMessages(request, std::move(callback),
std::move(pending_remote));
mojo::MakeSelfOwnedReceiver(std::move(receive_messages_express),
std::move(pending_receiver));
}
ReceiveMessagesExpress::ReceiveMessagesExpress(
mojo::PendingRemote<sharing::mojom::IncomingMessagesListener>
incoming_messages_listener,
signin::IdentityManager* identity_manager,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
: incoming_messages_listener_(std::move(incoming_messages_listener)),
token_fetcher_(identity_manager),
url_loader_factory_(std::move(url_loader_factory)) {}
ReceiveMessagesExpress::~ReceiveMessagesExpress() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
CD_LOG(VERBOSE, Feature::NS)
<< __func__
<< ": Receive messages session going down, request id=" << request_id_;
fast_path_ready_timeout_timer_.Stop();
if (start_receiving_messages_callback_) {
std::move(start_receiving_messages_callback_)
.Run(false, mojo::NullRemote());
}
}
void ReceiveMessagesExpress::StartReceivingMessages(
const chrome_browser_nearby_sharing_instantmessaging::
ReceiveMessagesExpressRequest& request,
StartReceivingMessagesCallback start_receiving_messages_callback,
mojo::PendingRemote<sharing::mojom::ReceiveMessagesSession>
pending_remote_for_result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!url_loader_);
CD_LOG(VERBOSE, Feature::NS)
<< "ReceiveMessagesExpress::StartReceivingMessages() called.";
request_id_ = request.header().request_id();
// Used to complete the initial mojo call once fast path is received.
start_receiving_messages_callback_ =
std::move(start_receiving_messages_callback);
// This is the remote side of the self owned mojo pipe that will be returned
// when completing start_receiving_messages_callback
self_pending_remote_ = std::move(pending_remote_for_result);
token_fetcher_.GetAccessToken(
base::BindOnce(&ReceiveMessagesExpress::DoStartReceivingMessages,
weak_ptr_factory_.GetWeakPtr(), request));
}
void ReceiveMessagesExpress::DoStartReceivingMessages(
const chrome_browser_nearby_sharing_instantmessaging::
ReceiveMessagesExpressRequest& request,
const std::string& oauth_token) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(url_loader_ == nullptr);
base::UmaHistogramBoolean(
"Nearby.Connections.InstantMessaging.ReceiveExpress."
"OAuthTokenFetchResult",
!oauth_token.empty());
if (oauth_token.empty()) {
FailSessionAndDestruct("Auth token fetch failed");
// |this| may be destroyed here.
return;
}
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": OAuth token fetched; starting stream download";
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = GURL(kInstantMessagingReceiveMessageAPI);
resource_request->load_flags =
net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE;
resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;
resource_request->method = net::HttpRequestHeaders::kPostMethod;
resource_request->headers.AddHeaderFromString(
base::StringPrintf(kAuthorizationHeaderFormat, oauth_token.c_str()));
url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
kTrafficAnnotation);
url_loader_->SetTimeoutDuration(kStreamTimeout);
url_loader_->AttachStringForUpload(request.SerializeAsString(),
"application/x-protobuf");
url_loader_->DownloadAsStream(url_loader_factory_.get(), this);
// We are safe to use base::Unretained() here because if
// ReceiveMessagesExpress is destroyed the timer will go out of scope first
// which will cancel it.
fast_path_ready_timeout_timer_.Start(
FROM_HERE, kFastPathReadyTimeout,
base::BindOnce(&ReceiveMessagesExpress::OnFastPathReadyTimeout,
base::Unretained(this)));
}
void ReceiveMessagesExpress::OnFastPathReadyTimeout() {
CD_LOG(WARNING, Feature::NS) << __func__;
FailSessionAndDestruct("Timeout before receiving fast path ready");
// |this| will be destroyed here.
return;
}
void ReceiveMessagesExpress::StopReceivingMessages() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
fast_path_ready_timeout_timer_.Stop();
// Cancel any pending calls into this object.
weak_ptr_factory_.InvalidateWeakPtrs();
// This implicitly cancels the download stream. We intentionally don't call
// OnComplete() when the other side calls StopReceivingMessages().
url_loader_.reset();
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": callback already invoked? "
<< (start_receiving_messages_callback_ ? "no" : "yes");
if (start_receiving_messages_callback_) {
FailSessionAndDestruct(
"StopReceivingMessages() called before fast path ready was received");
// |this| destroyed here.
return;
}
}
void ReceiveMessagesExpress::OnDataReceived(std::string_view data,
base::OnceClosure resume) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
for (auto response : stream_parser_.Append(data)) {
DelegateMessage(response);
}
std::move(resume).Run();
}
void ReceiveMessagesExpress::DelegateMessage(
const chrome_browser_nearby_sharing_instantmessaging::
ReceiveMessagesResponse& response) {
// Security Note - The ReceiveMessagesResponse proto is coming from a trusted
// Google server (Tachyon) from the signaling channel for webrtc messages for
// sharing messages and hence can be parsed on the browser process.
// The message contained within the proto is untrusted and should be parsed
// within a sandbox process.
switch (response.body_case()) {
case chrome_browser_nearby_sharing_instantmessaging::
ReceiveMessagesResponse::kFastPathReady:
OnFastPathReady();
break;
case chrome_browser_nearby_sharing_instantmessaging::
ReceiveMessagesResponse::kInboxMessage:
OnMessageReceived(response.inbox_message().message());
break;
default:
CD_LOG(ERROR, Feature::NS)
<< __func__
<< ": message body case was unexpected: " << response.body_case();
NOTREACHED();
}
}
void ReceiveMessagesExpress::OnComplete(bool success) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
fast_path_ready_timeout_timer_.Stop();
std::optional<ash::nearby::NearbyHttpStatus> http_status =
HttpStatusFromUrlLoader(url_loader_.get());
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": success? " << (success ? "yes" : "no")
<< ", start calback invoked? "
<< (start_receiving_messages_callback_ ? "no" : "yes") << ", net::Error "
<< url_loader_->NetError();
if (start_receiving_messages_callback_) {
LogReceiveResult(success, http_status, request_id_);
// If we have not called start_receiving_messages_callback_ yet, we
// consider that a failure and need to complete the mojo call with a
// failure.
FailSessionAndDestruct("Download stream ended before fast path ready");
// |this| will be destroyed here.
return;
} else {
// Only call OnComplete() if the start callback has been invoked, meaning
// the stream has opened and we have received "fast path ready".
incoming_messages_listener_->OnComplete(success);
}
}
void ReceiveMessagesExpress::OnRetry(base::OnceClosure start_retry) {
CD_LOG(ERROR, Feature::NS)
<< __func__ << ": retry is not implemented for the url_fetcher";
NOTIMPLEMENTED();
}
void ReceiveMessagesExpress::OnFastPathReady() {
CD_LOG(VERBOSE, Feature::NS) << __func__;
fast_path_ready_timeout_timer_.Stop();
if (start_receiving_messages_callback_) {
LogReceiveResult(/*success=*/true, /*http_status=*/std::nullopt,
request_id_);
std::move(start_receiving_messages_callback_)
.Run(true, std::move(self_pending_remote_));
}
}
void ReceiveMessagesExpress::OnMessageReceived(const std::string& message) {
CD_LOG(VERBOSE, Feature::NS)
<< __func__ << ": message size: " << message.size();
if (!incoming_messages_listener_) {
CD_LOG(WARNING, Feature::NS)
<< __func__ << ": no listener available to receive message";
return;
}
incoming_messages_listener_->OnMessage(message);
}
void ReceiveMessagesExpress::FailSessionAndDestruct(const std::string reason) {
// Cancel any pending calls into this object.
weak_ptr_factory_.InvalidateWeakPtrs();
// Explicitly stop any pending downloads if there are any.
url_loader_.reset();
if (start_receiving_messages_callback_) {
// We don't give the remote in the callback because at this point
// calling StopReceiveMessages won't do anything.
std::move(start_receiving_messages_callback_)
.Run(false, mojo::NullRemote());
}
CD_LOG(ERROR, Feature::NS)
<< __func__ << ": Terminating receive message express session: ["
<< reason << "]";
// If we have not returned self_pending_remote_ to the caller, This will kill
// the self-owned mojo pipe and implicitly destroy this object. If we have
// given out this pending remote through |start_receiving_messages_callback_|,
// the other side of the pipe controls the lifetime of this object and this
// reset does nothing.
self_pending_remote_.reset();
}
|