]> git.saurik.com Git - wxWidgets.git/blame - src/msw/sockmsw.cpp
Use the data scheme to load resources in the WebKitGTK+ implementation, rather than...
[wxWidgets.git] / src / msw / sockmsw.cpp
CommitLineData
51fe4b60 1/////////////////////////////////////////////////////////////////////////////
116de991
VZ
2// Name: src/msw/sockmsw.cpp
3// Purpose: MSW-specific socket code
51fe4b60
VZ
4// Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
5// Created: April 1997
6// Copyright: (C) 1999-1997, Guilhem Lavaux
7// (C) 1999-2000, Guillermo Rodriguez Garcia
8// (C) 2008 Vadim Zeitlin
9// RCS_ID: $Id$
526954c5 10// Licence: wxWindows licence
51fe4b60
VZ
11/////////////////////////////////////////////////////////////////////////////
12
b7ceceb1 13
86afa786
VS
14// For compilers that support precompilation, includes "wx.h".
15#include "wx/wxprec.h"
16
17#ifdef __BORLANDC__
18 #pragma hdrstop
19#endif
20
2804f77d
VZ
21#if wxUSE_SOCKETS
22
b7ceceb1
DE
23/* including rasasync.h (included from windows.h itself included from
24 * wx/setup.h and/or winsock.h results in this warning for
25 * RPCNOTIFICATION_ROUTINE
26 */
27#ifdef _MSC_VER
1c8681b4 28# pragma warning(disable:4115) /* named type definition in parentheses */
b7ceceb1
DE
29#endif
30
60913641 31#include "wx/private/socket.h"
e8d9821d 32#include "wx/msw/private.h" // for wxGetInstance()
12cc077e 33#include "wx/private/fd.h"
2804f77d 34#include "wx/apptrait.h"
f2c94e8a 35#include "wx/thread.h"
d8abb95f 36#include "wx/dynlib.h"
4f260c9c 37#include "wx/link.h"
b7ceceb1 38
116de991
VZ
39#ifdef __WXWINCE__
40/*
41 * As WSAAsyncSelect is not present on WinCE, it now uses WSACreateEvent,
42 * WSAEventSelect, WSAWaitForMultipleEvents and WSAEnumNetworkEvents. When
43 * enabling eventhandling for a socket a new thread it created that keeps track
44 * of the events and posts a messageto the hidden window to use the standard
45 * message loop.
46 */
b7ceceb1 47#include "wx/msw/wince/net.h"
7ec69821 48#include "wx/hashmap.h"
84aa68c4 49WX_DECLARE_HASH_MAP(int,bool,wxIntegerHash,wxIntegerEqual,SocketHash);
b7ceceb1 50
116de991
VZ
51#ifndef isdigit
52#define isdigit(x) (x > 47 && x < 58)
53#endif
54#include "wx/msw/wince/net.h"
b7ceceb1 55
116de991 56#endif // __WXWINCE__
b7ceceb1
DE
57
58#ifdef _MSC_VER
59# pragma warning(default:4115) /* named type definition in parentheses */
60#endif
61
51fe4b60 62#define CLASSNAME TEXT("_wxSocket_Internal_Window_Class")
b7ceceb1
DE
63
64/* implemented in utils.cpp */
32524c8f 65extern "C" WXDLLIMPEXP_BASE HWND
b7ceceb1
DE
66wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc);
67
51fe4b60 68/* Maximum number of different wxSocket objects at a given time.
b7ceceb1
DE
69 * This value can be modified at will, but it CANNOT be greater
70 * than (0x7FFF - WM_USER + 1)
71 */
72#define MAXSOCKETS 1024
73
74#if (MAXSOCKETS > (0x7FFF - WM_USER + 1))
75#error "MAXSOCKETS is too big!"
76#endif
77
dbfb61b3 78#ifndef __WXWINCE__
d8abb95f 79typedef int (PASCAL *WSAAsyncSelect_t)(SOCKET,HWND,u_int,long);
dbfb61b3
JS
80#else
81/* Typedef the needed function prototypes and the WSANETWORKEVENTS structure
82*/
83typedef struct _WSANETWORKEVENTS {
84 long lNetworkEvents;
85 int iErrorCode[10];
86} WSANETWORKEVENTS, FAR * LPWSANETWORKEVENTS;
d8abb95f
VZ
87typedef HANDLE (PASCAL *WSACreateEvent_t)();
88typedef int (PASCAL *WSAEventSelect_t)(SOCKET,HANDLE,long);
89typedef int (PASCAL *WSAWaitForMultipleEvents_t)(long,HANDLE,BOOL,long,BOOL);
90typedef int (PASCAL *WSAEnumNetworkEvents_t)(SOCKET,HANDLE,LPWSANETWORKEVENTS);
dbfb61b3 91#endif //__WXWINCE__
b7ceceb1 92
51fe4b60 93LRESULT CALLBACK wxSocket_Internal_WinProc(HWND, UINT, WPARAM, LPARAM);
c90cc42e 94
b7ceceb1
DE
95/* Global variables */
96
b7ceceb1 97static HWND hWin;
f2c94e8a 98wxCRIT_SECT_DECLARE_MEMBER(gs_critical);
51fe4b60 99static wxSocketImplMSW *socketList[MAXSOCKETS];
b7ceceb1 100static int firstAvailable;
dbfb61b3
JS
101
102#ifndef __WXWINCE__
d8abb95f 103static WSAAsyncSelect_t gs_WSAAsyncSelect = NULL;
dbfb61b3 104#else
84aa68c4 105static SocketHash socketHash;
dbfb61b3
JS
106static unsigned int currSocket;
107HANDLE hThread[MAXSOCKETS];
d8abb95f
VZ
108static WSACreateEvent_t gs_WSACreateEvent = NULL;
109static WSAEventSelect_t gs_WSAEventSelect = NULL;
110static WSAWaitForMultipleEvents_t gs_WSAWaitForMultipleEvents = NULL;
111static WSAEnumNetworkEvents_t gs_WSAEnumNetworkEvents = NULL;
dbfb61b3
JS
112/* This structure will be used to pass data on to the thread that handles socket events.
113*/
114typedef struct thread_data{
7ec69821
WS
115 HWND hEvtWin;
116 unsigned long msgnumber;
117 unsigned long fd;
118 unsigned long lEvent;
dbfb61b3
JS
119}thread_data;
120#endif
121
dbfb61b3 122#ifdef __WXWINCE__
d8abb95f
VZ
123/* This thread handles socket events on WinCE using WSAEventSelect() as
124 * WSAAsyncSelect is not supported. When an event occurs for the socket, it is
125 * checked what kind of event happend and the correct message gets posted so
126 * that the hidden window can handle it as it would in other MSW builds.
dbfb61b3
JS
127*/
128DWORD WINAPI SocketThread(LPVOID data)
129{
7ec69821
WS
130 WSANETWORKEVENTS NetworkEvents;
131 thread_data* d = (thread_data *)data;
132
133 HANDLE NetworkEvent = gs_WSACreateEvent();
134 gs_WSAEventSelect(d->fd, NetworkEvent, d->lEvent);
135
136 while(socketHash[d->fd] == true)
137 {
138 if ((gs_WSAWaitForMultipleEvents(1, &NetworkEvent, FALSE,INFINITE, FALSE)) == WAIT_FAILED)
139 {
140 printf("WSAWaitForMultipleEvents failed with error %d\n", WSAGetLastError());
141 return 0;
142 }
143 if (gs_WSAEnumNetworkEvents(d->fd ,NetworkEvent, &NetworkEvents) == SOCKET_ERROR)
144 {
145 printf("WSAEnumNetworkEvents failed with error %d\n", WSAGetLastError());
146 return 0;
147 }
148
149 long flags = NetworkEvents.lNetworkEvents;
150 if (flags & FD_READ)
151 ::PostMessage(d->hEvtWin, d->msgnumber,d->fd, FD_READ);
152 if (flags & FD_WRITE)
153 ::PostMessage(d->hEvtWin, d->msgnumber,d->fd, FD_WRITE);
154 if (flags & FD_OOB)
155 ::PostMessage(d->hEvtWin, d->msgnumber,d->fd, FD_OOB);
156 if (flags & FD_ACCEPT)
157 ::PostMessage(d->hEvtWin, d->msgnumber,d->fd, FD_ACCEPT);
158 if (flags & FD_CONNECT)
159 ::PostMessage(d->hEvtWin, d->msgnumber,d->fd, FD_CONNECT);
160 if (flags & FD_CLOSE)
161 ::PostMessage(d->hEvtWin, d->msgnumber,d->fd, FD_CLOSE);
162
163 }
164 gs_WSAEventSelect(d->fd, NetworkEvent, 0);
165 ExitThread(0);
166 return 0;
dbfb61b3
JS
167}
168#endif
169
2804f77d 170// ----------------------------------------------------------------------------
51fe4b60 171// MSW implementation of wxSocketManager
2804f77d 172// ----------------------------------------------------------------------------
dbfb61b3 173
51fe4b60 174class wxSocketMSWManager : public wxSocketManager
1c6dd11c 175{
2804f77d
VZ
176public:
177 virtual bool OnInit();
178 virtual void OnExit();
179
51fe4b60
VZ
180 virtual wxSocketImpl *CreateSocket(wxSocketBase& wxsocket)
181 {
182 return new wxSocketImplMSW(wxsocket);
183 }
c363ead1
VZ
184 virtual void Install_Callback(wxSocketImpl *socket,
185 wxSocketNotify event = wxSOCKET_LOST);
186 virtual void Uninstall_Callback(wxSocketImpl *socket,
187 wxSocketNotify event = wxSOCKET_LOST);
d8abb95f
VZ
188
189private:
190 static wxDynamicLibrary gs_wsock32dll;
2804f77d 191};
c90cc42e 192
d8abb95f
VZ
193wxDynamicLibrary wxSocketMSWManager::gs_wsock32dll;
194
51fe4b60 195bool wxSocketMSWManager::OnInit()
b7ceceb1 196{
84aa68c4
JS
197 static LPCTSTR pclassname = NULL;
198 int i;
b7ceceb1 199
84aa68c4 200 /* Create internal window for event notifications */
51fe4b60 201 hWin = wxCreateHiddenWindow(&pclassname, CLASSNAME, wxSocket_Internal_WinProc);
84aa68c4
JS
202 if (!hWin)
203 return false;
b7ceceb1 204
84aa68c4 205 /* Initialize socket list */
84aa68c4
JS
206 for (i = 0; i < MAXSOCKETS; i++)
207 {
208 socketList[i] = NULL;
209 }
210 firstAvailable = 0;
b7ceceb1 211
d8abb95f
VZ
212 // we don't link with wsock32.dll (or ws2 in CE case) statically to avoid
213 // dependencies on it for all the application using wx even if they don't use
214 // sockets
215#ifdef __WXWINCE__
9a83f860 216 #define WINSOCK_DLL_NAME wxT("ws2.dll")
d8abb95f 217#else
9a83f860 218 #define WINSOCK_DLL_NAME wxT("wsock32.dll")
d8abb95f
VZ
219#endif
220
221 gs_wsock32dll.Load(WINSOCK_DLL_NAME, wxDL_VERBATIM | wxDL_QUIET);
222 if ( !gs_wsock32dll.IsLoaded() )
223 return false;
224
dbfb61b3 225#ifndef __WXWINCE__
d8abb95f
VZ
226 wxDL_INIT_FUNC(gs_, WSAAsyncSelect, gs_wsock32dll);
227 if ( !gs_WSAAsyncSelect )
228 return false;
dbfb61b3 229#else
d8abb95f
VZ
230 wxDL_INIT_FUNC(gs_, WSAEventSelect, gs_wsock32dll);
231 if ( !gs_WSAEventSelect )
232 return false;
1c6dd11c 233
d8abb95f
VZ
234 wxDL_INIT_FUNC(gs_, WSACreateEvent, gs_wsock32dll);
235 if ( !gs_WSACreateEvent )
236 return false;
84aa68c4 237
d8abb95f
VZ
238 wxDL_INIT_FUNC(gs_, WSAWaitForMultipleEvents, gs_wsock32dll);
239 if ( !gs_WSAWaitForMultipleEvents )
240 return false;
84aa68c4 241
d8abb95f
VZ
242 wxDL_INIT_FUNC(gs_, WSAEnumNetworkEvents, gs_wsock32dll);
243 if ( !gs_WSAEnumNetworkEvents )
244 return false;
84aa68c4 245
d8abb95f
VZ
246 currSocket = 0;
247#endif // !__WXWINCE__/__WXWINCE__
7ec69821 248
51fe4b60
VZ
249 // finally initialize WinSock
250 WSADATA wsaData;
251 return WSAStartup((1 << 8) | 1, &wsaData) == 0;
b7ceceb1
DE
252}
253
51fe4b60 254void wxSocketMSWManager::OnExit()
b7ceceb1 255{
dbfb61b3 256#ifdef __WXWINCE__
1c6dd11c 257/* Delete the threads here */
7ec69821
WS
258 for(unsigned int i=0; i < currSocket; i++)
259 CloseHandle(hThread[i]);
dbfb61b3 260#endif
b7ceceb1
DE
261 /* Destroy internal window */
262 DestroyWindow(hWin);
e8d9821d 263 UnregisterClass(CLASSNAME, wxGetInstance());
b7ceceb1 264
51fe4b60 265 WSACleanup();
d8abb95f
VZ
266
267 gs_wsock32dll.Unload();
b7ceceb1
DE
268}
269
270/* Per-socket GUI initialization / cleanup */
271
51fe4b60
VZ
272wxSocketImplMSW::wxSocketImplMSW(wxSocketBase& wxsocket)
273 : wxSocketImpl(wxsocket)
b7ceceb1 274{
b7ceceb1 275 /* Allocate a new message number for this socket */
f2c94e8a 276 wxCRIT_SECT_LOCKER(lock, gs_critical);
b7ceceb1 277
51fe4b60 278 int i = firstAvailable;
b7ceceb1
DE
279 while (socketList[i] != NULL)
280 {
281 i = (i + 1) % MAXSOCKETS;
282
283 if (i == firstAvailable) /* abort! */
284 {
51fe4b60
VZ
285 m_msgnumber = 0; // invalid
286 return;
b7ceceb1
DE
287 }
288 }
51fe4b60 289 socketList[i] = this;
b7ceceb1 290 firstAvailable = (i + 1) % MAXSOCKETS;
51fe4b60 291 m_msgnumber = (i + WM_USER);
f0fbbe23
VZ
292}
293
51fe4b60 294wxSocketImplMSW::~wxSocketImplMSW()
b7ceceb1
DE
295{
296 /* Remove the socket from the list */
f2c94e8a 297 wxCRIT_SECT_LOCKER(lock, gs_critical);
cab9b205 298
51fe4b60 299 if ( m_msgnumber )
eb97543d 300 {
cab9b205
VZ
301 // we need to remove any pending messages for this socket to avoid having
302 // them sent to a new socket which could reuse the same message number as
303 // soon as we destroy this one
304 MSG msg;
51fe4b60 305 while ( ::PeekMessage(&msg, hWin, m_msgnumber, m_msgnumber, PM_REMOVE) )
cab9b205
VZ
306 ;
307
51fe4b60 308 socketList[m_msgnumber - WM_USER] = NULL;
cab9b205 309 }
eb97543d 310 //else: the socket has never been created successfully
b7ceceb1
DE
311}
312
313/* Windows proc for asynchronous event handling */
314
51fe4b60 315LRESULT CALLBACK wxSocket_Internal_WinProc(HWND hWnd,
b7ceceb1
DE
316 UINT uMsg,
317 WPARAM wParam,
318 LPARAM lParam)
319{
f2c94e8a
VZ
320 if ( uMsg < WM_USER || uMsg > (WM_USER + MAXSOCKETS - 1))
321 return DefWindowProc(hWnd, uMsg, wParam, lParam);
b7ceceb1 322
f2c94e8a 323 wxSocketImplMSW *socket;
5e9238f9 324 wxSocketNotify event = (wxSocketNotify)-1;
b7ceceb1 325 {
f2c94e8a
VZ
326 wxCRIT_SECT_LOCKER(lock, gs_critical);
327
328 socket = socketList[(uMsg - WM_USER)];
5e9238f9
VZ
329 if ( !socket )
330 return 0;
331
78690009
VZ
332 // the socket may be already closed but we could still receive
333 // notifications for it sent (asynchronously) before it got closed
334 if ( socket->m_fd == INVALID_SOCKET )
335 return 0;
336
5e9238f9
VZ
337 wxASSERT_MSG( socket->m_fd == (SOCKET)wParam,
338 "mismatch between message and socket?" );
f2c94e8a 339
12cc077e 340 switch ( WSAGETSELECTEVENT(lParam) )
b7ceceb1 341 {
5e9238f9 342 case FD_READ:
12cc077e
VZ
343 // We may get a FD_READ notification even when there is no data
344 // to read on the socket, in particular this happens on socket
345 // creation when we seem to always get FD_CONNECT, FD_WRITE and
346 // FD_READ notifications all at once (but it doesn't happen
347 // only then). Ignore such dummy notifications.
348 {
349 fd_set fds;
917b0085 350 timeval tv = { 0, 0 };
12cc077e
VZ
351
352 wxFD_ZERO(&fds);
353 wxFD_SET(socket->m_fd, &fds);
354
355 if ( select(socket->m_fd + 1, &fds, NULL, NULL, &tv) != 1 )
356 return 0;
357 }
358
5e9238f9
VZ
359 event = wxSOCKET_INPUT;
360 break;
361
362 case FD_WRITE:
363 event = wxSOCKET_OUTPUT;
364 break;
365
366 case FD_ACCEPT:
367 event = wxSOCKET_CONNECTION;
368 break;
369
370 case FD_CONNECT:
371 event = WSAGETSELECTERROR(lParam) ? wxSOCKET_LOST
372 : wxSOCKET_CONNECTION;
373 break;
374
375 case FD_CLOSE:
376 event = wxSOCKET_LOST;
377 break;
378
379 default:
380 wxFAIL_MSG( "unexpected socket notification" );
381 return 0;
b7ceceb1 382 }
f2c94e8a 383 } // unlock gs_critical
b7ceceb1 384
5e9238f9 385 socket->NotifyOnStateChange(event);
b7ceceb1 386
5e9238f9 387 return 0;
b7ceceb1
DE
388}
389
f0fbbe23 390/*
b7ceceb1
DE
391 * Enable all event notifications; we need to be notified of all
392 * events for internal processing, but we will only notify users
f0fbbe23 393 * when an appropriate callback function has been installed.
b7ceceb1 394 */
51fe4b60
VZ
395void wxSocketMSWManager::Install_Callback(wxSocketImpl *socket_,
396 wxSocketNotify WXUNUSED(event))
b7ceceb1 397{
51fe4b60
VZ
398 wxSocketImplMSW * const socket = static_cast<wxSocketImplMSW *>(socket_);
399
b7ceceb1
DE
400 if (socket->m_fd != INVALID_SOCKET)
401 {
402 /* We could probably just subscribe to all events regardless
403 * of the socket type, but MS recommends to do it this way.
404 */
405 long lEvent = socket->m_server?
406 FD_ACCEPT : (FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE);
dbfb61b3 407#ifndef __WXWINCE__
1c8681b4 408 gs_WSAAsyncSelect(socket->m_fd, hWin, socket->m_msgnumber, lEvent);
dbfb61b3
JS
409#else
410/*
411* WinCE creates a thread for socket event handling.
1c6dd11c 412* All needed parameters get passed through the thread_data structure.
dbfb61b3 413*/
84aa68c4 414
7ec69821
WS
415 thread_data* d = new thread_data;
416 d->lEvent = lEvent;
417 d->hEvtWin = hWin;
418 d->msgnumber = socket->m_msgnumber;
419 d->fd = socket->m_fd;
420 socketHash[socket->m_fd] = true;
421 hThread[currSocket++] = CreateThread(NULL, 0, &SocketThread,(LPVOID)d, 0, NULL);
dbfb61b3 422#endif
b7ceceb1
DE
423 }
424}
425
f0fbbe23
VZ
426/*
427 * Disable event notifications (used when shutting down the socket)
b7ceceb1 428 */
51fe4b60 429void wxSocketMSWManager::Uninstall_Callback(wxSocketImpl *socket_,
c363ead1 430 wxSocketNotify WXUNUSED(event))
b7ceceb1 431{
51fe4b60
VZ
432 wxSocketImplMSW * const socket = static_cast<wxSocketImplMSW *>(socket_);
433
b7ceceb1
DE
434 if (socket->m_fd != INVALID_SOCKET)
435 {
dbfb61b3 436#ifndef __WXWINCE__
1c8681b4 437 gs_WSAAsyncSelect(socket->m_fd, hWin, socket->m_msgnumber, 0);
dbfb61b3 438#else
7ec69821
WS
439 //Destroy the thread
440 socketHash[socket->m_fd] = false;
dbfb61b3 441#endif
b7ceceb1
DE
442 }
443}
444
51fe4b60 445// set the wxBase variable to point to our wxSocketManager implementation
2804f77d 446//
51fe4b60 447// see comments in wx/apptrait.h for the explanation of why do we do it
2804f77d
VZ
448// like this
449static struct ManagerSetter
450{
451 ManagerSetter()
452 {
51fe4b60 453 static wxSocketMSWManager s_manager;
2804f77d
VZ
454 wxAppTraits::SetDefaultSocketManager(&s_manager);
455 }
a3cf8dca 456} gs_managerSetter;
b7ceceb1 457
4f260c9c
VZ
458// see the relative linker macro in socket.cpp
459wxFORCE_LINK_THIS_MODULE( mswsocket );
460
116de991
VZ
461// ============================================================================
462// wxSocketImpl implementation
463// ============================================================================
464
116de991
VZ
465void wxSocketImplMSW::DoClose()
466{
c363ead1 467 wxSocketManager::Get()->Uninstall_Callback(this);
116de991
VZ
468
469 closesocket(m_fd);
470}
471
64b1cea0 472wxSocketError wxSocketImplMSW::GetLastError() const
116de991 473{
2b036c4b 474 switch ( WSAGetLastError() )
116de991 475 {
2b036c4b
VZ
476 case 0:
477 return wxSOCKET_NOERROR;
116de991 478
2b036c4b
VZ
479 case WSAENOTSOCK:
480 return wxSOCKET_INVSOCK;
116de991 481
2b036c4b 482 case WSAEWOULDBLOCK:
116de991 483 return wxSOCKET_WOULDBLOCK;
116de991 484
2b036c4b
VZ
485 default:
486 return wxSOCKET_IOERR;
116de991 487 }
116de991
VZ
488}
489
2804f77d 490#endif // wxUSE_SOCKETS