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