blob: 889e49537f8512608e3f1d94f44814a1f0b7935a [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/win32socketserver.h"
andresp@webrtc.orgff689be2015-02-12 11:54:26 +000012
13#include <algorithm>
14#include <ws2tcpip.h> // NOLINT
15
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020016#include "rtc_base/byteorder.h"
17#include "rtc_base/checks.h"
18#include "rtc_base/logging.h"
19#include "rtc_base/win32window.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020
21namespace rtc {
22
23///////////////////////////////////////////////////////////////////////////////
24// Win32Socket
25///////////////////////////////////////////////////////////////////////////////
26
27// TODO: Move this to a common place where PhysicalSocketServer can
28// share it.
29// Standard MTUs
Peter Boström0c4e06b2015-10-07 12:23:21 +020030static const uint16_t PACKET_MAXIMUMS[] = {
31 65535, // Theoretical maximum, Hyperchannel
32 32000, // Nothing
33 17914, // 16Mb IBM Token Ring
34 8166, // IEEE 802.4
35 // 4464 // IEEE 802.5 (4Mb max)
36 4352, // FDDI
37 // 2048, // Wideband Network
38 2002, // IEEE 802.5 (4Mb recommended)
39 // 1536, // Expermental Ethernet Networks
40 // 1500, // Ethernet, Point-to-Point (default)
41 1492, // IEEE 802.3
42 1006, // SLIP, ARPANET
43 // 576, // X.25 Networks
44 // 544, // DEC IP Portal
45 // 512, // NETBIOS
46 508, // IEEE 802/Source-Rt Bridge, ARCNET
47 296, // Point-to-Point (low delay)
48 68, // Official minimum
49 0, // End of list marker
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000050};
51
52static const int IP_HEADER_SIZE = 20u;
53static const int ICMP_HEADER_SIZE = 8u;
54static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
55
56// TODO: Enable for production builds also? Use FormatMessage?
tfarinaa41ab932015-10-30 16:08:48 -070057#if !defined(NDEBUG)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000058LPCSTR WSAErrorToString(int error, LPCSTR *description_result) {
59 LPCSTR string = "Unspecified";
60 LPCSTR description = "Unspecified description";
61 switch (error) {
62 case ERROR_SUCCESS:
63 string = "SUCCESS";
64 description = "Operation succeeded";
65 break;
66 case WSAEWOULDBLOCK:
67 string = "WSAEWOULDBLOCK";
68 description = "Using a non-blocking socket, will notify later";
69 break;
70 case WSAEACCES:
71 string = "WSAEACCES";
72 description = "Access denied, or sharing violation";
73 break;
74 case WSAEADDRNOTAVAIL:
75 string = "WSAEADDRNOTAVAIL";
76 description = "Address is not valid in this context";
77 break;
78 case WSAENETDOWN:
79 string = "WSAENETDOWN";
80 description = "Network is down";
81 break;
82 case WSAENETUNREACH:
83 string = "WSAENETUNREACH";
84 description = "Network is up, but unreachable";
85 break;
86 case WSAENETRESET:
87 string = "WSANETRESET";
88 description = "Connection has been reset due to keep-alive activity";
89 break;
90 case WSAECONNABORTED:
91 string = "WSAECONNABORTED";
92 description = "Aborted by host";
93 break;
94 case WSAECONNRESET:
95 string = "WSAECONNRESET";
96 description = "Connection reset by host";
97 break;
98 case WSAETIMEDOUT:
99 string = "WSAETIMEDOUT";
100 description = "Timed out, host failed to respond";
101 break;
102 case WSAECONNREFUSED:
103 string = "WSAECONNREFUSED";
104 description = "Host actively refused connection";
105 break;
106 case WSAEHOSTDOWN:
107 string = "WSAEHOSTDOWN";
108 description = "Host is down";
109 break;
110 case WSAEHOSTUNREACH:
111 string = "WSAEHOSTUNREACH";
112 description = "Host is unreachable";
113 break;
114 case WSAHOST_NOT_FOUND:
115 string = "WSAHOST_NOT_FOUND";
116 description = "No such host is known";
117 break;
118 }
119 if (description_result) {
120 *description_result = description;
121 }
122 return string;
123}
124
125void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {
126 LPCSTR description_string;
127 LPCSTR error_string = WSAErrorToString(error, &description_string);
128 LOG(LS_INFO) << context << " = " << error
129 << " (" << error_string << ":" << description_string << ") ["
130 << address.ToString() << "]";
131}
132#else
133void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {}
134#endif
135
136/////////////////////////////////////////////////////////////////////////////
137// Win32Socket::EventSink
138/////////////////////////////////////////////////////////////////////////////
139
140#define WM_SOCKETNOTIFY (WM_USER + 50)
141#define WM_DNSNOTIFY (WM_USER + 51)
142
143struct Win32Socket::DnsLookup {
144 HANDLE handle;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200145 uint16_t port;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146 char buffer[MAXGETHOSTSTRUCT];
147};
148
149class Win32Socket::EventSink : public Win32Window {
150 public:
151 explicit EventSink(Win32Socket * parent) : parent_(parent) { }
152
153 void Dispose();
154
155 virtual bool OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam,
156 LRESULT& result);
157 virtual void OnNcDestroy();
158
159 private:
160 bool OnSocketNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result);
161 bool OnDnsNotify(WPARAM wParam, LPARAM lParam, LRESULT& result);
162
163 Win32Socket * parent_;
164};
165
166void Win32Socket::EventSink::Dispose() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800167 parent_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000168 if (::IsWindow(handle())) {
169 ::DestroyWindow(handle());
170 } else {
171 delete this;
172 }
173}
174
175bool Win32Socket::EventSink::OnMessage(UINT uMsg, WPARAM wParam,
176 LPARAM lParam, LRESULT& result) {
177 switch (uMsg) {
178 case WM_SOCKETNOTIFY:
179 case WM_TIMER:
180 return OnSocketNotify(uMsg, wParam, lParam, result);
181 case WM_DNSNOTIFY:
182 return OnDnsNotify(wParam, lParam, result);
183 }
184 return false;
185}
186
187bool Win32Socket::EventSink::OnSocketNotify(UINT uMsg, WPARAM wParam,
188 LPARAM lParam, LRESULT& result) {
189 result = 0;
190
191 int wsa_event = WSAGETSELECTEVENT(lParam);
192 int wsa_error = WSAGETSELECTERROR(lParam);
193
194 // Treat connect timeouts as close notifications
195 if (uMsg == WM_TIMER) {
196 wsa_event = FD_CLOSE;
197 wsa_error = WSAETIMEDOUT;
198 }
199
200 if (parent_)
201 parent_->OnSocketNotify(static_cast<SOCKET>(wParam), wsa_event, wsa_error);
202 return true;
203}
204
205bool Win32Socket::EventSink::OnDnsNotify(WPARAM wParam, LPARAM lParam,
206 LRESULT& result) {
207 result = 0;
208
209 int error = WSAGETASYNCERROR(lParam);
210 if (parent_)
211 parent_->OnDnsNotify(reinterpret_cast<HANDLE>(wParam), error);
212 return true;
213}
214
215void Win32Socket::EventSink::OnNcDestroy() {
216 if (parent_) {
217 LOG(LS_ERROR) << "EventSink hwnd is being destroyed, but the event sink"
218 " hasn't yet been disposed.";
219 } else {
220 delete this;
221 }
222}
223
224/////////////////////////////////////////////////////////////////////////////
225// Win32Socket
226/////////////////////////////////////////////////////////////////////////////
227
228Win32Socket::Win32Socket()
deadbeef37f5ecf2017-02-27 14:06:41 -0800229 : socket_(INVALID_SOCKET),
230 error_(0),
231 state_(CS_CLOSED),
232 connect_time_(0),
233 closing_(false),
234 close_error_(0),
235 sink_(nullptr),
236 dns_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237
238Win32Socket::~Win32Socket() {
239 Close();
240}
241
242bool Win32Socket::CreateT(int family, int type) {
243 Close();
244 int proto = (SOCK_DGRAM == type) ? IPPROTO_UDP : IPPROTO_TCP;
deadbeef37f5ecf2017-02-27 14:06:41 -0800245 socket_ = ::WSASocket(family, type, proto, nullptr, 0, 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246 if (socket_ == INVALID_SOCKET) {
247 UpdateLastError();
248 return false;
249 }
250 if ((SOCK_DGRAM == type) && !SetAsync(FD_READ | FD_WRITE)) {
251 return false;
252 }
253 return true;
254}
255
256int Win32Socket::Attach(SOCKET s) {
nisseede5da42017-01-12 05:15:36 -0800257 RTC_DCHECK(socket_ == INVALID_SOCKET);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000258 if (socket_ != INVALID_SOCKET)
259 return SOCKET_ERROR;
260
nisseede5da42017-01-12 05:15:36 -0800261 RTC_DCHECK(s != INVALID_SOCKET);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262 if (s == INVALID_SOCKET)
263 return SOCKET_ERROR;
264
265 socket_ = s;
266 state_ = CS_CONNECTED;
267
268 if (!SetAsync(FD_READ | FD_WRITE | FD_CLOSE))
269 return SOCKET_ERROR;
270
271 return 0;
272}
273
274void Win32Socket::SetTimeout(int ms) {
275 if (sink_)
276 ::SetTimer(sink_->handle(), 1, ms, 0);
277}
278
279SocketAddress Win32Socket::GetLocalAddress() const {
280 sockaddr_storage addr = {0};
281 socklen_t addrlen = sizeof(addr);
282 int result = ::getsockname(socket_, reinterpret_cast<sockaddr*>(&addr),
283 &addrlen);
284 SocketAddress address;
285 if (result >= 0) {
286 SocketAddressFromSockAddrStorage(addr, &address);
287 } else {
288 LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
289 << socket_;
290 }
291 return address;
292}
293
294SocketAddress Win32Socket::GetRemoteAddress() const {
295 sockaddr_storage addr = {0};
296 socklen_t addrlen = sizeof(addr);
297 int result = ::getpeername(socket_, reinterpret_cast<sockaddr*>(&addr),
298 &addrlen);
299 SocketAddress address;
300 if (result >= 0) {
301 SocketAddressFromSockAddrStorage(addr, &address);
302 } else {
303 LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket="
304 << socket_;
305 }
306 return address;
307}
308
309int Win32Socket::Bind(const SocketAddress& addr) {
nisseede5da42017-01-12 05:15:36 -0800310 RTC_DCHECK(socket_ != INVALID_SOCKET);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000311 if (socket_ == INVALID_SOCKET)
312 return SOCKET_ERROR;
313
314 sockaddr_storage saddr;
315 size_t len = addr.ToSockAddrStorage(&saddr);
316 int err = ::bind(socket_,
317 reinterpret_cast<sockaddr*>(&saddr),
318 static_cast<int>(len));
319 UpdateLastError();
320 return err;
321}
322
323int Win32Socket::Connect(const SocketAddress& addr) {
324 if (state_ != CS_CLOSED) {
325 SetError(EALREADY);
326 return SOCKET_ERROR;
327 }
328
329 if (!addr.IsUnresolvedIP()) {
330 return DoConnect(addr);
331 }
332
333 LOG_F(LS_INFO) << "async dns lookup (" << addr.hostname() << ")";
334 DnsLookup * dns = new DnsLookup;
335 if (!sink_) {
336 // Explicitly create the sink ourselves here; we can't rely on SetAsync
337 // because we don't have a socket_ yet.
338 CreateSink();
339 }
340 // TODO: Replace with IPv6 compatible lookup.
341 dns->handle = WSAAsyncGetHostByName(sink_->handle(), WM_DNSNOTIFY,
342 addr.hostname().c_str(), dns->buffer,
343 sizeof(dns->buffer));
344
345 if (!dns->handle) {
346 LOG_F(LS_ERROR) << "WSAAsyncGetHostByName error: " << WSAGetLastError();
347 delete dns;
348 UpdateLastError();
349 Close();
350 return SOCKET_ERROR;
351 }
352
353 dns->port = addr.port();
354 dns_ = dns;
355 state_ = CS_CONNECTING;
356 return 0;
357}
358
359int Win32Socket::DoConnect(const SocketAddress& addr) {
360 if ((socket_ == INVALID_SOCKET) && !CreateT(addr.family(), SOCK_STREAM)) {
361 return SOCKET_ERROR;
362 }
363 if (!SetAsync(FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE)) {
364 return SOCKET_ERROR;
365 }
366
367 sockaddr_storage saddr = {0};
368 size_t len = addr.ToSockAddrStorage(&saddr);
369 connect_time_ = Time();
370 int result = connect(socket_,
371 reinterpret_cast<SOCKADDR*>(&saddr),
372 static_cast<int>(len));
373 if (result != SOCKET_ERROR) {
374 state_ = CS_CONNECTED;
375 } else {
376 int code = WSAGetLastError();
377 if (code == WSAEWOULDBLOCK) {
378 state_ = CS_CONNECTING;
379 } else {
380 ReportWSAError("WSAAsync:connect", code, addr);
381 error_ = code;
382 Close();
383 return SOCKET_ERROR;
384 }
385 }
386 addr_ = addr;
387
388 return 0;
389}
390
391int Win32Socket::GetError() const {
392 return error_;
393}
394
395void Win32Socket::SetError(int error) {
396 error_ = error;
397}
398
399Socket::ConnState Win32Socket::GetState() const {
400 return state_;
401}
402
403int Win32Socket::GetOption(Option opt, int* value) {
404 int slevel;
405 int sopt;
406 if (TranslateOption(opt, &slevel, &sopt) == -1)
407 return -1;
408
409 char* p = reinterpret_cast<char*>(value);
410 int optlen = sizeof(value);
411 return ::getsockopt(socket_, slevel, sopt, p, &optlen);
412}
413
414int Win32Socket::SetOption(Option opt, int value) {
415 int slevel;
416 int sopt;
417 if (TranslateOption(opt, &slevel, &sopt) == -1)
418 return -1;
419
420 const char* p = reinterpret_cast<const char*>(&value);
421 return ::setsockopt(socket_, slevel, sopt, p, sizeof(value));
422}
423
424int Win32Socket::Send(const void* buffer, size_t length) {
425 int sent = ::send(socket_,
426 reinterpret_cast<const char*>(buffer),
427 static_cast<int>(length),
428 0);
429 UpdateLastError();
430 return sent;
431}
432
433int Win32Socket::SendTo(const void* buffer, size_t length,
434 const SocketAddress& addr) {
435 sockaddr_storage saddr;
436 size_t addr_len = addr.ToSockAddrStorage(&saddr);
437 int sent = ::sendto(socket_, reinterpret_cast<const char*>(buffer),
438 static_cast<int>(length), 0,
439 reinterpret_cast<sockaddr*>(&saddr),
440 static_cast<int>(addr_len));
441 UpdateLastError();
442 return sent;
443}
444
Stefan Holmer9131efd2016-05-23 18:19:26 +0200445int Win32Socket::Recv(void* buffer, size_t length, int64_t* timestamp) {
446 if (timestamp) {
447 *timestamp = -1;
448 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000449 int received = ::recv(socket_, static_cast<char*>(buffer),
450 static_cast<int>(length), 0);
451 UpdateLastError();
452 if (closing_ && received <= static_cast<int>(length))
453 PostClosed();
454 return received;
455}
456
Stefan Holmer9131efd2016-05-23 18:19:26 +0200457int Win32Socket::RecvFrom(void* buffer,
458 size_t length,
459 SocketAddress* out_addr,
460 int64_t* timestamp) {
461 if (timestamp) {
462 *timestamp = -1;
463 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000464 sockaddr_storage saddr;
465 socklen_t addr_len = sizeof(saddr);
466 int received = ::recvfrom(socket_, static_cast<char*>(buffer),
467 static_cast<int>(length), 0,
468 reinterpret_cast<sockaddr*>(&saddr), &addr_len);
469 UpdateLastError();
470 if (received != SOCKET_ERROR)
471 SocketAddressFromSockAddrStorage(saddr, out_addr);
472 if (closing_ && received <= static_cast<int>(length))
473 PostClosed();
474 return received;
475}
476
477int Win32Socket::Listen(int backlog) {
478 int err = ::listen(socket_, backlog);
479 if (!SetAsync(FD_ACCEPT))
480 return SOCKET_ERROR;
481
482 UpdateLastError();
483 if (err == 0)
484 state_ = CS_CONNECTING;
485 return err;
486}
487
488Win32Socket* Win32Socket::Accept(SocketAddress* out_addr) {
489 sockaddr_storage saddr;
490 socklen_t addr_len = sizeof(saddr);
491 SOCKET s = ::accept(socket_, reinterpret_cast<sockaddr*>(&saddr), &addr_len);
492 UpdateLastError();
493 if (s == INVALID_SOCKET)
deadbeef37f5ecf2017-02-27 14:06:41 -0800494 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000495 if (out_addr)
496 SocketAddressFromSockAddrStorage(saddr, out_addr);
497 Win32Socket* socket = new Win32Socket;
498 if (0 == socket->Attach(s))
499 return socket;
500 delete socket;
deadbeef37f5ecf2017-02-27 14:06:41 -0800501 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000502}
503
504int Win32Socket::Close() {
505 int err = 0;
506 if (socket_ != INVALID_SOCKET) {
507 err = ::closesocket(socket_);
508 socket_ = INVALID_SOCKET;
509 closing_ = false;
510 close_error_ = 0;
511 UpdateLastError();
512 }
513 if (dns_) {
514 WSACancelAsyncRequest(dns_->handle);
515 delete dns_;
deadbeef37f5ecf2017-02-27 14:06:41 -0800516 dns_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000517 }
518 if (sink_) {
519 sink_->Dispose();
deadbeef37f5ecf2017-02-27 14:06:41 -0800520 sink_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000521 }
522 addr_.Clear();
523 state_ = CS_CLOSED;
524 return err;
525}
526
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000527void Win32Socket::CreateSink() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800528 RTC_DCHECK(nullptr == sink_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000529
530 // Create window
531 sink_ = new EventSink(this);
deadbeef37f5ecf2017-02-27 14:06:41 -0800532 sink_->Create(nullptr, L"EventSink", 0, 0, 0, 0, 10, 10);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000533}
534
535bool Win32Socket::SetAsync(int events) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800536 if (nullptr == sink_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000537 CreateSink();
deadbeef37f5ecf2017-02-27 14:06:41 -0800538 RTC_DCHECK(nullptr != sink_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000539 }
540
541 // start the async select
542 if (WSAAsyncSelect(socket_, sink_->handle(), WM_SOCKETNOTIFY, events)
543 == SOCKET_ERROR) {
544 UpdateLastError();
545 Close();
546 return false;
547 }
548
549 return true;
550}
551
552bool Win32Socket::HandleClosed(int close_error) {
553 // WM_CLOSE will be received before all data has been read, so we need to
554 // hold on to it until the read buffer has been drained.
555 char ch;
556 closing_ = true;
557 close_error_ = close_error;
558 return (::recv(socket_, &ch, 1, MSG_PEEK) <= 0);
559}
560
561void Win32Socket::PostClosed() {
562 // If we see that the buffer is indeed drained, then send the close.
563 closing_ = false;
564 ::PostMessage(sink_->handle(), WM_SOCKETNOTIFY,
565 socket_, WSAMAKESELECTREPLY(FD_CLOSE, close_error_));
566}
567
568void Win32Socket::UpdateLastError() {
569 error_ = WSAGetLastError();
570}
571
572int Win32Socket::TranslateOption(Option opt, int* slevel, int* sopt) {
573 switch (opt) {
574 case OPT_DONTFRAGMENT:
575 *slevel = IPPROTO_IP;
576 *sopt = IP_DONTFRAGMENT;
577 break;
578 case OPT_RCVBUF:
579 *slevel = SOL_SOCKET;
580 *sopt = SO_RCVBUF;
581 break;
582 case OPT_SNDBUF:
583 *slevel = SOL_SOCKET;
584 *sopt = SO_SNDBUF;
585 break;
586 case OPT_NODELAY:
587 *slevel = IPPROTO_TCP;
588 *sopt = TCP_NODELAY;
589 break;
590 case OPT_DSCP:
591 LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
592 return -1;
593 default:
nissec80e7412017-01-11 05:56:46 -0800594 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000595 return -1;
596 }
597 return 0;
598}
599
600void Win32Socket::OnSocketNotify(SOCKET socket, int event, int error) {
601 // Ignore events if we're already closed.
602 if (socket != socket_)
603 return;
604
605 error_ = error;
606 switch (event) {
607 case FD_CONNECT:
608 if (error != ERROR_SUCCESS) {
609 ReportWSAError("WSAAsync:connect notify", error, addr_);
tfarinaa41ab932015-10-30 16:08:48 -0700610#if !defined(NDEBUG)
Honghai Zhang82d78622016-05-06 11:29:15 -0700611 int64_t duration = TimeSince(connect_time_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000612 LOG(LS_INFO) << "WSAAsync:connect error (" << duration
613 << " ms), faking close";
614#endif
615 state_ = CS_CLOSED;
616 // If you get an error connecting, close doesn't really do anything
617 // and it certainly doesn't send back any close notification, but
618 // we really only maintain a few states, so it is easiest to get
619 // back into a known state by pretending that a close happened, even
620 // though the connect event never did occur.
621 SignalCloseEvent(this, error);
622 } else {
tfarinaa41ab932015-10-30 16:08:48 -0700623#if !defined(NDEBUG)
Honghai Zhang82d78622016-05-06 11:29:15 -0700624 int64_t duration = TimeSince(connect_time_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000625 LOG(LS_INFO) << "WSAAsync:connect (" << duration << " ms)";
626#endif
627 state_ = CS_CONNECTED;
628 SignalConnectEvent(this);
629 }
630 break;
631
632 case FD_ACCEPT:
633 case FD_READ:
634 if (error != ERROR_SUCCESS) {
635 ReportWSAError("WSAAsync:read notify", error, addr_);
636 } else {
637 SignalReadEvent(this);
638 }
639 break;
640
641 case FD_WRITE:
642 if (error != ERROR_SUCCESS) {
643 ReportWSAError("WSAAsync:write notify", error, addr_);
644 } else {
645 SignalWriteEvent(this);
646 }
647 break;
648
649 case FD_CLOSE:
650 if (HandleClosed(error)) {
651 ReportWSAError("WSAAsync:close notify", error, addr_);
652 state_ = CS_CLOSED;
653 SignalCloseEvent(this, error);
654 }
655 break;
656 }
657}
658
659void Win32Socket::OnDnsNotify(HANDLE task, int error) {
660 if (!dns_ || dns_->handle != task)
661 return;
662
Peter Boström0c4e06b2015-10-07 12:23:21 +0200663 uint32_t ip = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000664 if (error == 0) {
665 hostent* pHost = reinterpret_cast<hostent*>(dns_->buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200666 uint32_t net_ip = *reinterpret_cast<uint32_t*>(pHost->h_addr_list[0]);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000667 ip = NetworkToHost32(net_ip);
668 }
669
670 LOG_F(LS_INFO) << "(" << IPAddress(ip).ToSensitiveString()
671 << ", " << error << ")";
672
673 if (error == 0) {
674 SocketAddress address(ip, dns_->port);
675 error = DoConnect(address);
676 } else {
677 Close();
678 }
679
680 if (error) {
681 error_ = error;
682 SignalCloseEvent(this, error_);
683 } else {
684 delete dns_;
deadbeef37f5ecf2017-02-27 14:06:41 -0800685 dns_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000686 }
687}
688
689///////////////////////////////////////////////////////////////////////////////
690// Win32SocketServer
691// Provides cricket base services on top of a win32 gui thread
692///////////////////////////////////////////////////////////////////////////////
693
694static UINT s_wm_wakeup_id = 0;
695const TCHAR Win32SocketServer::kWindowName[] = L"libjingle Message Window";
696
nisse7eaa4ea2017-05-08 05:25:41 -0700697Win32SocketServer::Win32SocketServer()
698 : wnd_(this),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000699 posted_(false),
deadbeef37f5ecf2017-02-27 14:06:41 -0800700 hdlg_(nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000701 if (s_wm_wakeup_id == 0)
702 s_wm_wakeup_id = RegisterWindowMessage(L"WM_WAKEUP");
deadbeef37f5ecf2017-02-27 14:06:41 -0800703 if (!wnd_.Create(nullptr, kWindowName, 0, 0, 0, 0, 0, 0)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000704 LOG_GLE(LS_ERROR) << "Failed to create message window.";
705 }
706}
707
708Win32SocketServer::~Win32SocketServer() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800709 if (wnd_.handle() != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000710 KillTimer(wnd_.handle(), 1);
711 wnd_.Destroy();
712 }
713}
714
715Socket* Win32SocketServer::CreateSocket(int type) {
716 return CreateSocket(AF_INET, type);
717}
718
719Socket* Win32SocketServer::CreateSocket(int family, int type) {
720 return CreateAsyncSocket(family, type);
721}
722
723AsyncSocket* Win32SocketServer::CreateAsyncSocket(int type) {
724 return CreateAsyncSocket(AF_INET, type);
725}
726
727AsyncSocket* Win32SocketServer::CreateAsyncSocket(int family, int type) {
728 Win32Socket* socket = new Win32Socket;
729 if (socket->CreateT(family, type)) {
730 return socket;
731 }
732 delete socket;
deadbeef37f5ecf2017-02-27 14:06:41 -0800733 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000734}
735
736void Win32SocketServer::SetMessageQueue(MessageQueue* queue) {
737 message_queue_ = queue;
738}
739
740bool Win32SocketServer::Wait(int cms, bool process_io) {
741 BOOL b;
742 if (process_io) {
743 // Spin the Win32 message pump at least once, and as long as requested.
744 // This is the Thread::ProcessMessages case.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200745 uint32_t start = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000746 do {
747 MSG msg;
deadbeef37f5ecf2017-02-27 14:06:41 -0800748 SetTimer(wnd_.handle(), 0, cms, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000749 // Get the next available message. If we have a modeless dialog, give
750 // give the message to IsDialogMessage, which will return true if it
751 // was a message for the dialog that it handled internally.
752 // Otherwise, dispatch as usual via Translate/DispatchMessage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800753 b = GetMessage(&msg, nullptr, 0, 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000754 if (b == -1) {
755 LOG_GLE(LS_ERROR) << "GetMessage failed.";
756 return false;
757 } else if(b) {
758 if (!hdlg_ || !IsDialogMessage(hdlg_, &msg)) {
759 TranslateMessage(&msg);
760 DispatchMessage(&msg);
761 }
762 }
763 KillTimer(wnd_.handle(), 0);
764 } while (b && TimeSince(start) < cms);
765 } else if (cms != 0) {
766 // Sit and wait forever for a WakeUp. This is the Thread::Send case.
nisseede5da42017-01-12 05:15:36 -0800767 RTC_DCHECK(cms == -1);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000768 MSG msg;
deadbeef37f5ecf2017-02-27 14:06:41 -0800769 b = GetMessage(&msg, nullptr, s_wm_wakeup_id, s_wm_wakeup_id);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000770 {
771 CritScope scope(&cs_);
772 posted_ = false;
773 }
774 } else {
775 // No-op (cms == 0 && !process_io). This is the Pump case.
776 b = TRUE;
777 }
778 return (b != FALSE);
779}
780
781void Win32SocketServer::WakeUp() {
782 if (wnd_.handle()) {
783 // Set the "message pending" flag, if not already set.
784 {
785 CritScope scope(&cs_);
786 if (posted_)
787 return;
788 posted_ = true;
789 }
790
791 PostMessage(wnd_.handle(), s_wm_wakeup_id, 0, 0);
792 }
793}
794
795void Win32SocketServer::Pump() {
796 // Clear the "message pending" flag.
797 {
798 CritScope scope(&cs_);
799 posted_ = false;
800 }
801
802 // Dispatch all the messages that are currently in our queue. If new messages
803 // are posted during the dispatch, they will be handled in the next Pump.
804 // We use max(1, ...) to make sure we try to dispatch at least once, since
805 // this allow us to process "sent" messages, not included in the size() count.
806 Message msg;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000807 for (size_t max_messages_to_process =
808 std::max<size_t>(1, message_queue_->size());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000809 max_messages_to_process > 0 && message_queue_->Get(&msg, 0, false);
810 --max_messages_to_process) {
811 message_queue_->Dispatch(&msg);
812 }
813
814 // Anything remaining?
815 int delay = message_queue_->GetDelay();
816 if (delay == -1) {
817 KillTimer(wnd_.handle(), 1);
818 } else {
deadbeef37f5ecf2017-02-27 14:06:41 -0800819 SetTimer(wnd_.handle(), 1, delay, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000820 }
821}
822
823bool Win32SocketServer::MessageWindow::OnMessage(UINT wm, WPARAM wp,
824 LPARAM lp, LRESULT& lr) {
825 bool handled = false;
826 if (wm == s_wm_wakeup_id || (wm == WM_TIMER && wp == 1)) {
827 ss_->Pump();
828 lr = 0;
829 handled = true;
830 }
831 return handled;
832}
833
834} // namespace rtc