blob: 72d352d3988485b143a319ac6329e0fe170ebe3b [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
Steve Anton9de3aac2017-10-24 10:08:26 -0700155 bool OnMessage(UINT uMsg,
156 WPARAM wParam,
157 LPARAM lParam,
158 LRESULT& result) override;
159 void OnNcDestroy() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000160
161 private:
162 bool OnSocketNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result);
163 bool OnDnsNotify(WPARAM wParam, LPARAM lParam, LRESULT& result);
164
165 Win32Socket * parent_;
166};
167
168void Win32Socket::EventSink::Dispose() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800169 parent_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170 if (::IsWindow(handle())) {
171 ::DestroyWindow(handle());
172 } else {
173 delete this;
174 }
175}
176
177bool Win32Socket::EventSink::OnMessage(UINT uMsg, WPARAM wParam,
178 LPARAM lParam, LRESULT& result) {
179 switch (uMsg) {
180 case WM_SOCKETNOTIFY:
181 case WM_TIMER:
182 return OnSocketNotify(uMsg, wParam, lParam, result);
183 case WM_DNSNOTIFY:
184 return OnDnsNotify(wParam, lParam, result);
185 }
186 return false;
187}
188
189bool Win32Socket::EventSink::OnSocketNotify(UINT uMsg, WPARAM wParam,
190 LPARAM lParam, LRESULT& result) {
191 result = 0;
192
193 int wsa_event = WSAGETSELECTEVENT(lParam);
194 int wsa_error = WSAGETSELECTERROR(lParam);
195
196 // Treat connect timeouts as close notifications
197 if (uMsg == WM_TIMER) {
198 wsa_event = FD_CLOSE;
199 wsa_error = WSAETIMEDOUT;
200 }
201
202 if (parent_)
203 parent_->OnSocketNotify(static_cast<SOCKET>(wParam), wsa_event, wsa_error);
204 return true;
205}
206
207bool Win32Socket::EventSink::OnDnsNotify(WPARAM wParam, LPARAM lParam,
208 LRESULT& result) {
209 result = 0;
210
211 int error = WSAGETASYNCERROR(lParam);
212 if (parent_)
213 parent_->OnDnsNotify(reinterpret_cast<HANDLE>(wParam), error);
214 return true;
215}
216
217void Win32Socket::EventSink::OnNcDestroy() {
218 if (parent_) {
219 LOG(LS_ERROR) << "EventSink hwnd is being destroyed, but the event sink"
220 " hasn't yet been disposed.";
221 } else {
222 delete this;
223 }
224}
225
226/////////////////////////////////////////////////////////////////////////////
227// Win32Socket
228/////////////////////////////////////////////////////////////////////////////
229
230Win32Socket::Win32Socket()
deadbeef37f5ecf2017-02-27 14:06:41 -0800231 : socket_(INVALID_SOCKET),
232 error_(0),
233 state_(CS_CLOSED),
234 connect_time_(0),
235 closing_(false),
236 close_error_(0),
237 sink_(nullptr),
238 dns_(nullptr) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000239
240Win32Socket::~Win32Socket() {
241 Close();
242}
243
244bool Win32Socket::CreateT(int family, int type) {
245 Close();
246 int proto = (SOCK_DGRAM == type) ? IPPROTO_UDP : IPPROTO_TCP;
deadbeef37f5ecf2017-02-27 14:06:41 -0800247 socket_ = ::WSASocket(family, type, proto, nullptr, 0, 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000248 if (socket_ == INVALID_SOCKET) {
249 UpdateLastError();
250 return false;
251 }
252 if ((SOCK_DGRAM == type) && !SetAsync(FD_READ | FD_WRITE)) {
253 return false;
254 }
255 return true;
256}
257
258int Win32Socket::Attach(SOCKET s) {
nisseede5da42017-01-12 05:15:36 -0800259 RTC_DCHECK(socket_ == INVALID_SOCKET);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260 if (socket_ != INVALID_SOCKET)
261 return SOCKET_ERROR;
262
nisseede5da42017-01-12 05:15:36 -0800263 RTC_DCHECK(s != INVALID_SOCKET);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264 if (s == INVALID_SOCKET)
265 return SOCKET_ERROR;
266
267 socket_ = s;
268 state_ = CS_CONNECTED;
269
270 if (!SetAsync(FD_READ | FD_WRITE | FD_CLOSE))
271 return SOCKET_ERROR;
272
273 return 0;
274}
275
276void Win32Socket::SetTimeout(int ms) {
277 if (sink_)
278 ::SetTimer(sink_->handle(), 1, ms, 0);
279}
280
281SocketAddress Win32Socket::GetLocalAddress() const {
282 sockaddr_storage addr = {0};
283 socklen_t addrlen = sizeof(addr);
284 int result = ::getsockname(socket_, reinterpret_cast<sockaddr*>(&addr),
285 &addrlen);
286 SocketAddress address;
287 if (result >= 0) {
288 SocketAddressFromSockAddrStorage(addr, &address);
289 } else {
290 LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
291 << socket_;
292 }
293 return address;
294}
295
296SocketAddress Win32Socket::GetRemoteAddress() const {
297 sockaddr_storage addr = {0};
298 socklen_t addrlen = sizeof(addr);
299 int result = ::getpeername(socket_, reinterpret_cast<sockaddr*>(&addr),
300 &addrlen);
301 SocketAddress address;
302 if (result >= 0) {
303 SocketAddressFromSockAddrStorage(addr, &address);
304 } else {
305 LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket="
306 << socket_;
307 }
308 return address;
309}
310
311int Win32Socket::Bind(const SocketAddress& addr) {
nisseede5da42017-01-12 05:15:36 -0800312 RTC_DCHECK(socket_ != INVALID_SOCKET);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313 if (socket_ == INVALID_SOCKET)
314 return SOCKET_ERROR;
315
316 sockaddr_storage saddr;
317 size_t len = addr.ToSockAddrStorage(&saddr);
318 int err = ::bind(socket_,
319 reinterpret_cast<sockaddr*>(&saddr),
320 static_cast<int>(len));
321 UpdateLastError();
322 return err;
323}
324
325int Win32Socket::Connect(const SocketAddress& addr) {
326 if (state_ != CS_CLOSED) {
327 SetError(EALREADY);
328 return SOCKET_ERROR;
329 }
330
331 if (!addr.IsUnresolvedIP()) {
332 return DoConnect(addr);
333 }
334
335 LOG_F(LS_INFO) << "async dns lookup (" << addr.hostname() << ")";
336 DnsLookup * dns = new DnsLookup;
337 if (!sink_) {
338 // Explicitly create the sink ourselves here; we can't rely on SetAsync
339 // because we don't have a socket_ yet.
340 CreateSink();
341 }
342 // TODO: Replace with IPv6 compatible lookup.
343 dns->handle = WSAAsyncGetHostByName(sink_->handle(), WM_DNSNOTIFY,
344 addr.hostname().c_str(), dns->buffer,
345 sizeof(dns->buffer));
346
347 if (!dns->handle) {
348 LOG_F(LS_ERROR) << "WSAAsyncGetHostByName error: " << WSAGetLastError();
349 delete dns;
350 UpdateLastError();
351 Close();
352 return SOCKET_ERROR;
353 }
354
355 dns->port = addr.port();
356 dns_ = dns;
357 state_ = CS_CONNECTING;
358 return 0;
359}
360
361int Win32Socket::DoConnect(const SocketAddress& addr) {
362 if ((socket_ == INVALID_SOCKET) && !CreateT(addr.family(), SOCK_STREAM)) {
363 return SOCKET_ERROR;
364 }
365 if (!SetAsync(FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE)) {
366 return SOCKET_ERROR;
367 }
368
369 sockaddr_storage saddr = {0};
370 size_t len = addr.ToSockAddrStorage(&saddr);
371 connect_time_ = Time();
372 int result = connect(socket_,
373 reinterpret_cast<SOCKADDR*>(&saddr),
374 static_cast<int>(len));
375 if (result != SOCKET_ERROR) {
376 state_ = CS_CONNECTED;
377 } else {
378 int code = WSAGetLastError();
379 if (code == WSAEWOULDBLOCK) {
380 state_ = CS_CONNECTING;
381 } else {
382 ReportWSAError("WSAAsync:connect", code, addr);
383 error_ = code;
384 Close();
385 return SOCKET_ERROR;
386 }
387 }
388 addr_ = addr;
389
390 return 0;
391}
392
393int Win32Socket::GetError() const {
394 return error_;
395}
396
397void Win32Socket::SetError(int error) {
398 error_ = error;
399}
400
401Socket::ConnState Win32Socket::GetState() const {
402 return state_;
403}
404
405int Win32Socket::GetOption(Option opt, int* value) {
406 int slevel;
407 int sopt;
408 if (TranslateOption(opt, &slevel, &sopt) == -1)
409 return -1;
410
411 char* p = reinterpret_cast<char*>(value);
412 int optlen = sizeof(value);
413 return ::getsockopt(socket_, slevel, sopt, p, &optlen);
414}
415
416int Win32Socket::SetOption(Option opt, int value) {
417 int slevel;
418 int sopt;
419 if (TranslateOption(opt, &slevel, &sopt) == -1)
420 return -1;
421
422 const char* p = reinterpret_cast<const char*>(&value);
423 return ::setsockopt(socket_, slevel, sopt, p, sizeof(value));
424}
425
426int Win32Socket::Send(const void* buffer, size_t length) {
427 int sent = ::send(socket_,
428 reinterpret_cast<const char*>(buffer),
429 static_cast<int>(length),
430 0);
431 UpdateLastError();
432 return sent;
433}
434
435int Win32Socket::SendTo(const void* buffer, size_t length,
436 const SocketAddress& addr) {
437 sockaddr_storage saddr;
438 size_t addr_len = addr.ToSockAddrStorage(&saddr);
439 int sent = ::sendto(socket_, reinterpret_cast<const char*>(buffer),
440 static_cast<int>(length), 0,
441 reinterpret_cast<sockaddr*>(&saddr),
442 static_cast<int>(addr_len));
443 UpdateLastError();
444 return sent;
445}
446
Stefan Holmer9131efd2016-05-23 18:19:26 +0200447int Win32Socket::Recv(void* buffer, size_t length, int64_t* timestamp) {
448 if (timestamp) {
449 *timestamp = -1;
450 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000451 int received = ::recv(socket_, static_cast<char*>(buffer),
452 static_cast<int>(length), 0);
453 UpdateLastError();
454 if (closing_ && received <= static_cast<int>(length))
455 PostClosed();
456 return received;
457}
458
Stefan Holmer9131efd2016-05-23 18:19:26 +0200459int Win32Socket::RecvFrom(void* buffer,
460 size_t length,
461 SocketAddress* out_addr,
462 int64_t* timestamp) {
463 if (timestamp) {
464 *timestamp = -1;
465 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000466 sockaddr_storage saddr;
467 socklen_t addr_len = sizeof(saddr);
468 int received = ::recvfrom(socket_, static_cast<char*>(buffer),
469 static_cast<int>(length), 0,
470 reinterpret_cast<sockaddr*>(&saddr), &addr_len);
471 UpdateLastError();
472 if (received != SOCKET_ERROR)
473 SocketAddressFromSockAddrStorage(saddr, out_addr);
474 if (closing_ && received <= static_cast<int>(length))
475 PostClosed();
476 return received;
477}
478
479int Win32Socket::Listen(int backlog) {
480 int err = ::listen(socket_, backlog);
481 if (!SetAsync(FD_ACCEPT))
482 return SOCKET_ERROR;
483
484 UpdateLastError();
485 if (err == 0)
486 state_ = CS_CONNECTING;
487 return err;
488}
489
490Win32Socket* Win32Socket::Accept(SocketAddress* out_addr) {
491 sockaddr_storage saddr;
492 socklen_t addr_len = sizeof(saddr);
493 SOCKET s = ::accept(socket_, reinterpret_cast<sockaddr*>(&saddr), &addr_len);
494 UpdateLastError();
495 if (s == INVALID_SOCKET)
deadbeef37f5ecf2017-02-27 14:06:41 -0800496 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000497 if (out_addr)
498 SocketAddressFromSockAddrStorage(saddr, out_addr);
499 Win32Socket* socket = new Win32Socket;
500 if (0 == socket->Attach(s))
501 return socket;
502 delete socket;
deadbeef37f5ecf2017-02-27 14:06:41 -0800503 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000504}
505
506int Win32Socket::Close() {
507 int err = 0;
508 if (socket_ != INVALID_SOCKET) {
509 err = ::closesocket(socket_);
510 socket_ = INVALID_SOCKET;
511 closing_ = false;
512 close_error_ = 0;
513 UpdateLastError();
514 }
515 if (dns_) {
516 WSACancelAsyncRequest(dns_->handle);
517 delete dns_;
deadbeef37f5ecf2017-02-27 14:06:41 -0800518 dns_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000519 }
520 if (sink_) {
521 sink_->Dispose();
deadbeef37f5ecf2017-02-27 14:06:41 -0800522 sink_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000523 }
524 addr_.Clear();
525 state_ = CS_CLOSED;
526 return err;
527}
528
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000529void Win32Socket::CreateSink() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800530 RTC_DCHECK(nullptr == sink_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000531
532 // Create window
533 sink_ = new EventSink(this);
deadbeef37f5ecf2017-02-27 14:06:41 -0800534 sink_->Create(nullptr, L"EventSink", 0, 0, 0, 0, 10, 10);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000535}
536
537bool Win32Socket::SetAsync(int events) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800538 if (nullptr == sink_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000539 CreateSink();
deadbeef37f5ecf2017-02-27 14:06:41 -0800540 RTC_DCHECK(nullptr != sink_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000541 }
542
543 // start the async select
544 if (WSAAsyncSelect(socket_, sink_->handle(), WM_SOCKETNOTIFY, events)
545 == SOCKET_ERROR) {
546 UpdateLastError();
547 Close();
548 return false;
549 }
550
551 return true;
552}
553
554bool Win32Socket::HandleClosed(int close_error) {
555 // WM_CLOSE will be received before all data has been read, so we need to
556 // hold on to it until the read buffer has been drained.
557 char ch;
558 closing_ = true;
559 close_error_ = close_error;
560 return (::recv(socket_, &ch, 1, MSG_PEEK) <= 0);
561}
562
563void Win32Socket::PostClosed() {
564 // If we see that the buffer is indeed drained, then send the close.
565 closing_ = false;
566 ::PostMessage(sink_->handle(), WM_SOCKETNOTIFY,
567 socket_, WSAMAKESELECTREPLY(FD_CLOSE, close_error_));
568}
569
570void Win32Socket::UpdateLastError() {
571 error_ = WSAGetLastError();
572}
573
574int Win32Socket::TranslateOption(Option opt, int* slevel, int* sopt) {
575 switch (opt) {
576 case OPT_DONTFRAGMENT:
577 *slevel = IPPROTO_IP;
578 *sopt = IP_DONTFRAGMENT;
579 break;
580 case OPT_RCVBUF:
581 *slevel = SOL_SOCKET;
582 *sopt = SO_RCVBUF;
583 break;
584 case OPT_SNDBUF:
585 *slevel = SOL_SOCKET;
586 *sopt = SO_SNDBUF;
587 break;
588 case OPT_NODELAY:
589 *slevel = IPPROTO_TCP;
590 *sopt = TCP_NODELAY;
591 break;
592 case OPT_DSCP:
593 LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
594 return -1;
595 default:
nissec80e7412017-01-11 05:56:46 -0800596 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000597 return -1;
598 }
599 return 0;
600}
601
602void Win32Socket::OnSocketNotify(SOCKET socket, int event, int error) {
603 // Ignore events if we're already closed.
604 if (socket != socket_)
605 return;
606
607 error_ = error;
608 switch (event) {
609 case FD_CONNECT:
610 if (error != ERROR_SUCCESS) {
611 ReportWSAError("WSAAsync:connect notify", error, addr_);
tfarinaa41ab932015-10-30 16:08:48 -0700612#if !defined(NDEBUG)
Honghai Zhang82d78622016-05-06 11:29:15 -0700613 int64_t duration = TimeSince(connect_time_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000614 LOG(LS_INFO) << "WSAAsync:connect error (" << duration
615 << " ms), faking close";
616#endif
617 state_ = CS_CLOSED;
618 // If you get an error connecting, close doesn't really do anything
619 // and it certainly doesn't send back any close notification, but
620 // we really only maintain a few states, so it is easiest to get
621 // back into a known state by pretending that a close happened, even
622 // though the connect event never did occur.
623 SignalCloseEvent(this, error);
624 } else {
tfarinaa41ab932015-10-30 16:08:48 -0700625#if !defined(NDEBUG)
Honghai Zhang82d78622016-05-06 11:29:15 -0700626 int64_t duration = TimeSince(connect_time_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000627 LOG(LS_INFO) << "WSAAsync:connect (" << duration << " ms)";
628#endif
629 state_ = CS_CONNECTED;
630 SignalConnectEvent(this);
631 }
632 break;
633
634 case FD_ACCEPT:
635 case FD_READ:
636 if (error != ERROR_SUCCESS) {
637 ReportWSAError("WSAAsync:read notify", error, addr_);
638 } else {
639 SignalReadEvent(this);
640 }
641 break;
642
643 case FD_WRITE:
644 if (error != ERROR_SUCCESS) {
645 ReportWSAError("WSAAsync:write notify", error, addr_);
646 } else {
647 SignalWriteEvent(this);
648 }
649 break;
650
651 case FD_CLOSE:
652 if (HandleClosed(error)) {
653 ReportWSAError("WSAAsync:close notify", error, addr_);
654 state_ = CS_CLOSED;
655 SignalCloseEvent(this, error);
656 }
657 break;
658 }
659}
660
661void Win32Socket::OnDnsNotify(HANDLE task, int error) {
662 if (!dns_ || dns_->handle != task)
663 return;
664
Peter Boström0c4e06b2015-10-07 12:23:21 +0200665 uint32_t ip = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000666 if (error == 0) {
667 hostent* pHost = reinterpret_cast<hostent*>(dns_->buffer);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200668 uint32_t net_ip = *reinterpret_cast<uint32_t*>(pHost->h_addr_list[0]);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000669 ip = NetworkToHost32(net_ip);
670 }
671
672 LOG_F(LS_INFO) << "(" << IPAddress(ip).ToSensitiveString()
673 << ", " << error << ")";
674
675 if (error == 0) {
676 SocketAddress address(ip, dns_->port);
677 error = DoConnect(address);
678 } else {
679 Close();
680 }
681
682 if (error) {
683 error_ = error;
684 SignalCloseEvent(this, error_);
685 } else {
686 delete dns_;
deadbeef37f5ecf2017-02-27 14:06:41 -0800687 dns_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000688 }
689}
690
691///////////////////////////////////////////////////////////////////////////////
692// Win32SocketServer
693// Provides cricket base services on top of a win32 gui thread
694///////////////////////////////////////////////////////////////////////////////
695
696static UINT s_wm_wakeup_id = 0;
697const TCHAR Win32SocketServer::kWindowName[] = L"libjingle Message Window";
698
nisse7eaa4ea2017-05-08 05:25:41 -0700699Win32SocketServer::Win32SocketServer()
700 : wnd_(this),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000701 posted_(false),
deadbeef37f5ecf2017-02-27 14:06:41 -0800702 hdlg_(nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000703 if (s_wm_wakeup_id == 0)
704 s_wm_wakeup_id = RegisterWindowMessage(L"WM_WAKEUP");
deadbeef37f5ecf2017-02-27 14:06:41 -0800705 if (!wnd_.Create(nullptr, kWindowName, 0, 0, 0, 0, 0, 0)) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000706 LOG_GLE(LS_ERROR) << "Failed to create message window.";
707 }
708}
709
710Win32SocketServer::~Win32SocketServer() {
deadbeef37f5ecf2017-02-27 14:06:41 -0800711 if (wnd_.handle() != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000712 KillTimer(wnd_.handle(), 1);
713 wnd_.Destroy();
714 }
715}
716
717Socket* Win32SocketServer::CreateSocket(int type) {
718 return CreateSocket(AF_INET, type);
719}
720
721Socket* Win32SocketServer::CreateSocket(int family, int type) {
722 return CreateAsyncSocket(family, type);
723}
724
725AsyncSocket* Win32SocketServer::CreateAsyncSocket(int type) {
726 return CreateAsyncSocket(AF_INET, type);
727}
728
729AsyncSocket* Win32SocketServer::CreateAsyncSocket(int family, int type) {
730 Win32Socket* socket = new Win32Socket;
731 if (socket->CreateT(family, type)) {
732 return socket;
733 }
734 delete socket;
deadbeef37f5ecf2017-02-27 14:06:41 -0800735 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000736}
737
738void Win32SocketServer::SetMessageQueue(MessageQueue* queue) {
739 message_queue_ = queue;
740}
741
742bool Win32SocketServer::Wait(int cms, bool process_io) {
743 BOOL b;
744 if (process_io) {
745 // Spin the Win32 message pump at least once, and as long as requested.
746 // This is the Thread::ProcessMessages case.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200747 uint32_t start = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000748 do {
749 MSG msg;
deadbeef37f5ecf2017-02-27 14:06:41 -0800750 SetTimer(wnd_.handle(), 0, cms, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000751 // Get the next available message. If we have a modeless dialog, give
752 // give the message to IsDialogMessage, which will return true if it
753 // was a message for the dialog that it handled internally.
754 // Otherwise, dispatch as usual via Translate/DispatchMessage.
deadbeef37f5ecf2017-02-27 14:06:41 -0800755 b = GetMessage(&msg, nullptr, 0, 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000756 if (b == -1) {
757 LOG_GLE(LS_ERROR) << "GetMessage failed.";
758 return false;
759 } else if(b) {
760 if (!hdlg_ || !IsDialogMessage(hdlg_, &msg)) {
761 TranslateMessage(&msg);
762 DispatchMessage(&msg);
763 }
764 }
765 KillTimer(wnd_.handle(), 0);
766 } while (b && TimeSince(start) < cms);
767 } else if (cms != 0) {
768 // Sit and wait forever for a WakeUp. This is the Thread::Send case.
nisseede5da42017-01-12 05:15:36 -0800769 RTC_DCHECK(cms == -1);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000770 MSG msg;
deadbeef37f5ecf2017-02-27 14:06:41 -0800771 b = GetMessage(&msg, nullptr, s_wm_wakeup_id, s_wm_wakeup_id);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000772 {
773 CritScope scope(&cs_);
774 posted_ = false;
775 }
776 } else {
777 // No-op (cms == 0 && !process_io). This is the Pump case.
778 b = TRUE;
779 }
780 return (b != FALSE);
781}
782
783void Win32SocketServer::WakeUp() {
784 if (wnd_.handle()) {
785 // Set the "message pending" flag, if not already set.
786 {
787 CritScope scope(&cs_);
788 if (posted_)
789 return;
790 posted_ = true;
791 }
792
793 PostMessage(wnd_.handle(), s_wm_wakeup_id, 0, 0);
794 }
795}
796
797void Win32SocketServer::Pump() {
798 // Clear the "message pending" flag.
799 {
800 CritScope scope(&cs_);
801 posted_ = false;
802 }
803
804 // Dispatch all the messages that are currently in our queue. If new messages
805 // are posted during the dispatch, they will be handled in the next Pump.
806 // We use max(1, ...) to make sure we try to dispatch at least once, since
807 // this allow us to process "sent" messages, not included in the size() count.
808 Message msg;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000809 for (size_t max_messages_to_process =
810 std::max<size_t>(1, message_queue_->size());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000811 max_messages_to_process > 0 && message_queue_->Get(&msg, 0, false);
812 --max_messages_to_process) {
813 message_queue_->Dispatch(&msg);
814 }
815
816 // Anything remaining?
817 int delay = message_queue_->GetDelay();
818 if (delay == -1) {
819 KillTimer(wnd_.handle(), 1);
820 } else {
deadbeef37f5ecf2017-02-27 14:06:41 -0800821 SetTimer(wnd_.handle(), 1, delay, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000822 }
823}
824
825bool Win32SocketServer::MessageWindow::OnMessage(UINT wm, WPARAM wp,
826 LPARAM lp, LRESULT& lr) {
827 bool handled = false;
828 if (wm == s_wm_wakeup_id || (wm == WM_TIMER && wp == 1)) {
829 ss_->Pump();
830 lr = 0;
831 handled = true;
832 }
833 return handled;
834}
835
Steve Anton9de3aac2017-10-24 10:08:26 -0700836Win32Thread::Win32Thread(SocketServer* ss) : Thread(ss), id_(0) {}
837
838Win32Thread::~Win32Thread() {
839 Stop();
840}
841
842void Win32Thread::Run() {
843 id_ = GetCurrentThreadId();
844 Thread::Run();
845 id_ = 0;
846}
847
848void Win32Thread::Quit() {
849 PostThreadMessage(id_, WM_QUIT, 0, 0);
850}
851
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000852} // namespace rtc