Add signalSyncPoint to the WebGraphicsContext3D command buffer impls.
[chromium-blink-merge.git] / net / udp / udp_socket_win.cc
blob5c6da9fc47c154dfd9e40ad682e980512eb19002
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 "net/udp/udp_socket_win.h"
7 #include <mstcpip.h>
9 #include "base/callback.h"
10 #include "base/logging.h"
11 #include "base/message_loop.h"
12 #include "base/metrics/histogram.h"
13 #include "base/metrics/stats_counters.h"
14 #include "base/posix/eintr_wrapper.h"
15 #include "base/rand_util.h"
16 #include "net/base/io_buffer.h"
17 #include "net/base/ip_endpoint.h"
18 #include "net/base/net_errors.h"
19 #include "net/base/net_log.h"
20 #include "net/base/net_util.h"
21 #include "net/base/winsock_init.h"
22 #include "net/base/winsock_util.h"
23 #include "net/udp/udp_net_log_parameters.h"
25 namespace {
27 static const int kBindRetries = 10;
28 static const int kPortStart = 1024;
29 static const int kPortEnd = 65535;
31 } // namespace net
33 namespace net {
35 // This class encapsulates all the state that has to be preserved as long as
36 // there is a network IO operation in progress. If the owner UDPSocketWin
37 // is destroyed while an operation is in progress, the Core is detached and it
38 // lives until the operation completes and the OS doesn't reference any resource
39 // declared on this class anymore.
40 class UDPSocketWin::Core : public base::RefCounted<Core> {
41 public:
42 explicit Core(UDPSocketWin* socket);
44 // Start watching for the end of a read or write operation.
45 void WatchForRead();
46 void WatchForWrite();
48 // The UDPSocketWin is going away.
49 void Detach() { socket_ = NULL; }
51 // The separate OVERLAPPED variables for asynchronous operation.
52 OVERLAPPED read_overlapped_;
53 OVERLAPPED write_overlapped_;
55 // The buffers used in Read() and Write().
56 scoped_refptr<IOBuffer> read_iobuffer_;
57 scoped_refptr<IOBuffer> write_iobuffer_;
59 // The address storage passed to WSARecvFrom().
60 SockaddrStorage recv_addr_storage_;
62 private:
63 friend class base::RefCounted<Core>;
65 class ReadDelegate : public base::win::ObjectWatcher::Delegate {
66 public:
67 explicit ReadDelegate(Core* core) : core_(core) {}
68 virtual ~ReadDelegate() {}
70 // base::ObjectWatcher::Delegate methods:
71 virtual void OnObjectSignaled(HANDLE object);
73 private:
74 Core* const core_;
77 class WriteDelegate : public base::win::ObjectWatcher::Delegate {
78 public:
79 explicit WriteDelegate(Core* core) : core_(core) {}
80 virtual ~WriteDelegate() {}
82 // base::ObjectWatcher::Delegate methods:
83 virtual void OnObjectSignaled(HANDLE object);
85 private:
86 Core* const core_;
89 ~Core();
91 // The socket that created this object.
92 UDPSocketWin* socket_;
94 // |reader_| handles the signals from |read_watcher_|.
95 ReadDelegate reader_;
96 // |writer_| handles the signals from |write_watcher_|.
97 WriteDelegate writer_;
99 // |read_watcher_| watches for events from Read().
100 base::win::ObjectWatcher read_watcher_;
101 // |write_watcher_| watches for events from Write();
102 base::win::ObjectWatcher write_watcher_;
104 DISALLOW_COPY_AND_ASSIGN(Core);
107 UDPSocketWin::Core::Core(UDPSocketWin* socket)
108 : socket_(socket),
109 ALLOW_THIS_IN_INITIALIZER_LIST(reader_(this)),
110 ALLOW_THIS_IN_INITIALIZER_LIST(writer_(this)) {
111 memset(&read_overlapped_, 0, sizeof(read_overlapped_));
112 memset(&write_overlapped_, 0, sizeof(write_overlapped_));
114 read_overlapped_.hEvent = WSACreateEvent();
115 write_overlapped_.hEvent = WSACreateEvent();
118 UDPSocketWin::Core::~Core() {
119 // Make sure the message loop is not watching this object anymore.
120 read_watcher_.StopWatching();
121 write_watcher_.StopWatching();
123 WSACloseEvent(read_overlapped_.hEvent);
124 memset(&read_overlapped_, 0xaf, sizeof(read_overlapped_));
125 WSACloseEvent(write_overlapped_.hEvent);
126 memset(&write_overlapped_, 0xaf, sizeof(write_overlapped_));
129 void UDPSocketWin::Core::WatchForRead() {
130 // We grab an extra reference because there is an IO operation in progress.
131 // Balanced in ReadDelegate::OnObjectSignaled().
132 AddRef();
133 read_watcher_.StartWatching(read_overlapped_.hEvent, &reader_);
136 void UDPSocketWin::Core::WatchForWrite() {
137 // We grab an extra reference because there is an IO operation in progress.
138 // Balanced in WriteDelegate::OnObjectSignaled().
139 AddRef();
140 write_watcher_.StartWatching(write_overlapped_.hEvent, &writer_);
143 void UDPSocketWin::Core::ReadDelegate::OnObjectSignaled(HANDLE object) {
144 DCHECK_EQ(object, core_->read_overlapped_.hEvent);
145 if (core_->socket_)
146 core_->socket_->DidCompleteRead();
148 core_->Release();
151 void UDPSocketWin::Core::WriteDelegate::OnObjectSignaled(HANDLE object) {
152 DCHECK_EQ(object, core_->write_overlapped_.hEvent);
153 if (core_->socket_)
154 core_->socket_->DidCompleteWrite();
156 core_->Release();
159 //-----------------------------------------------------------------------------
161 UDPSocketWin::UDPSocketWin(DatagramSocket::BindType bind_type,
162 const RandIntCallback& rand_int_cb,
163 net::NetLog* net_log,
164 const net::NetLog::Source& source)
165 : socket_(INVALID_SOCKET),
166 socket_options_(0),
167 bind_type_(bind_type),
168 rand_int_cb_(rand_int_cb),
169 recv_from_address_(NULL),
170 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_UDP_SOCKET)) {
171 EnsureWinsockInit();
172 net_log_.BeginEvent(NetLog::TYPE_SOCKET_ALIVE,
173 source.ToEventParametersCallback());
174 if (bind_type == DatagramSocket::RANDOM_BIND)
175 DCHECK(!rand_int_cb.is_null());
178 UDPSocketWin::~UDPSocketWin() {
179 Close();
180 net_log_.EndEvent(NetLog::TYPE_SOCKET_ALIVE);
183 void UDPSocketWin::Close() {
184 DCHECK(CalledOnValidThread());
186 if (!is_connected())
187 return;
189 // Zero out any pending read/write callback state.
190 read_callback_.Reset();
191 recv_from_address_ = NULL;
192 write_callback_.Reset();
194 base::TimeTicks start_time = base::TimeTicks::Now();
195 closesocket(socket_);
196 UMA_HISTOGRAM_TIMES("Net.UDPSocketWinClose",
197 base::TimeTicks::Now() - start_time);
198 socket_ = INVALID_SOCKET;
200 core_->Detach();
201 core_ = NULL;
204 int UDPSocketWin::GetPeerAddress(IPEndPoint* address) const {
205 DCHECK(CalledOnValidThread());
206 DCHECK(address);
207 if (!is_connected())
208 return ERR_SOCKET_NOT_CONNECTED;
210 // TODO(szym): Simplify. http://crbug.com/126152
211 if (!remote_address_.get()) {
212 SockaddrStorage storage;
213 if (getpeername(socket_, storage.addr, &storage.addr_len))
214 return MapSystemError(WSAGetLastError());
215 scoped_ptr<IPEndPoint> address(new IPEndPoint());
216 if (!address->FromSockAddr(storage.addr, storage.addr_len))
217 return ERR_FAILED;
218 remote_address_.reset(address.release());
221 *address = *remote_address_;
222 return OK;
225 int UDPSocketWin::GetLocalAddress(IPEndPoint* address) const {
226 DCHECK(CalledOnValidThread());
227 DCHECK(address);
228 if (!is_connected())
229 return ERR_SOCKET_NOT_CONNECTED;
231 // TODO(szym): Simplify. http://crbug.com/126152
232 if (!local_address_.get()) {
233 SockaddrStorage storage;
234 if (getsockname(socket_, storage.addr, &storage.addr_len))
235 return MapSystemError(WSAGetLastError());
236 scoped_ptr<IPEndPoint> address(new IPEndPoint());
237 if (!address->FromSockAddr(storage.addr, storage.addr_len))
238 return ERR_FAILED;
239 local_address_.reset(address.release());
242 *address = *local_address_;
243 return OK;
246 int UDPSocketWin::Read(IOBuffer* buf,
247 int buf_len,
248 const CompletionCallback& callback) {
249 return RecvFrom(buf, buf_len, NULL, callback);
252 int UDPSocketWin::RecvFrom(IOBuffer* buf,
253 int buf_len,
254 IPEndPoint* address,
255 const CompletionCallback& callback) {
256 DCHECK(CalledOnValidThread());
257 DCHECK_NE(INVALID_SOCKET, socket_);
258 DCHECK(read_callback_.is_null());
259 DCHECK(!recv_from_address_);
260 DCHECK(!callback.is_null()); // Synchronous operation not supported.
261 DCHECK_GT(buf_len, 0);
263 int nread = InternalRecvFrom(buf, buf_len, address);
264 if (nread != ERR_IO_PENDING)
265 return nread;
267 read_callback_ = callback;
268 recv_from_address_ = address;
269 return ERR_IO_PENDING;
272 int UDPSocketWin::Write(IOBuffer* buf,
273 int buf_len,
274 const CompletionCallback& callback) {
275 return SendToOrWrite(buf, buf_len, NULL, callback);
278 int UDPSocketWin::SendTo(IOBuffer* buf,
279 int buf_len,
280 const IPEndPoint& address,
281 const CompletionCallback& callback) {
282 return SendToOrWrite(buf, buf_len, &address, callback);
285 int UDPSocketWin::SendToOrWrite(IOBuffer* buf,
286 int buf_len,
287 const IPEndPoint* address,
288 const CompletionCallback& callback) {
289 DCHECK(CalledOnValidThread());
290 DCHECK_NE(INVALID_SOCKET, socket_);
291 DCHECK(write_callback_.is_null());
292 DCHECK(!callback.is_null()); // Synchronous operation not supported.
293 DCHECK_GT(buf_len, 0);
294 DCHECK(!send_to_address_.get());
296 int nwrite = InternalSendTo(buf, buf_len, address);
297 if (nwrite != ERR_IO_PENDING)
298 return nwrite;
300 if (address)
301 send_to_address_.reset(new IPEndPoint(*address));
302 write_callback_ = callback;
303 return ERR_IO_PENDING;
306 int UDPSocketWin::Connect(const IPEndPoint& address) {
307 net_log_.BeginEvent(NetLog::TYPE_UDP_CONNECT,
308 CreateNetLogUDPConnectCallback(&address));
309 int rv = InternalConnect(address);
310 if (rv != OK)
311 Close();
312 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_UDP_CONNECT, rv);
313 return rv;
316 int UDPSocketWin::InternalConnect(const IPEndPoint& address) {
317 DCHECK(!is_connected());
318 DCHECK(!remote_address_.get());
319 int rv = CreateSocket(address);
320 if (rv < 0)
321 return rv;
323 if (bind_type_ == DatagramSocket::RANDOM_BIND)
324 rv = RandomBind(address);
325 // else connect() does the DatagramSocket::DEFAULT_BIND
327 if (rv < 0)
328 return rv;
330 SockaddrStorage storage;
331 if (!address.ToSockAddr(storage.addr, &storage.addr_len))
332 return ERR_FAILED;
334 rv = connect(socket_, storage.addr, storage.addr_len);
335 if (rv < 0)
336 return MapSystemError(WSAGetLastError());
338 remote_address_.reset(new IPEndPoint(address));
339 return rv;
342 int UDPSocketWin::Bind(const IPEndPoint& address) {
343 DCHECK(!is_connected());
344 int rv = CreateSocket(address);
345 if (rv < 0)
346 return rv;
347 rv = SetSocketOptions();
348 if (rv < 0)
349 return rv;
350 rv = DoBind(address);
351 if (rv < 0)
352 return rv;
353 local_address_.reset();
354 return rv;
357 int UDPSocketWin::CreateSocket(const IPEndPoint& address) {
358 socket_ = WSASocket(address.GetSockAddrFamily(), SOCK_DGRAM, IPPROTO_UDP,
359 NULL, 0, WSA_FLAG_OVERLAPPED);
360 if (socket_ == INVALID_SOCKET)
361 return MapSystemError(WSAGetLastError());
362 core_ = new Core(this);
363 return OK;
366 bool UDPSocketWin::SetReceiveBufferSize(int32 size) {
367 DCHECK(CalledOnValidThread());
368 int rv = setsockopt(socket_, SOL_SOCKET, SO_RCVBUF,
369 reinterpret_cast<const char*>(&size), sizeof(size));
370 DCHECK(!rv) << "Could not set socket receive buffer size: " << errno;
371 return rv == 0;
374 bool UDPSocketWin::SetSendBufferSize(int32 size) {
375 DCHECK(CalledOnValidThread());
376 int rv = setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,
377 reinterpret_cast<const char*>(&size), sizeof(size));
378 DCHECK(!rv) << "Could not set socket send buffer size: " << errno;
379 return rv == 0;
382 void UDPSocketWin::AllowAddressReuse() {
383 DCHECK(CalledOnValidThread());
384 DCHECK(!is_connected());
386 socket_options_ |= SOCKET_OPTION_REUSE_ADDRESS;
389 void UDPSocketWin::AllowBroadcast() {
390 DCHECK(CalledOnValidThread());
391 DCHECK(!is_connected());
393 socket_options_ |= SOCKET_OPTION_BROADCAST;
396 void UDPSocketWin::DoReadCallback(int rv) {
397 DCHECK_NE(rv, ERR_IO_PENDING);
398 DCHECK(!read_callback_.is_null());
400 // since Run may result in Read being called, clear read_callback_ up front.
401 CompletionCallback c = read_callback_;
402 read_callback_.Reset();
403 c.Run(rv);
406 void UDPSocketWin::DoWriteCallback(int rv) {
407 DCHECK_NE(rv, ERR_IO_PENDING);
408 DCHECK(!write_callback_.is_null());
410 // since Run may result in Write being called, clear write_callback_ up front.
411 CompletionCallback c = write_callback_;
412 write_callback_.Reset();
413 c.Run(rv);
416 void UDPSocketWin::DidCompleteRead() {
417 DWORD num_bytes, flags;
418 BOOL ok = WSAGetOverlappedResult(socket_, &core_->read_overlapped_,
419 &num_bytes, FALSE, &flags);
420 WSAResetEvent(core_->read_overlapped_.hEvent);
421 int result = ok ? num_bytes : MapSystemError(WSAGetLastError());
422 // Convert address.
423 if (recv_from_address_ && result >= 0) {
424 if (!ReceiveAddressToIPEndpoint(recv_from_address_))
425 result = ERR_FAILED;
427 LogRead(result, core_->read_iobuffer_->data());
428 core_->read_iobuffer_ = NULL;
429 recv_from_address_ = NULL;
430 DoReadCallback(result);
433 void UDPSocketWin::LogRead(int result, const char* bytes) const {
434 if (result < 0) {
435 net_log_.AddEventWithNetErrorCode(NetLog::TYPE_UDP_RECEIVE_ERROR, result);
436 return;
439 if (net_log_.IsLoggingAllEvents()) {
440 // Get address for logging, if |address| is NULL.
441 IPEndPoint address;
442 bool is_address_valid = ReceiveAddressToIPEndpoint(&address);
443 net_log_.AddEvent(
444 NetLog::TYPE_UDP_BYTES_RECEIVED,
445 CreateNetLogUDPDataTranferCallback(
446 result, bytes,
447 is_address_valid ? &address : NULL));
450 base::StatsCounter read_bytes("udp.read_bytes");
451 read_bytes.Add(result);
454 void UDPSocketWin::DidCompleteWrite() {
455 DWORD num_bytes, flags;
456 BOOL ok = WSAGetOverlappedResult(socket_, &core_->write_overlapped_,
457 &num_bytes, FALSE, &flags);
458 WSAResetEvent(core_->write_overlapped_.hEvent);
459 int result = ok ? num_bytes : MapSystemError(WSAGetLastError());
460 LogWrite(result, core_->write_iobuffer_->data(), send_to_address_.get());
462 send_to_address_.reset();
463 core_->write_iobuffer_ = NULL;
464 DoWriteCallback(result);
467 void UDPSocketWin::LogWrite(int result,
468 const char* bytes,
469 const IPEndPoint* address) const {
470 if (result < 0) {
471 net_log_.AddEventWithNetErrorCode(NetLog::TYPE_UDP_SEND_ERROR, result);
472 return;
475 if (net_log_.IsLoggingAllEvents()) {
476 net_log_.AddEvent(
477 NetLog::TYPE_UDP_BYTES_SENT,
478 CreateNetLogUDPDataTranferCallback(result, bytes, address));
481 base::StatsCounter write_bytes("udp.write_bytes");
482 write_bytes.Add(result);
485 int UDPSocketWin::InternalRecvFrom(IOBuffer* buf, int buf_len,
486 IPEndPoint* address) {
487 DCHECK(!core_->read_iobuffer_);
488 SockaddrStorage& storage = core_->recv_addr_storage_;
489 storage.addr_len = sizeof(storage.addr_storage);
491 WSABUF read_buffer;
492 read_buffer.buf = buf->data();
493 read_buffer.len = buf_len;
495 DWORD flags = 0;
496 DWORD num;
497 CHECK_NE(INVALID_SOCKET, socket_);
498 AssertEventNotSignaled(core_->read_overlapped_.hEvent);
499 int rv = WSARecvFrom(socket_, &read_buffer, 1, &num, &flags, storage.addr,
500 &storage.addr_len, &core_->read_overlapped_, NULL);
501 if (rv == 0) {
502 if (ResetEventIfSignaled(core_->read_overlapped_.hEvent)) {
503 int result = num;
504 // Convert address.
505 if (address && result >= 0) {
506 if (!ReceiveAddressToIPEndpoint(address))
507 result = ERR_FAILED;
509 LogRead(result, buf->data());
510 return result;
512 } else {
513 int os_error = WSAGetLastError();
514 if (os_error != WSA_IO_PENDING) {
515 int result = MapSystemError(os_error);
516 LogRead(result, NULL);
517 return result;
520 core_->WatchForRead();
521 core_->read_iobuffer_ = buf;
522 return ERR_IO_PENDING;
525 int UDPSocketWin::InternalSendTo(IOBuffer* buf, int buf_len,
526 const IPEndPoint* address) {
527 DCHECK(!core_->write_iobuffer_);
528 SockaddrStorage storage;
529 struct sockaddr* addr = storage.addr;
530 // Convert address.
531 if (!address) {
532 addr = NULL;
533 storage.addr_len = 0;
534 } else {
535 if (!address->ToSockAddr(addr, &storage.addr_len)) {
536 int result = ERR_FAILED;
537 LogWrite(result, NULL, NULL);
538 return result;
542 WSABUF write_buffer;
543 write_buffer.buf = buf->data();
544 write_buffer.len = buf_len;
546 DWORD flags = 0;
547 DWORD num;
548 AssertEventNotSignaled(core_->write_overlapped_.hEvent);
549 int rv = WSASendTo(socket_, &write_buffer, 1, &num, flags,
550 addr, storage.addr_len, &core_->write_overlapped_, NULL);
551 if (rv == 0) {
552 if (ResetEventIfSignaled(core_->write_overlapped_.hEvent)) {
553 int result = num;
554 LogWrite(result, buf->data(), address);
555 return result;
557 } else {
558 int os_error = WSAGetLastError();
559 if (os_error != WSA_IO_PENDING) {
560 int result = MapSystemError(os_error);
561 LogWrite(result, NULL, NULL);
562 return result;
566 core_->WatchForWrite();
567 core_->write_iobuffer_ = buf;
568 return ERR_IO_PENDING;
571 int UDPSocketWin::SetSocketOptions() {
572 BOOL true_value = 1;
573 if (socket_options_ & SOCKET_OPTION_REUSE_ADDRESS) {
574 int rv = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
575 reinterpret_cast<const char*>(&true_value),
576 sizeof(true_value));
577 if (rv < 0)
578 return MapSystemError(errno);
580 if (socket_options_ & SOCKET_OPTION_BROADCAST) {
581 int rv = setsockopt(socket_, SOL_SOCKET, SO_BROADCAST,
582 reinterpret_cast<const char*>(&true_value),
583 sizeof(true_value));
584 if (rv < 0)
585 return MapSystemError(errno);
587 return OK;
590 int UDPSocketWin::DoBind(const IPEndPoint& address) {
591 SockaddrStorage storage;
592 if (!address.ToSockAddr(storage.addr, &storage.addr_len))
593 return ERR_UNEXPECTED;
594 int rv = bind(socket_, storage.addr, storage.addr_len);
595 return rv < 0 ? MapSystemError(WSAGetLastError()) : rv;
598 int UDPSocketWin::RandomBind(const IPEndPoint& address) {
599 DCHECK(bind_type_ == DatagramSocket::RANDOM_BIND && !rand_int_cb_.is_null());
601 // Construct IPAddressNumber of appropriate size (IPv4 or IPv6) of 0s.
602 IPAddressNumber ip(address.address().size());
604 for (int i = 0; i < kBindRetries; ++i) {
605 int rv = DoBind(IPEndPoint(ip, rand_int_cb_.Run(kPortStart, kPortEnd)));
606 if (rv == OK || rv != ERR_ADDRESS_IN_USE)
607 return rv;
609 return DoBind(IPEndPoint(ip, 0));
612 bool UDPSocketWin::ReceiveAddressToIPEndpoint(IPEndPoint* address) const {
613 SockaddrStorage& storage = core_->recv_addr_storage_;
614 return address->FromSockAddr(storage.addr, storage.addr_len);
617 } // namespace net