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