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"
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"
27 static const int kBindRetries
= 10;
28 static const int kPortStart
= 1024;
29 static const int kPortEnd
= 65535;
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
> {
42 explicit Core(UDPSocketWin
* socket
);
44 // Start watching for the end of a read or write operation.
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_
;
63 friend class base::RefCounted
<Core
>;
65 class ReadDelegate
: public base::win::ObjectWatcher::Delegate
{
67 explicit ReadDelegate(Core
* core
) : core_(core
) {}
68 virtual ~ReadDelegate() {}
70 // base::ObjectWatcher::Delegate methods:
71 virtual void OnObjectSignaled(HANDLE object
);
77 class WriteDelegate
: public base::win::ObjectWatcher::Delegate
{
79 explicit WriteDelegate(Core
* core
) : core_(core
) {}
80 virtual ~WriteDelegate() {}
82 // base::ObjectWatcher::Delegate methods:
83 virtual void OnObjectSignaled(HANDLE object
);
91 // The socket that created this object.
92 UDPSocketWin
* socket_
;
94 // |reader_| handles the signals from |read_watcher_|.
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
)
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().
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().
140 write_watcher_
.StartWatching(write_overlapped_
.hEvent
, &writer_
);
143 void UDPSocketWin::Core::ReadDelegate::OnObjectSignaled(HANDLE object
) {
144 DCHECK_EQ(object
, core_
->read_overlapped_
.hEvent
);
146 core_
->socket_
->DidCompleteRead();
151 void UDPSocketWin::Core::WriteDelegate::OnObjectSignaled(HANDLE object
) {
152 DCHECK_EQ(object
, core_
->write_overlapped_
.hEvent
);
154 core_
->socket_
->DidCompleteWrite();
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
),
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
)) {
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() {
180 net_log_
.EndEvent(NetLog::TYPE_SOCKET_ALIVE
);
183 void UDPSocketWin::Close() {
184 DCHECK(CalledOnValidThread());
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
;
204 int UDPSocketWin::GetPeerAddress(IPEndPoint
* address
) const {
205 DCHECK(CalledOnValidThread());
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
))
218 remote_address_
.reset(address
.release());
221 *address
= *remote_address_
;
225 int UDPSocketWin::GetLocalAddress(IPEndPoint
* address
) const {
226 DCHECK(CalledOnValidThread());
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
))
239 local_address_
.reset(address
.release());
242 *address
= *local_address_
;
246 int UDPSocketWin::Read(IOBuffer
* buf
,
248 const CompletionCallback
& callback
) {
249 return RecvFrom(buf
, buf_len
, NULL
, callback
);
252 int UDPSocketWin::RecvFrom(IOBuffer
* buf
,
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
)
267 read_callback_
= callback
;
268 recv_from_address_
= address
;
269 return ERR_IO_PENDING
;
272 int UDPSocketWin::Write(IOBuffer
* buf
,
274 const CompletionCallback
& callback
) {
275 return SendToOrWrite(buf
, buf_len
, NULL
, callback
);
278 int UDPSocketWin::SendTo(IOBuffer
* buf
,
280 const IPEndPoint
& address
,
281 const CompletionCallback
& callback
) {
282 return SendToOrWrite(buf
, buf_len
, &address
, callback
);
285 int UDPSocketWin::SendToOrWrite(IOBuffer
* buf
,
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
)
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
);
312 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_UDP_CONNECT
, rv
);
316 int UDPSocketWin::InternalConnect(const IPEndPoint
& address
) {
317 DCHECK(!is_connected());
318 DCHECK(!remote_address_
.get());
319 int rv
= CreateSocket(address
);
323 if (bind_type_
== DatagramSocket::RANDOM_BIND
)
324 rv
= RandomBind(address
);
325 // else connect() does the DatagramSocket::DEFAULT_BIND
330 SockaddrStorage storage
;
331 if (!address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
334 rv
= connect(socket_
, storage
.addr
, storage
.addr_len
);
336 return MapSystemError(WSAGetLastError());
338 remote_address_
.reset(new IPEndPoint(address
));
342 int UDPSocketWin::Bind(const IPEndPoint
& address
) {
343 DCHECK(!is_connected());
344 int rv
= CreateSocket(address
);
347 rv
= SetSocketOptions();
350 rv
= DoBind(address
);
353 local_address_
.reset();
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);
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
;
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
;
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();
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();
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());
423 if (recv_from_address_
&& result
>= 0) {
424 if (!ReceiveAddressToIPEndpoint(recv_from_address_
))
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 {
435 net_log_
.AddEventWithNetErrorCode(NetLog::TYPE_UDP_RECEIVE_ERROR
, result
);
439 if (net_log_
.IsLoggingAllEvents()) {
440 // Get address for logging, if |address| is NULL.
442 bool is_address_valid
= ReceiveAddressToIPEndpoint(&address
);
444 NetLog::TYPE_UDP_BYTES_RECEIVED
,
445 CreateNetLogUDPDataTranferCallback(
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
,
469 const IPEndPoint
* address
) const {
471 net_log_
.AddEventWithNetErrorCode(NetLog::TYPE_UDP_SEND_ERROR
, result
);
475 if (net_log_
.IsLoggingAllEvents()) {
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
);
492 read_buffer
.buf
= buf
->data();
493 read_buffer
.len
= buf_len
;
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
);
502 if (ResetEventIfSignaled(core_
->read_overlapped_
.hEvent
)) {
505 if (address
&& result
>= 0) {
506 if (!ReceiveAddressToIPEndpoint(address
))
509 LogRead(result
, buf
->data());
513 int os_error
= WSAGetLastError();
514 if (os_error
!= WSA_IO_PENDING
) {
515 int result
= MapSystemError(os_error
);
516 LogRead(result
, NULL
);
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
;
533 storage
.addr_len
= 0;
535 if (!address
->ToSockAddr(addr
, &storage
.addr_len
)) {
536 int result
= ERR_FAILED
;
537 LogWrite(result
, NULL
, NULL
);
543 write_buffer
.buf
= buf
->data();
544 write_buffer
.len
= buf_len
;
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
);
552 if (ResetEventIfSignaled(core_
->write_overlapped_
.hEvent
)) {
554 LogWrite(result
, buf
->data(), address
);
558 int os_error
= WSAGetLastError();
559 if (os_error
!= WSA_IO_PENDING
) {
560 int result
= MapSystemError(os_error
);
561 LogWrite(result
, NULL
, NULL
);
566 core_
->WatchForWrite();
567 core_
->write_iobuffer_
= buf
;
568 return ERR_IO_PENDING
;
571 int UDPSocketWin::SetSocketOptions() {
573 if (socket_options_
& SOCKET_OPTION_REUSE_ADDRESS
) {
574 int rv
= setsockopt(socket_
, SOL_SOCKET
, SO_REUSEADDR
,
575 reinterpret_cast<const char*>(&true_value
),
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
),
585 return MapSystemError(errno
);
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
)
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
);