3
* Copyright 2004--2005, Google Inc.
5
* Redistribution and use in source and binary forms, with or without
6
* modification, are permitted provided that the following conditions are met:
8
* 1. Redistributions of source code must retain the above copyright notice,
9
* this list of conditions and the following disclaimer.
10
* 2. Redistributions in binary form must reproduce the above copyright notice,
11
* this list of conditions and the following disclaimer in the documentation
12
* and/or other materials provided with the distribution.
13
* 3. The name of the author may not be used to endorse or promote products
14
* derived from this software without specific prior written permission.
16
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
#include "talk/base/win32socketserver.h"
29
#include "talk/base/byteorder.h"
30
#include "talk/base/common.h"
31
#include "talk/base/logging.h"
32
#include "talk/base/winping.h"
33
#include "talk/base/win32window.h"
34
#include <ws2tcpip.h> // NOLINT
38
///////////////////////////////////////////////////////////////////////////////
40
///////////////////////////////////////////////////////////////////////////////
42
// TODO: Move this to a common place where PhysicalSocketServer can
45
static const uint16 PACKET_MAXIMUMS[] = {
46
65535, // Theoretical maximum, Hyperchannel
48
17914, // 16Mb IBM Token Ring
50
// 4464 // IEEE 802.5 (4Mb max)
52
// 2048, // Wideband Network
53
2002, // IEEE 802.5 (4Mb recommended)
54
// 1536, // Expermental Ethernet Networks
55
// 1500, // Ethernet, Point-to-Point (default)
57
1006, // SLIP, ARPANET
58
// 576, // X.25 Networks
59
// 544, // DEC IP Portal
61
508, // IEEE 802/Source-Rt Bridge, ARCNET
62
296, // Point-to-Point (low delay)
63
68, // Official minimum
64
0, // End of list marker
67
static const uint32 IP_HEADER_SIZE = 20;
68
static const uint32 ICMP_HEADER_SIZE = 8;
70
// TODO: Enable for production builds also? Use FormatMessage?
72
LPCSTR WSAErrorToString(int error, LPCSTR *description_result) {
73
LPCSTR string = "Unspecified";
74
LPCSTR description = "Unspecified description";
78
description = "Operation succeeded";
81
string = "WSAEWOULDBLOCK";
82
description = "Using a non-blocking socket, will notify later";
86
description = "Access denied, or sharing violation";
88
case WSAEADDRNOTAVAIL:
89
string = "WSAEADDRNOTAVAIL";
90
description = "Address is not valid in this context";
93
string = "WSAENETDOWN";
94
description = "Network is down";
97
string = "WSAENETUNREACH";
98
description = "Network is up, but unreachable";
101
string = "WSANETRESET";
102
description = "Connection has been reset due to keep-alive activity";
104
case WSAECONNABORTED:
105
string = "WSAECONNABORTED";
106
description = "Aborted by host";
109
string = "WSAECONNRESET";
110
description = "Connection reset by host";
113
string = "WSAETIMEDOUT";
114
description = "Timed out, host failed to respond";
116
case WSAECONNREFUSED:
117
string = "WSAECONNREFUSED";
118
description = "Host actively refused connection";
121
string = "WSAEHOSTDOWN";
122
description = "Host is down";
124
case WSAEHOSTUNREACH:
125
string = "WSAEHOSTUNREACH";
126
description = "Host is unreachable";
128
case WSAHOST_NOT_FOUND:
129
string = "WSAHOST_NOT_FOUND";
130
description = "No such host is known";
133
if (description_result) {
134
*description_result = description;
139
void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {
140
LPCSTR description_string;
141
LPCSTR error_string = WSAErrorToString(error, &description_string);
142
LOG(LS_INFO) << context << " = " << error
143
<< " (" << error_string << ":" << description_string << ") ["
144
<< address.ToString() << "]";
147
void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {}
150
/////////////////////////////////////////////////////////////////////////////
151
// Win32Socket::EventSink
152
/////////////////////////////////////////////////////////////////////////////
154
#define WM_SOCKETNOTIFY (WM_USER + 50)
155
#define WM_DNSNOTIFY (WM_USER + 51)
157
struct Win32Socket::DnsLookup {
160
char buffer[MAXGETHOSTSTRUCT];
163
class Win32Socket::EventSink : public Win32Window {
165
explicit EventSink(Win32Socket * parent) : parent_(parent) { }
169
virtual bool OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam,
171
virtual void OnNcDestroy();
174
bool OnSocketNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result);
175
bool OnDnsNotify(WPARAM wParam, LPARAM lParam, LRESULT& result);
177
Win32Socket * parent_;
180
void Win32Socket::EventSink::Dispose() {
182
if (::IsWindow(handle())) {
183
::DestroyWindow(handle());
189
bool Win32Socket::EventSink::OnMessage(UINT uMsg, WPARAM wParam,
190
LPARAM lParam, LRESULT& result) {
192
case WM_SOCKETNOTIFY:
194
return OnSocketNotify(uMsg, wParam, lParam, result);
196
return OnDnsNotify(wParam, lParam, result);
201
bool Win32Socket::EventSink::OnSocketNotify(UINT uMsg, WPARAM wParam,
202
LPARAM lParam, LRESULT& result) {
205
int wsa_event = WSAGETSELECTEVENT(lParam);
206
int wsa_error = WSAGETSELECTERROR(lParam);
208
// Treat connect timeouts as close notifications
209
if (uMsg == WM_TIMER) {
210
wsa_event = FD_CLOSE;
211
wsa_error = WSAETIMEDOUT;
215
parent_->OnSocketNotify(static_cast<SOCKET>(wParam), wsa_event, wsa_error);
219
bool Win32Socket::EventSink::OnDnsNotify(WPARAM wParam, LPARAM lParam,
223
int error = WSAGETASYNCERROR(lParam);
225
parent_->OnDnsNotify(reinterpret_cast<HANDLE>(wParam), error);
229
void Win32Socket::EventSink::OnNcDestroy() {
231
LOG(LS_ERROR) << "EventSink hwnd is being destroyed, but the event sink"
232
" hasn't yet been disposed.";
238
/////////////////////////////////////////////////////////////////////////////
240
/////////////////////////////////////////////////////////////////////////////
242
Win32Socket::Win32Socket()
243
: socket_(INVALID_SOCKET), error_(0), state_(CS_CLOSED), connect_time_(0),
244
closing_(false), close_error_(0), sink_(NULL), dns_(NULL) {
247
Win32Socket::~Win32Socket() {
251
bool Win32Socket::CreateT(int family, int type) {
253
int proto = (SOCK_DGRAM == type) ? IPPROTO_UDP : IPPROTO_TCP;
254
socket_ = ::WSASocket(family, type, proto, NULL, NULL, 0);
255
if (socket_ == INVALID_SOCKET) {
259
if ((SOCK_DGRAM == type) && !SetAsync(FD_READ | FD_WRITE)) {
265
int Win32Socket::Attach(SOCKET s) {
266
ASSERT(socket_ == INVALID_SOCKET);
267
if (socket_ != INVALID_SOCKET)
270
ASSERT(s != INVALID_SOCKET);
271
if (s == INVALID_SOCKET)
275
state_ = CS_CONNECTED;
277
if (!SetAsync(FD_READ | FD_WRITE | FD_CLOSE))
283
void Win32Socket::SetTimeout(int ms) {
285
::SetTimer(sink_->handle(), 1, ms, 0);
288
SocketAddress Win32Socket::GetLocalAddress() const {
289
sockaddr_storage addr;
290
socklen_t addrlen = sizeof(addr);
291
int result = ::getsockname(socket_, reinterpret_cast<sockaddr*>(&addr),
293
SocketAddress address;
295
SocketAddressFromSockAddrStorage(addr, &address);
297
LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
303
SocketAddress Win32Socket::GetRemoteAddress() const {
304
sockaddr_storage addr;
305
socklen_t addrlen = sizeof(addr);
306
int result = ::getpeername(socket_, reinterpret_cast<sockaddr*>(&addr),
308
SocketAddress address;
310
SocketAddressFromSockAddrStorage(addr, &address);
312
LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket="
318
int Win32Socket::Bind(const SocketAddress& addr) {
319
ASSERT(socket_ != INVALID_SOCKET);
320
if (socket_ == INVALID_SOCKET)
323
sockaddr_storage saddr;
324
size_t len = addr.ToSockAddrStorage(&saddr);
325
int err = ::bind(socket_,
326
reinterpret_cast<sockaddr*>(&saddr),
327
static_cast<int>(len));
332
int Win32Socket::Connect(const SocketAddress& addr) {
333
if ((socket_ == INVALID_SOCKET) && !CreateT(AF_INET, SOCK_STREAM))
336
if (!sink_ && !SetAsync(FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE))
339
// If we have an IP address, connect now.
340
if (!addr.IsUnresolved()) {
341
return DoConnect(addr);
344
LOG_F(LS_INFO) << "async dns lookup (" << addr.IPAsString() << ")";
345
DnsLookup * dns = new DnsLookup;
346
// TODO: Replace with IPv6 compatible lookup.
347
dns->handle = WSAAsyncGetHostByName(sink_->handle(), WM_DNSNOTIFY,
348
addr.IPAsString().c_str(), dns->buffer, sizeof(dns->buffer));
351
LOG_F(LS_ERROR) << "WSAAsyncGetHostByName error: " << WSAGetLastError();
358
dns->port = addr.port();
360
state_ = CS_CONNECTING;
364
int Win32Socket::DoConnect(const SocketAddress& addr) {
365
sockaddr_storage saddr;
366
size_t len = addr.ToSockAddrStorage(&saddr);
367
connect_time_ = Time();
368
int result = connect(socket_,
369
reinterpret_cast<SOCKADDR*>(&saddr),
370
static_cast<int>(len));
371
if (result != SOCKET_ERROR) {
372
state_ = CS_CONNECTED;
374
int code = WSAGetLastError();
375
if (code == WSAEWOULDBLOCK) {
376
state_ = CS_CONNECTING;
378
ReportWSAError("WSAAsync:connect", code, addr);
389
int Win32Socket::GetError() const {
393
void Win32Socket::SetError(int error) {
397
Socket::ConnState Win32Socket::GetState() const {
401
int Win32Socket::GetOption(Option opt, int* value) {
404
if (TranslateOption(opt, &slevel, &sopt) == -1)
407
char* p = reinterpret_cast<char*>(value);
408
int optlen = sizeof(value);
409
return ::getsockopt(socket_, slevel, sopt, p, &optlen);
412
int Win32Socket::SetOption(Option opt, int value) {
415
if (TranslateOption(opt, &slevel, &sopt) == -1)
418
const char* p = reinterpret_cast<const char*>(&value);
419
return ::setsockopt(socket_, slevel, sopt, p, sizeof(value));
422
int Win32Socket::Send(const void* buffer, size_t length) {
423
int sent = ::send(socket_,
424
reinterpret_cast<const char*>(buffer),
425
static_cast<int>(length),
431
int Win32Socket::SendTo(const void* buffer, size_t length,
432
const SocketAddress& addr) {
433
sockaddr_storage saddr;
434
size_t addr_len = addr.ToSockAddrStorage(&saddr);
435
int sent = ::sendto(socket_, reinterpret_cast<const char*>(buffer),
436
static_cast<int>(length), 0,
437
reinterpret_cast<sockaddr*>(&saddr),
438
static_cast<int>(addr_len));
443
int Win32Socket::Recv(void* buffer, size_t length) {
444
int received = ::recv(socket_, static_cast<char*>(buffer),
445
static_cast<int>(length), 0);
447
if (closing_ && received <= static_cast<int>(length))
452
int Win32Socket::RecvFrom(void* buffer, size_t length,
453
SocketAddress* out_addr) {
454
sockaddr_storage saddr;
455
socklen_t addr_len = sizeof(saddr);
456
int received = ::recvfrom(socket_, static_cast<char*>(buffer),
457
static_cast<int>(length), 0,
458
reinterpret_cast<sockaddr*>(&saddr), &addr_len);
460
if (received != SOCKET_ERROR)
461
SocketAddressFromSockAddrStorage(saddr, out_addr);
462
if (closing_ && received <= static_cast<int>(length))
467
int Win32Socket::Listen(int backlog) {
468
int err = ::listen(socket_, backlog);
469
if (!SetAsync(FD_ACCEPT))
474
state_ = CS_CONNECTING;
478
Win32Socket* Win32Socket::Accept(SocketAddress* out_addr) {
479
sockaddr_storage saddr;
480
socklen_t addr_len = sizeof(saddr);
481
SOCKET s = ::accept(socket_, reinterpret_cast<sockaddr*>(&saddr), &addr_len);
483
if (s == INVALID_SOCKET)
486
SocketAddressFromSockAddrStorage(saddr, out_addr);
487
Win32Socket* socket = new Win32Socket;
488
if (0 == socket->Attach(s))
494
int Win32Socket::Close() {
496
if (socket_ != INVALID_SOCKET) {
497
err = ::closesocket(socket_);
498
socket_ = INVALID_SOCKET;
504
WSACancelAsyncRequest(dns_->handle);
517
int Win32Socket::EstimateMTU(uint16* mtu) {
518
SocketAddress addr = GetRemoteAddress();
525
if (!ping.IsValid()) {
526
error_ = EINVAL; // can't think of a better error ID
530
for (int level = 0; PACKET_MAXIMUMS[level + 1] > 0; ++level) {
531
int32 size = PACKET_MAXIMUMS[level] - IP_HEADER_SIZE - ICMP_HEADER_SIZE;
532
WinPing::PingResult result = ping.Ping(addr.ip(), size, 0, 1, false);
533
if (result == WinPing::PING_FAIL) {
534
error_ = EINVAL; // can't think of a better error ID
537
if (result != WinPing::PING_TOO_LARGE) {
538
*mtu = PACKET_MAXIMUMS[level];
547
bool Win32Socket::SetAsync(int events) {
548
ASSERT(NULL == sink_);
551
sink_ = new EventSink(this);
552
sink_->Create(NULL, L"EventSink", 0, 0, 0, 0, 10, 10);
554
// start the async select
555
if (WSAAsyncSelect(socket_, sink_->handle(), WM_SOCKETNOTIFY, events)
565
bool Win32Socket::HandleClosed(int close_error) {
566
// WM_CLOSE will be received before all data has been read, so we need to
567
// hold on to it until the read buffer has been drained.
570
close_error_ = close_error;
571
return (::recv(socket_, &ch, 1, MSG_PEEK) <= 0);
574
void Win32Socket::PostClosed() {
575
// If we see that the buffer is indeed drained, then send the close.
577
::PostMessage(sink_->handle(), WM_SOCKETNOTIFY,
578
socket_, WSAMAKESELECTREPLY(FD_CLOSE, close_error_));
581
void Win32Socket::UpdateLastError() {
582
error_ = WSAGetLastError();
585
int Win32Socket::TranslateOption(Option opt, int* slevel, int* sopt) {
587
case OPT_DONTFRAGMENT:
588
*slevel = IPPROTO_IP;
589
*sopt = IP_DONTFRAGMENT;
592
*slevel = SOL_SOCKET;
596
*slevel = SOL_SOCKET;
600
*slevel = IPPROTO_TCP;
610
void Win32Socket::OnSocketNotify(SOCKET socket, int event, int error) {
611
// Ignore events if we're already closed.
612
if (socket != socket_)
618
if (error != ERROR_SUCCESS) {
619
ReportWSAError("WSAAsync:connect notify", error, addr_);
621
int32 duration = TimeSince(connect_time_);
622
LOG(LS_INFO) << "WSAAsync:connect error (" << duration
623
<< " ms), faking close";
626
// If you get an error connecting, close doesn't really do anything
627
// and it certainly doesn't send back any close notification, but
628
// we really only maintain a few states, so it is easiest to get
629
// back into a known state by pretending that a close happened, even
630
// though the connect event never did occur.
631
SignalCloseEvent(this, error);
634
int32 duration = TimeSince(connect_time_);
635
LOG(LS_INFO) << "WSAAsync:connect (" << duration << " ms)";
637
state_ = CS_CONNECTED;
638
SignalConnectEvent(this);
644
if (error != ERROR_SUCCESS) {
645
ReportWSAError("WSAAsync:read notify", error, addr_);
647
SignalReadEvent(this);
652
if (error != ERROR_SUCCESS) {
653
ReportWSAError("WSAAsync:write notify", error, addr_);
655
SignalWriteEvent(this);
660
if (HandleClosed(error)) {
661
ReportWSAError("WSAAsync:close notify", error, addr_);
663
SignalCloseEvent(this, error);
669
void Win32Socket::OnDnsNotify(HANDLE task, int error) {
670
if (!dns_ || dns_->handle != task)
675
hostent* pHost = reinterpret_cast<hostent*>(dns_->buffer);
676
uint32 net_ip = *reinterpret_cast<uint32*>(pHost->h_addr_list[0]);
677
ip = NetworkToHost32(net_ip);
680
LOG_F(LS_INFO) << "(" << SocketAddress::IPToString(ip)
681
<< ", " << error << ")";
684
SocketAddress address(ip, dns_->port);
685
error = DoConnect(address);
692
SignalCloseEvent(this, error_);
699
///////////////////////////////////////////////////////////////////////////////
701
// Provides cricket base services on top of a win32 gui thread
702
///////////////////////////////////////////////////////////////////////////////
704
static UINT s_wm_wakeup_id = 0;
705
const TCHAR Win32SocketServer::kWindowName[] = L"libjingle Message Window";
707
Win32SocketServer::Win32SocketServer(MessageQueue* message_queue)
708
: message_queue_(message_queue),
712
if (s_wm_wakeup_id == 0)
713
s_wm_wakeup_id = RegisterWindowMessage(L"WM_WAKEUP");
714
if (!wnd_.Create(NULL, kWindowName, 0, 0, 0, 0, 0, 0)) {
715
LOG_GLE(LS_ERROR) << "Failed to create message window.";
719
Win32SocketServer::~Win32SocketServer() {
720
if (wnd_.handle() != NULL) {
721
KillTimer(wnd_.handle(), 1);
726
Socket* Win32SocketServer::CreateSocket(int type) {
727
return CreateSocket(AF_INET, type);
730
Socket* Win32SocketServer::CreateSocket(int family, int type) {
731
return CreateAsyncSocket(family, type);
734
AsyncSocket* Win32SocketServer::CreateAsyncSocket(int type) {
735
return CreateAsyncSocket(AF_INET, type);
738
AsyncSocket* Win32SocketServer::CreateAsyncSocket(int family, int type) {
739
Win32Socket* socket = new Win32Socket;
740
if (socket->CreateT(family, type)) {
747
void Win32SocketServer::SetMessageQueue(MessageQueue* queue) {
748
message_queue_ = queue;
751
bool Win32SocketServer::Wait(int cms, bool process_io) {
754
// Spin the Win32 message pump at least once, and as long as requested.
755
// This is the Thread::ProcessMessages case.
756
uint32 start = Time();
759
SetTimer(wnd_.handle(), 0, cms, NULL);
760
// Get the next available message. If we have a modeless dialog, give
761
// give the message to IsDialogMessage, which will return true if it
762
// was a message for the dialog that it handled internally.
763
// Otherwise, dispatch as usual via Translate/DispatchMessage.
764
b = GetMessage(&msg, NULL, 0, 0);
766
LOG_GLE(LS_ERROR) << "GetMessage failed.";
769
if (!hdlg_ || !IsDialogMessage(hdlg_, &msg)) {
770
TranslateMessage(&msg);
771
DispatchMessage(&msg);
774
KillTimer(wnd_.handle(), 0);
775
} while (b && TimeSince(start) < cms);
776
} else if (cms != 0) {
777
// Sit and wait forever for a WakeUp. This is the Thread::Send case.
780
b = GetMessage(&msg, NULL, s_wm_wakeup_id, s_wm_wakeup_id);
782
CritScope scope(&cs_);
786
// No-op (cms == 0 && !process_io). This is the Pump case.
792
void Win32SocketServer::WakeUp() {
794
// Set the "message pending" flag, if not already set.
796
CritScope scope(&cs_);
802
PostMessage(wnd_.handle(), s_wm_wakeup_id, 0, 0);
806
void Win32SocketServer::Pump() {
807
// Clear the "message pending" flag.
809
CritScope scope(&cs_);
813
// Dispatch all the messages that are currently in our queue. If new messages
814
// are posted during the dispatch, they will be handled in the next Pump.
815
// We use max(1, ...) to make sure we try to dispatch at least once, since
816
// this allow us to process "sent" messages, not included in the size() count.
818
for (size_t max_messages_to_process = _max<size_t>(1, message_queue_->size());
819
max_messages_to_process > 0 && message_queue_->Get(&msg, 0, false);
820
--max_messages_to_process) {
821
message_queue_->Dispatch(&msg);
824
// Anything remaining?
825
int delay = message_queue_->GetDelay();
827
KillTimer(wnd_.handle(), 1);
829
SetTimer(wnd_.handle(), 1, delay, NULL);
833
bool Win32SocketServer::MessageWindow::OnMessage(UINT wm, WPARAM wp,
834
LPARAM lp, LRESULT& lr) {
835
bool handled = false;
836
if (wm == s_wm_wakeup_id || (wm == WM_TIMER && wp == 1)) {
844
} // namespace talk_base