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