Add ICU message format support
[chromium-blink-merge.git] / content / browser / renderer_host / p2p / socket_host_udp.cc
blob5137972ebb0d9edb3d6f02cfd820135a39caaff1
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/renderer_host/p2p/socket_host_udp.h"
7 #include "base/bind.h"
8 #include "base/metrics/field_trial.h"
9 #include "base/metrics/histogram.h"
10 #include "base/stl_util.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/trace_event/trace_event.h"
13 #include "content/browser/renderer_host/p2p/socket_host_throttler.h"
14 #include "content/common/p2p_messages.h"
15 #include "content/public/browser/content_browser_client.h"
16 #include "content/public/common/content_client.h"
17 #include "ipc/ipc_sender.h"
18 #include "net/base/io_buffer.h"
19 #include "net/base/net_errors.h"
20 #include "net/base/net_util.h"
21 #include "third_party/webrtc/base/asyncpacketsocket.h"
23 namespace {
25 // UDP packets cannot be bigger than 64k.
26 const int kReadBufferSize = 65536;
27 // Socket receive buffer size.
28 const int kRecvSocketBufferSize = 65536; // 64K
30 // Defines set of transient errors. These errors are ignored when we get them
31 // from sendto() or recvfrom() calls.
33 // net::ERR_OUT_OF_MEMORY
35 // This is caused by ENOBUFS which means the buffer of the network interface
36 // is full.
38 // net::ERR_CONNECTION_RESET
40 // This is caused by WSAENETRESET or WSAECONNRESET which means the
41 // last send resulted in an "ICMP Port Unreachable" message.
42 struct {
43 int code;
44 const char* name;
45 } static const kTransientErrors[] {
46 {net::ERR_ADDRESS_UNREACHABLE, "net::ERR_ADDRESS_UNREACHABLE"},
47 {net::ERR_ADDRESS_INVALID, "net::ERR_ADDRESS_INVALID"},
48 {net::ERR_ACCESS_DENIED, "net::ERR_ACCESS_DENIED"},
49 {net::ERR_CONNECTION_RESET, "net::ERR_CONNECTION_RESET"},
50 {net::ERR_OUT_OF_MEMORY, "net::ERR_OUT_OF_MEMORY"},
51 {net::ERR_INTERNET_DISCONNECTED, "net::ERR_INTERNET_DISCONNECTED"}
54 bool IsTransientError(int error) {
55 for (const auto& transient_error : kTransientErrors) {
56 if (transient_error.code == error)
57 return true;
59 return false;
62 const char* GetTransientErrorName(int error) {
63 for (const auto& transient_error : kTransientErrors) {
64 if (transient_error.code == error)
65 return transient_error.name;
67 return "";
70 } // namespace
72 namespace content {
74 P2PSocketHostUdp::PendingPacket::PendingPacket(
75 const net::IPEndPoint& to,
76 const std::vector<char>& content,
77 const rtc::PacketOptions& options,
78 uint64 id)
79 : to(to),
80 data(new net::IOBuffer(content.size())),
81 size(content.size()),
82 packet_options(options),
83 id(id) {
84 memcpy(data->data(), &content[0], size);
87 P2PSocketHostUdp::PendingPacket::~PendingPacket() {
90 P2PSocketHostUdp::P2PSocketHostUdp(IPC::Sender* message_sender,
91 int socket_id,
92 P2PMessageThrottler* throttler)
93 : P2PSocketHost(message_sender, socket_id, P2PSocketHost::UDP),
94 send_pending_(false),
95 last_dscp_(net::DSCP_CS0),
96 throttler_(throttler),
97 send_buffer_size_(0) {
98 net::UDPServerSocket* socket = new net::UDPServerSocket(
99 GetContentClient()->browser()->GetNetLog(), net::NetLog::Source());
100 #if defined(OS_WIN)
101 socket->UseNonBlockingIO();
102 #endif
103 socket_.reset(socket);
106 P2PSocketHostUdp::~P2PSocketHostUdp() {
107 if (state_ == STATE_OPEN) {
108 DCHECK(socket_.get());
109 socket_.reset();
113 void P2PSocketHostUdp::SetSendBufferSize() {
114 unsigned int send_buffer_size = 0;
116 base::StringToUint(
117 base::FieldTrialList::FindFullName("WebRTC-SystemUDPSendSocketSize"),
118 &send_buffer_size);
120 if (send_buffer_size > 0) {
121 if (!SetOption(P2P_SOCKET_OPT_SNDBUF, send_buffer_size)) {
122 LOG(WARNING) << "Failed to set socket send buffer size to "
123 << send_buffer_size;
124 } else {
125 send_buffer_size_ = send_buffer_size;
130 bool P2PSocketHostUdp::Init(const net::IPEndPoint& local_address,
131 const P2PHostAndIPEndPoint& remote_address) {
132 DCHECK_EQ(state_, STATE_UNINITIALIZED);
134 int result = socket_->Listen(local_address);
135 if (result < 0) {
136 LOG(ERROR) << "bind() failed: " << result;
137 OnError();
138 return false;
141 // Setting recv socket buffer size.
142 if (socket_->SetReceiveBufferSize(kRecvSocketBufferSize) != net::OK) {
143 LOG(WARNING) << "Failed to set socket receive buffer size to "
144 << kRecvSocketBufferSize;
147 net::IPEndPoint address;
148 result = socket_->GetLocalAddress(&address);
149 if (result < 0) {
150 LOG(ERROR) << "P2PSocketHostUdp::Init(): unable to get local address: "
151 << result;
152 OnError();
153 return false;
155 VLOG(1) << "Local address: " << address.ToString();
157 state_ = STATE_OPEN;
159 SetSendBufferSize();
161 // NOTE: Remote address will be same as what renderer provided.
162 message_sender_->Send(new P2PMsg_OnSocketCreated(
163 id_, address, remote_address.ip_address));
165 recv_buffer_ = new net::IOBuffer(kReadBufferSize);
166 DoRead();
168 return true;
171 void P2PSocketHostUdp::OnError() {
172 socket_.reset();
173 send_queue_.clear();
175 if (state_ == STATE_UNINITIALIZED || state_ == STATE_OPEN)
176 message_sender_->Send(new P2PMsg_OnError(id_));
178 state_ = STATE_ERROR;
181 void P2PSocketHostUdp::DoRead() {
182 int result;
183 do {
184 result = socket_->RecvFrom(
185 recv_buffer_.get(),
186 kReadBufferSize,
187 &recv_address_,
188 base::Bind(&P2PSocketHostUdp::OnRecv, base::Unretained(this)));
189 if (result == net::ERR_IO_PENDING)
190 return;
191 HandleReadResult(result);
192 } while (state_ == STATE_OPEN);
195 void P2PSocketHostUdp::OnRecv(int result) {
196 HandleReadResult(result);
197 if (state_ == STATE_OPEN) {
198 DoRead();
202 void P2PSocketHostUdp::HandleReadResult(int result) {
203 DCHECK_EQ(STATE_OPEN, state_);
205 if (result > 0) {
206 std::vector<char> data(recv_buffer_->data(), recv_buffer_->data() + result);
208 if (!ContainsKey(connected_peers_, recv_address_)) {
209 P2PSocketHost::StunMessageType type;
210 bool stun = GetStunPacketType(&*data.begin(), data.size(), &type);
211 if ((stun && IsRequestOrResponse(type))) {
212 connected_peers_.insert(recv_address_);
213 } else if (!stun || type == STUN_DATA_INDICATION) {
214 LOG(ERROR) << "Received unexpected data packet from "
215 << recv_address_.ToString()
216 << " before STUN binding is finished.";
217 return;
221 message_sender_->Send(new P2PMsg_OnDataReceived(
222 id_, recv_address_, data, base::TimeTicks::Now()));
224 if (dump_incoming_rtp_packet_)
225 DumpRtpPacket(&data[0], data.size(), true);
226 } else if (result < 0 && !IsTransientError(result)) {
227 LOG(ERROR) << "Error when reading from UDP socket: " << result;
228 OnError();
232 void P2PSocketHostUdp::Send(const net::IPEndPoint& to,
233 const std::vector<char>& data,
234 const rtc::PacketOptions& options,
235 uint64 packet_id) {
236 if (!socket_) {
237 // The Send message may be sent after the an OnError message was
238 // sent by hasn't been processed the renderer.
239 return;
242 if (!ContainsKey(connected_peers_, to)) {
243 P2PSocketHost::StunMessageType type = P2PSocketHost::StunMessageType();
244 bool stun = GetStunPacketType(&*data.begin(), data.size(), &type);
245 if (!stun || type == STUN_DATA_INDICATION) {
246 LOG(ERROR) << "Page tried to send a data packet to " << to.ToString()
247 << " before STUN binding is finished.";
248 OnError();
249 return;
252 if (throttler_->DropNextPacket(data.size())) {
253 VLOG(0) << "STUN message is dropped due to high volume.";
254 // Do not reset socket.
255 return;
259 IncrementTotalSentPackets();
261 if (send_pending_) {
262 send_queue_.push_back(PendingPacket(to, data, options, packet_id));
263 IncrementDelayedBytes(data.size());
264 IncrementDelayedPackets();
265 } else {
266 // TODO(mallinath: Remove unnecessary memcpy in this case.
267 PendingPacket packet(to, data, options, packet_id);
268 DoSend(packet);
272 void P2PSocketHostUdp::DoSend(const PendingPacket& packet) {
273 TRACE_EVENT_ASYNC_STEP_INTO1("p2p", "Send", packet.id, "UdpAsyncSendTo",
274 "size", packet.size);
275 // Don't try to set DSCP in following conditions,
276 // 1. If the outgoing packet is set to DSCP_NO_CHANGE
277 // 2. If no change in DSCP value from last packet
278 // 3. If there is any error in setting DSCP on socket.
279 net::DiffServCodePoint dscp =
280 static_cast<net::DiffServCodePoint>(packet.packet_options.dscp);
281 if (dscp != net::DSCP_NO_CHANGE && last_dscp_ != dscp &&
282 last_dscp_ != net::DSCP_NO_CHANGE) {
283 int result = socket_->SetDiffServCodePoint(dscp);
284 if (result == net::OK) {
285 last_dscp_ = dscp;
286 } else if (!IsTransientError(result) && last_dscp_ != net::DSCP_CS0) {
287 // We receieved a non-transient error, and it seems we have
288 // not changed the DSCP in the past, disable DSCP as it unlikely
289 // to work in the future.
290 last_dscp_ = net::DSCP_NO_CHANGE;
294 uint64 tick_received = base::TimeTicks::Now().ToInternalValue();
296 packet_processing_helpers::ApplyPacketOptions(
297 packet.data->data(), packet.size, packet.packet_options, 0);
298 int result = socket_->SendTo(packet.data.get(),
299 packet.size,
300 packet.to,
301 base::Bind(&P2PSocketHostUdp::OnSend,
302 base::Unretained(this),
303 packet.id,
304 tick_received));
306 // sendto() may return an error, e.g. if we've received an ICMP Destination
307 // Unreachable message. When this happens try sending the same packet again,
308 // and just drop it if it fails again.
309 if (IsTransientError(result)) {
310 result = socket_->SendTo(packet.data.get(),
311 packet.size,
312 packet.to,
313 base::Bind(&P2PSocketHostUdp::OnSend,
314 base::Unretained(this),
315 packet.id,
316 tick_received));
319 if (result == net::ERR_IO_PENDING) {
320 send_pending_ = true;
321 } else {
322 HandleSendResult(packet.id, tick_received, result);
325 if (dump_outgoing_rtp_packet_)
326 DumpRtpPacket(packet.data->data(), packet.size, false);
329 void P2PSocketHostUdp::OnSend(uint64 packet_id,
330 uint64 tick_received,
331 int result) {
332 DCHECK(send_pending_);
333 DCHECK_NE(result, net::ERR_IO_PENDING);
335 send_pending_ = false;
337 HandleSendResult(packet_id, tick_received, result);
339 // Send next packets if we have them waiting in the buffer.
340 while (state_ == STATE_OPEN && !send_queue_.empty() && !send_pending_) {
341 PendingPacket packet = send_queue_.front();
342 DoSend(packet);
343 send_queue_.pop_front();
344 DecrementDelayedBytes(packet.size);
348 void P2PSocketHostUdp::HandleSendResult(uint64 packet_id,
349 uint64 tick_received,
350 int result) {
351 TRACE_EVENT_ASYNC_END1("p2p", "Send", packet_id,
352 "result", result);
353 if (result < 0) {
354 if (!IsTransientError(result)) {
355 LOG(ERROR) << "Error when sending data in UDP socket: " << result;
356 OnError();
357 return;
359 VLOG(0) << "sendto() has failed twice returning a "
360 " transient error " << GetTransientErrorName(result)
361 << ". Dropping the packet.";
364 // UMA to track the histograms from 1ms to 1 sec for how long a packet spends
365 // in the browser process.
366 UMA_HISTOGRAM_TIMES(
367 "WebRTC.SystemSendPacketDuration_UDP" /* name */,
368 base::TimeTicks::Now() -
369 base::TimeTicks::FromInternalValue(tick_received) /* sample */);
371 message_sender_->Send(
372 new P2PMsg_OnSendComplete(id_, P2PSendPacketMetrics(packet_id)));
375 P2PSocketHost* P2PSocketHostUdp::AcceptIncomingTcpConnection(
376 const net::IPEndPoint& remote_address, int id) {
377 NOTREACHED();
378 OnError();
379 return NULL;
382 bool P2PSocketHostUdp::SetOption(P2PSocketOption option, int value) {
383 DCHECK_EQ(STATE_OPEN, state_);
384 switch (option) {
385 case P2P_SOCKET_OPT_RCVBUF:
386 return socket_->SetReceiveBufferSize(value) == net::OK;
387 case P2P_SOCKET_OPT_SNDBUF:
388 // Ignore any following call to set the send buffer size if we're under
389 // experiment.
390 if (send_buffer_size_ > 0) {
391 return true;
393 return socket_->SetSendBufferSize(value) == net::OK;
394 case P2P_SOCKET_OPT_DSCP:
395 return (net::OK == socket_->SetDiffServCodePoint(
396 static_cast<net::DiffServCodePoint>(value))) ? true : false;
397 default:
398 NOTREACHED();
399 return false;
403 } // namespace content