]> git.saurik.com Git - wxWidgets.git/blame - src/msw/sockmsw.cpp
Ignore the time portion of the datetime object when setting the date.
[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$
10// License: wxWindows licence
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()
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
51fe4b60 61#define CLASSNAME TEXT("_wxSocket_Internal_Window_Class")
b7ceceb1
DE
62
63/* implemented in utils.cpp */
32524c8f 64extern "C" WXDLLIMPEXP_BASE HWND
b7ceceb1
DE
65wxCreateHiddenWindow(LPCTSTR *pclassname, LPCTSTR classname, WNDPROC wndproc);
66
51fe4b60 67/* Maximum number of different wxSocket objects at a given time.
b7ceceb1
DE
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
dbfb61b3 77#ifndef __WXWINCE__
d8abb95f 78typedef int (PASCAL *WSAAsyncSelect_t)(SOCKET,HWND,u_int,long);
dbfb61b3
JS
79#else
80/* Typedef the needed function prototypes and the WSANETWORKEVENTS structure
81*/
82typedef struct _WSANETWORKEVENTS {
83 long lNetworkEvents;
84 int iErrorCode[10];
85} WSANETWORKEVENTS, FAR * LPWSANETWORKEVENTS;
d8abb95f
VZ
86typedef HANDLE (PASCAL *WSACreateEvent_t)();
87typedef int (PASCAL *WSAEventSelect_t)(SOCKET,HANDLE,long);
88typedef int (PASCAL *WSAWaitForMultipleEvents_t)(long,HANDLE,BOOL,long,BOOL);
89typedef int (PASCAL *WSAEnumNetworkEvents_t)(SOCKET,HANDLE,LPWSANETWORKEVENTS);
dbfb61b3 90#endif //__WXWINCE__
b7ceceb1 91
51fe4b60 92LRESULT CALLBACK wxSocket_Internal_WinProc(HWND, UINT, WPARAM, LPARAM);
c90cc42e 93
b7ceceb1
DE
94/* Global variables */
95
b7ceceb1 96static HWND hWin;
f2c94e8a 97wxCRIT_SECT_DECLARE_MEMBER(gs_critical);
51fe4b60 98static wxSocketImplMSW *socketList[MAXSOCKETS];
b7ceceb1 99static int firstAvailable;
dbfb61b3
JS
100
101#ifndef __WXWINCE__
d8abb95f 102static WSAAsyncSelect_t gs_WSAAsyncSelect = NULL;
dbfb61b3 103#else
84aa68c4 104static SocketHash socketHash;
dbfb61b3
JS
105static unsigned int currSocket;
106HANDLE hThread[MAXSOCKETS];
d8abb95f
VZ
107static WSACreateEvent_t gs_WSACreateEvent = NULL;
108static WSAEventSelect_t gs_WSAEventSelect = NULL;
109static WSAWaitForMultipleEvents_t gs_WSAWaitForMultipleEvents = NULL;
110static WSAEnumNetworkEvents_t gs_WSAEnumNetworkEvents = NULL;
dbfb61b3
JS
111/* This structure will be used to pass data on to the thread that handles socket events.
112*/
113typedef struct thread_data{
7ec69821
WS
114 HWND hEvtWin;
115 unsigned long msgnumber;
116 unsigned long fd;
117 unsigned long lEvent;
dbfb61b3
JS
118}thread_data;
119#endif
120
dbfb61b3 121#ifdef __WXWINCE__
d8abb95f
VZ
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.
dbfb61b3
JS
126*/
127DWORD WINAPI SocketThread(LPVOID data)
128{
7ec69821
WS
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;
dbfb61b3
JS
166}
167#endif
168
2804f77d 169// ----------------------------------------------------------------------------
51fe4b60 170// MSW implementation of wxSocketManager
2804f77d 171// ----------------------------------------------------------------------------
dbfb61b3 172
51fe4b60 173class wxSocketMSWManager : public wxSocketManager
1c6dd11c 174{
2804f77d
VZ
175public:
176 virtual bool OnInit();
177 virtual void OnExit();
178
51fe4b60
VZ
179 virtual wxSocketImpl *CreateSocket(wxSocketBase& wxsocket)
180 {
181 return new wxSocketImplMSW(wxsocket);
182 }
c363ead1
VZ
183 virtual void Install_Callback(wxSocketImpl *socket,
184 wxSocketNotify event = wxSOCKET_LOST);
185 virtual void Uninstall_Callback(wxSocketImpl *socket,
186 wxSocketNotify event = wxSOCKET_LOST);
d8abb95f
VZ
187
188private:
189 static wxDynamicLibrary gs_wsock32dll;
2804f77d 190};
c90cc42e 191
d8abb95f
VZ
192wxDynamicLibrary wxSocketMSWManager::gs_wsock32dll;
193
51fe4b60 194bool wxSocketMSWManager::OnInit()
b7ceceb1 195{
84aa68c4
JS
196 static LPCTSTR pclassname = NULL;
197 int i;
b7ceceb1 198
84aa68c4 199 /* Create internal window for event notifications */
51fe4b60 200 hWin = wxCreateHiddenWindow(&pclassname, CLASSNAME, wxSocket_Internal_WinProc);
84aa68c4
JS
201 if (!hWin)
202 return false;
b7ceceb1 203
84aa68c4 204 /* Initialize socket list */
84aa68c4
JS
205 for (i = 0; i < MAXSOCKETS; i++)
206 {
207 socketList[i] = NULL;
208 }
209 firstAvailable = 0;
b7ceceb1 210
d8abb95f
VZ
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__
9a83f860 215 #define WINSOCK_DLL_NAME wxT("ws2.dll")
d8abb95f 216#else
9a83f860 217 #define WINSOCK_DLL_NAME wxT("wsock32.dll")
d8abb95f
VZ
218#endif
219
220 gs_wsock32dll.Load(WINSOCK_DLL_NAME, wxDL_VERBATIM | wxDL_QUIET);
221 if ( !gs_wsock32dll.IsLoaded() )
222 return false;
223
dbfb61b3 224#ifndef __WXWINCE__
d8abb95f
VZ
225 wxDL_INIT_FUNC(gs_, WSAAsyncSelect, gs_wsock32dll);
226 if ( !gs_WSAAsyncSelect )
227 return false;
dbfb61b3 228#else
d8abb95f
VZ
229 wxDL_INIT_FUNC(gs_, WSAEventSelect, gs_wsock32dll);
230 if ( !gs_WSAEventSelect )
231 return false;
1c6dd11c 232
d8abb95f
VZ
233 wxDL_INIT_FUNC(gs_, WSACreateEvent, gs_wsock32dll);
234 if ( !gs_WSACreateEvent )
235 return false;
84aa68c4 236
d8abb95f
VZ
237 wxDL_INIT_FUNC(gs_, WSAWaitForMultipleEvents, gs_wsock32dll);
238 if ( !gs_WSAWaitForMultipleEvents )
239 return false;
84aa68c4 240
d8abb95f
VZ
241 wxDL_INIT_FUNC(gs_, WSAEnumNetworkEvents, gs_wsock32dll);
242 if ( !gs_WSAEnumNetworkEvents )
243 return false;
84aa68c4 244
d8abb95f
VZ
245 currSocket = 0;
246#endif // !__WXWINCE__/__WXWINCE__
7ec69821 247
51fe4b60
VZ
248 // finally initialize WinSock
249 WSADATA wsaData;
250 return WSAStartup((1 << 8) | 1, &wsaData) == 0;
b7ceceb1
DE
251}
252
51fe4b60 253void wxSocketMSWManager::OnExit()
b7ceceb1 254{
dbfb61b3 255#ifdef __WXWINCE__
1c6dd11c 256/* Delete the threads here */
7ec69821
WS
257 for(unsigned int i=0; i < currSocket; i++)
258 CloseHandle(hThread[i]);
dbfb61b3 259#endif
b7ceceb1
DE
260 /* Destroy internal window */
261 DestroyWindow(hWin);
e8d9821d 262 UnregisterClass(CLASSNAME, wxGetInstance());
b7ceceb1 263
51fe4b60 264 WSACleanup();
d8abb95f
VZ
265
266 gs_wsock32dll.Unload();
b7ceceb1
DE
267}
268
269/* Per-socket GUI initialization / cleanup */
270
51fe4b60
VZ
271wxSocketImplMSW::wxSocketImplMSW(wxSocketBase& wxsocket)
272 : wxSocketImpl(wxsocket)
b7ceceb1 273{
b7ceceb1 274 /* Allocate a new message number for this socket */
f2c94e8a 275 wxCRIT_SECT_LOCKER(lock, gs_critical);
b7ceceb1 276
51fe4b60 277 int i = firstAvailable;
b7ceceb1
DE
278 while (socketList[i] != NULL)
279 {
280 i = (i + 1) % MAXSOCKETS;
281
282 if (i == firstAvailable) /* abort! */
283 {
51fe4b60
VZ
284 m_msgnumber = 0; // invalid
285 return;
b7ceceb1
DE
286 }
287 }
51fe4b60 288 socketList[i] = this;
b7ceceb1 289 firstAvailable = (i + 1) % MAXSOCKETS;
51fe4b60 290 m_msgnumber = (i + WM_USER);
f0fbbe23
VZ
291}
292
51fe4b60 293wxSocketImplMSW::~wxSocketImplMSW()
b7ceceb1
DE
294{
295 /* Remove the socket from the list */
f2c94e8a 296 wxCRIT_SECT_LOCKER(lock, gs_critical);
cab9b205 297
51fe4b60 298 if ( m_msgnumber )
eb97543d 299 {
cab9b205
VZ
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;
51fe4b60 304 while ( ::PeekMessage(&msg, hWin, m_msgnumber, m_msgnumber, PM_REMOVE) )
cab9b205
VZ
305 ;
306
51fe4b60 307 socketList[m_msgnumber - WM_USER] = NULL;
cab9b205 308 }
eb97543d 309 //else: the socket has never been created successfully
b7ceceb1
DE
310}
311
312/* Windows proc for asynchronous event handling */
313
51fe4b60 314LRESULT CALLBACK wxSocket_Internal_WinProc(HWND hWnd,
b7ceceb1
DE
315 UINT uMsg,
316 WPARAM wParam,
317 LPARAM lParam)
318{
f2c94e8a
VZ
319 if ( uMsg < WM_USER || uMsg > (WM_USER + MAXSOCKETS - 1))
320 return DefWindowProc(hWnd, uMsg, wParam, lParam);
b7ceceb1 321
f2c94e8a 322 wxSocketImplMSW *socket;
5e9238f9 323 wxSocketNotify event = (wxSocketNotify)-1;
b7ceceb1 324 {
f2c94e8a
VZ
325 wxCRIT_SECT_LOCKER(lock, gs_critical);
326
327 socket = socketList[(uMsg - WM_USER)];
5e9238f9
VZ
328 if ( !socket )
329 return 0;
330
78690009
VZ
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
5e9238f9
VZ
336 wxASSERT_MSG( socket->m_fd == (SOCKET)wParam,
337 "mismatch between message and socket?" );
f2c94e8a 338
5e9238f9 339 switch WSAGETSELECTEVENT(lParam)
b7ceceb1 340 {
5e9238f9
VZ
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;
b7ceceb1 365 }
f2c94e8a 366 } // unlock gs_critical
b7ceceb1 367
5e9238f9 368 socket->NotifyOnStateChange(event);
b7ceceb1 369
5e9238f9 370 return 0;
b7ceceb1
DE
371}
372
f0fbbe23 373/*
b7ceceb1
DE
374 * Enable all event notifications; we need to be notified of all
375 * events for internal processing, but we will only notify users
f0fbbe23 376 * when an appropriate callback function has been installed.
b7ceceb1 377 */
51fe4b60
VZ
378void wxSocketMSWManager::Install_Callback(wxSocketImpl *socket_,
379 wxSocketNotify WXUNUSED(event))
b7ceceb1 380{
51fe4b60
VZ
381 wxSocketImplMSW * const socket = static_cast<wxSocketImplMSW *>(socket_);
382
b7ceceb1
DE
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);
dbfb61b3 390#ifndef __WXWINCE__
1c8681b4 391 gs_WSAAsyncSelect(socket->m_fd, hWin, socket->m_msgnumber, lEvent);
dbfb61b3
JS
392#else
393/*
394* WinCE creates a thread for socket event handling.
1c6dd11c 395* All needed parameters get passed through the thread_data structure.
dbfb61b3 396*/
84aa68c4 397
7ec69821
WS
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);
dbfb61b3 405#endif
b7ceceb1
DE
406 }
407}
408
f0fbbe23
VZ
409/*
410 * Disable event notifications (used when shutting down the socket)
b7ceceb1 411 */
51fe4b60 412void wxSocketMSWManager::Uninstall_Callback(wxSocketImpl *socket_,
c363ead1 413 wxSocketNotify WXUNUSED(event))
b7ceceb1 414{
51fe4b60
VZ
415 wxSocketImplMSW * const socket = static_cast<wxSocketImplMSW *>(socket_);
416
b7ceceb1
DE
417 if (socket->m_fd != INVALID_SOCKET)
418 {
dbfb61b3 419#ifndef __WXWINCE__
1c8681b4 420 gs_WSAAsyncSelect(socket->m_fd, hWin, socket->m_msgnumber, 0);
dbfb61b3 421#else
7ec69821
WS
422 //Destroy the thread
423 socketHash[socket->m_fd] = false;
dbfb61b3 424#endif
b7ceceb1
DE
425 }
426}
427
51fe4b60 428// set the wxBase variable to point to our wxSocketManager implementation
2804f77d 429//
51fe4b60 430// see comments in wx/apptrait.h for the explanation of why do we do it
2804f77d
VZ
431// like this
432static struct ManagerSetter
433{
434 ManagerSetter()
435 {
51fe4b60 436 static wxSocketMSWManager s_manager;
2804f77d
VZ
437 wxAppTraits::SetDefaultSocketManager(&s_manager);
438 }
a3cf8dca 439} gs_managerSetter;
b7ceceb1 440
4f260c9c
VZ
441// see the relative linker macro in socket.cpp
442wxFORCE_LINK_THIS_MODULE( mswsocket );
443
116de991
VZ
444// ============================================================================
445// wxSocketImpl implementation
446// ============================================================================
447
116de991
VZ
448void wxSocketImplMSW::DoClose()
449{
c363ead1 450 wxSocketManager::Get()->Uninstall_Callback(this);
116de991
VZ
451
452 closesocket(m_fd);
453}
454
64b1cea0 455wxSocketError wxSocketImplMSW::GetLastError() const
116de991 456{
2b036c4b 457 switch ( WSAGetLastError() )
116de991 458 {
2b036c4b
VZ
459 case 0:
460 return wxSOCKET_NOERROR;
116de991 461
2b036c4b
VZ
462 case WSAENOTSOCK:
463 return wxSOCKET_INVSOCK;
116de991 464
2b036c4b 465 case WSAEWOULDBLOCK:
116de991 466 return wxSOCKET_WOULDBLOCK;
116de991 467
2b036c4b
VZ
468 default:
469 return wxSOCKET_IOERR;
116de991 470 }
116de991
VZ
471}
472
2804f77d 473#endif // wxUSE_SOCKETS