]> git.saurik.com Git - wxWidgets.git/blob - src/msw/gsocket.cpp
added pragmas to disable icc warning when va_arg is used with a pointer type
[wxWidgets.git] / src / msw / gsocket.cpp
1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket)
3 * Name: gsocket.cpp
4 * Copyright: (c) Guilhem Lavaux
5 * Licence: wxWindows Licence
6 * Author: Guillermo Rodriguez Garcia <guille@iies.es>
7 * Purpose: GSocket main MSW file
8 * Licence: The wxWindows licence
9 * CVSID: $Id$
10 * -------------------------------------------------------------------------
11 */
12
13 // For compilers that support precompilation, includes "wx.h".
14 #include "wx/wxprec.h"
15
16 #ifdef __BORLANDC__
17 #pragma hdrstop
18 #endif
19
20 #ifdef _MSC_VER
21 /* RPCNOTIFICATION_ROUTINE in rasasync.h (included from winsock.h),
22 * warning: conditional expression is constant.
23 */
24 # pragma warning(disable:4115)
25 /* FD_SET,
26 * warning: named type definition in parentheses.
27 */
28 # pragma warning(disable:4127)
29 /* GAddress_UNIX_GetPath,
30 * warning: unreferenced formal parameter.
31 */
32 # pragma warning(disable:4100)
33
34 #ifdef __WXWINCE__
35 /* windows.h results in tons of warnings at max warning level */
36 # ifdef _MSC_VER
37 # pragma warning(push, 1)
38 # endif
39 # include <windows.h>
40 # ifdef _MSC_VER
41 # pragma warning(pop)
42 # pragma warning(disable:4514)
43 # endif
44 #endif
45
46 #endif /* _MSC_VER */
47
48 #if defined(__CYGWIN__)
49 //CYGWIN gives annoying warning about runtime stuff if we don't do this
50 # define USE_SYS_TYPES_FD_SET
51 # include <sys/types.h>
52 #endif
53
54 #include <winsock.h>
55
56 #ifndef __GSOCKET_STANDALONE__
57 # include "wx/platform.h"
58 # include "wx/setup.h"
59 #endif
60
61 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
62
63 #ifndef __GSOCKET_STANDALONE__
64 # include "wx/msw/gsockmsw.h"
65 # include "wx/gsocket.h"
66 #else
67 # include "gsockmsw.h"
68 # include "gsocket.h"
69 #endif /* __GSOCKET_STANDALONE__ */
70
71 #ifndef __WXWINCE__
72 #include <assert.h>
73 #else
74 #define assert(x)
75 #ifndef isdigit
76 #define isdigit(x) (x > 47 && x < 58)
77 #endif
78 #include "wx/msw/wince/net.h"
79 #endif
80
81 #include <string.h>
82 #include <stdio.h>
83 #include <stdlib.h>
84 #include <stddef.h>
85 #include <ctype.h>
86
87 /* if we use configure for MSW WX_SOCKLEN_T will be already defined */
88 #ifndef WX_SOCKLEN_T
89 # define WX_SOCKLEN_T int
90 #endif
91
92 /* Table of GUI-related functions. We must call them indirectly because
93 * of wxBase and GUI separation: */
94
95 static GSocketGUIFunctionsTable *gs_gui_functions;
96
97 class GSocketGUIFunctionsTableNull: public GSocketGUIFunctionsTable
98 {
99 public:
100 virtual bool OnInit();
101 virtual void OnExit();
102 virtual bool CanUseEventLoop();
103 virtual bool Init_Socket(GSocket *socket);
104 virtual void Destroy_Socket(GSocket *socket);
105 virtual void Enable_Events(GSocket *socket);
106 virtual void Disable_Events(GSocket *socket);
107 };
108
109 bool GSocketGUIFunctionsTableNull::OnInit()
110 { return true; }
111 void GSocketGUIFunctionsTableNull::OnExit()
112 {}
113 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
114 { return false; }
115 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket *WXUNUSED(socket))
116 { return true; }
117 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket *WXUNUSED(socket))
118 {}
119 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket *WXUNUSED(socket))
120 {}
121 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket *WXUNUSED(socket))
122 {}
123 /* Global initialisers */
124
125 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable *guifunc)
126 {
127 gs_gui_functions = guifunc;
128 }
129
130 int GSocket_Init(void)
131 {
132 WSADATA wsaData;
133
134 if (!gs_gui_functions)
135 {
136 static GSocketGUIFunctionsTableNull table;
137 gs_gui_functions = &table;
138 }
139 if ( !gs_gui_functions->OnInit() )
140 {
141 return 0;
142 }
143
144 /* Initialize WinSocket */
145 return (WSAStartup((1 << 8) | 1, &wsaData) == 0);
146 }
147
148 void GSocket_Cleanup(void)
149 {
150 if (gs_gui_functions)
151 {
152 gs_gui_functions->OnExit();
153 }
154
155 /* Cleanup WinSocket */
156 WSACleanup();
157 }
158
159 /* Constructors / Destructors for GSocket */
160
161 GSocket::GSocket()
162 {
163 int i;
164
165 m_fd = INVALID_SOCKET;
166 for (i = 0; i < GSOCK_MAX_EVENT; i++)
167 {
168 m_cbacks[i] = NULL;
169 }
170 m_detected = 0;
171 m_local = NULL;
172 m_peer = NULL;
173 m_error = GSOCK_NOERROR;
174 m_server = false;
175 m_stream = true;
176 m_non_blocking = false;
177 m_timeout.tv_sec = 10 * 60; /* 10 minutes */
178 m_timeout.tv_usec = 0;
179 m_establishing = false;
180 m_reusable = false;
181
182 assert(gs_gui_functions);
183 /* Per-socket GUI-specific initialization */
184 m_ok = gs_gui_functions->Init_Socket(this);
185 }
186
187 void GSocket::Close()
188 {
189 gs_gui_functions->Disable_Events(this);
190 closesocket(m_fd);
191 m_fd = INVALID_SOCKET;
192 }
193
194 GSocket::~GSocket()
195 {
196 assert(this);
197
198 /* Per-socket GUI-specific cleanup */
199 gs_gui_functions->Destroy_Socket(this);
200
201 /* Check that the socket is really shutdowned */
202 if (m_fd != INVALID_SOCKET)
203 Shutdown();
204
205 /* Destroy private addresses */
206 if (m_local)
207 GAddress_destroy(m_local);
208
209 if (m_peer)
210 GAddress_destroy(m_peer);
211 }
212
213 /* GSocket_Shutdown:
214 * Disallow further read/write operations on this socket, close
215 * the fd and disable all callbacks.
216 */
217 void GSocket::Shutdown()
218 {
219 int evt;
220
221 assert(this);
222
223 /* If socket has been created, shutdown it */
224 if (m_fd != INVALID_SOCKET)
225 {
226 shutdown(m_fd, 2);
227 Close();
228 }
229
230 /* Disable GUI callbacks */
231 for (evt = 0; evt < GSOCK_MAX_EVENT; evt++)
232 m_cbacks[evt] = NULL;
233
234 m_detected = GSOCK_LOST_FLAG;
235 }
236
237 /* Address handling */
238
239 /* GSocket_SetLocal:
240 * GSocket_GetLocal:
241 * GSocket_SetPeer:
242 * GSocket_GetPeer:
243 * Set or get the local or peer address for this socket. The 'set'
244 * functions return GSOCK_NOERROR on success, an error code otherwise.
245 * The 'get' functions return a pointer to a GAddress object on success,
246 * or NULL otherwise, in which case they set the error code of the
247 * corresponding GSocket.
248 *
249 * Error codes:
250 * GSOCK_INVSOCK - the socket is not valid.
251 * GSOCK_INVADDR - the address is not valid.
252 */
253 GSocketError GSocket::SetLocal(GAddress *address)
254 {
255 assert(this);
256
257 /* the socket must be initialized, or it must be a server */
258 if (m_fd != INVALID_SOCKET && !m_server)
259 {
260 m_error = GSOCK_INVSOCK;
261 return GSOCK_INVSOCK;
262 }
263
264 /* check address */
265 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
266 {
267 m_error = GSOCK_INVADDR;
268 return GSOCK_INVADDR;
269 }
270
271 if (m_local)
272 GAddress_destroy(m_local);
273
274 m_local = GAddress_copy(address);
275
276 return GSOCK_NOERROR;
277 }
278
279 GSocketError GSocket::SetPeer(GAddress *address)
280 {
281 assert(this);
282
283 /* check address */
284 if (address == NULL || address->m_family == GSOCK_NOFAMILY)
285 {
286 m_error = GSOCK_INVADDR;
287 return GSOCK_INVADDR;
288 }
289
290 if (m_peer)
291 GAddress_destroy(m_peer);
292
293 m_peer = GAddress_copy(address);
294
295 return GSOCK_NOERROR;
296 }
297
298 GAddress *GSocket::GetLocal()
299 {
300 GAddress *address;
301 struct sockaddr addr;
302 WX_SOCKLEN_T size = sizeof(addr);
303 GSocketError err;
304
305 assert(this);
306
307 /* try to get it from the m_local var first */
308 if (m_local)
309 return GAddress_copy(m_local);
310
311 /* else, if the socket is initialized, try getsockname */
312 if (m_fd == INVALID_SOCKET)
313 {
314 m_error = GSOCK_INVSOCK;
315 return NULL;
316 }
317
318 if (getsockname(m_fd, &addr, &size) == SOCKET_ERROR)
319 {
320 m_error = GSOCK_IOERR;
321 return NULL;
322 }
323
324 /* got a valid address from getsockname, create a GAddress object */
325 if ((address = GAddress_new()) == NULL)
326 {
327 m_error = GSOCK_MEMERR;
328 return NULL;
329 }
330
331 if ((err = _GAddress_translate_from(address, &addr, size)) != GSOCK_NOERROR)
332 {
333 GAddress_destroy(address);
334 m_error = err;
335 return NULL;
336 }
337
338 return address;
339 }
340
341 GAddress *GSocket::GetPeer()
342 {
343 assert(this);
344
345 /* try to get it from the m_peer var */
346 if (m_peer)
347 return GAddress_copy(m_peer);
348
349 return NULL;
350 }
351
352 /* Server specific parts */
353
354 /* GSocket_SetServer:
355 * Sets up this socket as a server. The local address must have been
356 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
357 * Returns GSOCK_NOERROR on success, one of the following otherwise:
358 *
359 * Error codes:
360 * GSOCK_INVSOCK - the socket is in use.
361 * GSOCK_INVADDR - the local address has not been set.
362 * GSOCK_IOERR - low-level error.
363 */
364 GSocketError GSocket::SetServer()
365 {
366 u_long arg = 1;
367
368 assert(this);
369
370 /* must not be in use */
371 if (m_fd != INVALID_SOCKET)
372 {
373 m_error = GSOCK_INVSOCK;
374 return GSOCK_INVSOCK;
375 }
376
377 /* the local addr must have been set */
378 if (!m_local)
379 {
380 m_error = GSOCK_INVADDR;
381 return GSOCK_INVADDR;
382 }
383
384 /* Initialize all fields */
385 m_server = true;
386 m_stream = true;
387
388 /* Create the socket */
389 m_fd = socket(m_local->m_realfamily, SOCK_STREAM, 0);
390
391 if (m_fd == INVALID_SOCKET)
392 {
393 m_error = GSOCK_IOERR;
394 return GSOCK_IOERR;
395 }
396
397 ioctlsocket(m_fd, FIONBIO, (u_long FAR *) &arg);
398 gs_gui_functions->Enable_Events(this);
399
400 /* allow a socket to re-bind if the socket is in the TIME_WAIT
401 state after being previously closed.
402 */
403 if (m_reusable) {
404 setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&arg, sizeof(u_long));
405 }
406
407 /* Bind to the local address,
408 * retrieve the actual address bound,
409 * and listen up to 5 connections.
410 */
411 if ((bind(m_fd, m_local->m_addr, m_local->m_len) != 0) ||
412 (getsockname(m_fd,
413 m_local->m_addr,
414 (WX_SOCKLEN_T *)&m_local->m_len) != 0) ||
415 (listen(m_fd, 5) != 0))
416 {
417 Close();
418 m_error = GSOCK_IOERR;
419 return GSOCK_IOERR;
420 }
421
422 return GSOCK_NOERROR;
423 }
424
425 /* GSocket_WaitConnection:
426 * Waits for an incoming client connection. Returns a pointer to
427 * a GSocket object, or NULL if there was an error, in which case
428 * the last error field will be updated for the calling GSocket.
429 *
430 * Error codes (set in the calling GSocket)
431 * GSOCK_INVSOCK - the socket is not valid or not a server.
432 * GSOCK_TIMEDOUT - timeout, no incoming connections.
433 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
434 * GSOCK_MEMERR - couldn't allocate memory.
435 * GSOCK_IOERR - low-level error.
436 */
437 GSocket *GSocket::WaitConnection()
438 {
439 GSocket *connection;
440 struct sockaddr from;
441 WX_SOCKLEN_T fromlen = sizeof(from);
442 GSocketError err;
443 u_long arg = 1;
444
445 assert(this);
446
447 /* Reenable CONNECTION events */
448 m_detected &= ~GSOCK_CONNECTION_FLAG;
449
450 /* If the socket has already been created, we exit immediately */
451 if (m_fd == INVALID_SOCKET || !m_server)
452 {
453 m_error = GSOCK_INVSOCK;
454 return NULL;
455 }
456
457 /* Create a GSocket object for the new connection */
458 connection = GSocket_new();
459
460 if (!connection)
461 {
462 m_error = GSOCK_MEMERR;
463 return NULL;
464 }
465
466 /* Wait for a connection (with timeout) */
467 if (Input_Timeout() == GSOCK_TIMEDOUT)
468 {
469 delete connection;
470 /* m_error set by _GSocket_Input_Timeout */
471 return NULL;
472 }
473
474 connection->m_fd = accept(m_fd, &from, &fromlen);
475
476 if (connection->m_fd == INVALID_SOCKET)
477 {
478 if (WSAGetLastError() == WSAEWOULDBLOCK)
479 m_error = GSOCK_WOULDBLOCK;
480 else
481 m_error = GSOCK_IOERR;
482
483 delete connection;
484 return NULL;
485 }
486
487 /* Initialize all fields */
488 connection->m_server = false;
489 connection->m_stream = true;
490
491 /* Setup the peer address field */
492 connection->m_peer = GAddress_new();
493 if (!connection->m_peer)
494 {
495 delete connection;
496 m_error = GSOCK_MEMERR;
497 return NULL;
498 }
499 err = _GAddress_translate_from(connection->m_peer, &from, fromlen);
500 if (err != GSOCK_NOERROR)
501 {
502 GAddress_destroy(connection->m_peer);
503 delete connection;
504 m_error = err;
505 return NULL;
506 }
507
508 ioctlsocket(connection->m_fd, FIONBIO, (u_long FAR *) &arg);
509 gs_gui_functions->Enable_Events(connection);
510
511 return connection;
512 }
513
514 /* GSocket_SetReusable:
515 * Simply sets the m_resuable flag on the socket. GSocket_SetServer will
516 * make the appropriate setsockopt() call.
517 * Implemented as a GSocket function because clients (ie, wxSocketServer)
518 * don't have access to the GSocket struct information.
519 * Returns true if the flag was set correctly, false if an error occurred
520 * (ie, if the parameter was NULL)
521 */
522 bool GSocket::SetReusable()
523 {
524 /* socket must not be null, and must not be in use/already bound */
525 if (this && m_fd == INVALID_SOCKET) {
526 m_reusable = true;
527 return true;
528 }
529 return false;
530 }
531
532 /* Client specific parts */
533
534 /* GSocket_Connect:
535 * For stream (connection oriented) sockets, GSocket_Connect() tries
536 * to establish a client connection to a server using the peer address
537 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
538 * connection has been successfully established, or one of the error
539 * codes listed below. Note that for nonblocking sockets, a return
540 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
541 * request can be completed later; you should use GSocket_Select()
542 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
543 * corresponding asynchronous events.
544 *
545 * For datagram (non connection oriented) sockets, GSocket_Connect()
546 * just sets the peer address established with GSocket_SetPeer() as
547 * default destination.
548 *
549 * Error codes:
550 * GSOCK_INVSOCK - the socket is in use or not valid.
551 * GSOCK_INVADDR - the peer address has not been established.
552 * GSOCK_TIMEDOUT - timeout, the connection failed.
553 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
554 * GSOCK_MEMERR - couldn't allocate memory.
555 * GSOCK_IOERR - low-level error.
556 */
557 GSocketError GSocket::Connect(GSocketStream stream)
558 {
559 int ret, err;
560 u_long arg = 1;
561
562 assert(this);
563
564 /* Enable CONNECTION events (needed for nonblocking connections) */
565 m_detected &= ~GSOCK_CONNECTION_FLAG;
566
567 if (m_fd != INVALID_SOCKET)
568 {
569 m_error = GSOCK_INVSOCK;
570 return GSOCK_INVSOCK;
571 }
572
573 if (!m_peer)
574 {
575 m_error = GSOCK_INVADDR;
576 return GSOCK_INVADDR;
577 }
578
579 /* Streamed or dgram socket? */
580 m_stream = (stream == GSOCK_STREAMED);
581 m_server = false;
582 m_establishing = false;
583
584 /* Create the socket */
585 m_fd = socket(m_peer->m_realfamily,
586 m_stream? SOCK_STREAM : SOCK_DGRAM, 0);
587
588 if (m_fd == INVALID_SOCKET)
589 {
590 m_error = GSOCK_IOERR;
591 return GSOCK_IOERR;
592 }
593
594 ioctlsocket(m_fd, FIONBIO, (u_long FAR *) &arg);
595 gs_gui_functions->Enable_Events(this);
596
597 /* Connect it to the peer address, with a timeout (see below) */
598 ret = connect(m_fd, m_peer->m_addr, m_peer->m_len);
599
600 if (ret == SOCKET_ERROR)
601 {
602 err = WSAGetLastError();
603
604 /* If connect failed with EWOULDBLOCK and the GSocket object
605 * is in blocking mode, we select() for the specified timeout
606 * checking for writability to see if the connection request
607 * completes.
608 */
609 if ((err == WSAEWOULDBLOCK) && (!m_non_blocking))
610 {
611 err = Connect_Timeout();
612
613 if (err != GSOCK_NOERROR)
614 {
615 Close();
616 /* m_error is set in _GSocket_Connect_Timeout */
617 }
618
619 return (GSocketError) err;
620 }
621
622 /* If connect failed with EWOULDBLOCK and the GSocket object
623 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
624 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
625 * this way if the connection completes, a GSOCK_CONNECTION
626 * event will be generated, if enabled.
627 */
628 if ((err == WSAEWOULDBLOCK) && (m_non_blocking))
629 {
630 m_establishing = true;
631 m_error = GSOCK_WOULDBLOCK;
632 return GSOCK_WOULDBLOCK;
633 }
634
635 /* If connect failed with an error other than EWOULDBLOCK,
636 * then the call to GSocket_Connect() has failed.
637 */
638 Close();
639 m_error = GSOCK_IOERR;
640 return GSOCK_IOERR;
641 }
642
643 return GSOCK_NOERROR;
644 }
645
646 /* Datagram sockets */
647
648 /* GSocket_SetNonOriented:
649 * Sets up this socket as a non-connection oriented (datagram) socket.
650 * Before using this function, the local address must have been set
651 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
652 * on success, or one of the following otherwise.
653 *
654 * Error codes:
655 * GSOCK_INVSOCK - the socket is in use.
656 * GSOCK_INVADDR - the local address has not been set.
657 * GSOCK_IOERR - low-level error.
658 */
659 GSocketError GSocket::SetNonOriented()
660 {
661 u_long arg = 1;
662
663 assert(this);
664
665 if (m_fd != INVALID_SOCKET)
666 {
667 m_error = GSOCK_INVSOCK;
668 return GSOCK_INVSOCK;
669 }
670
671 if (!m_local)
672 {
673 m_error = GSOCK_INVADDR;
674 return GSOCK_INVADDR;
675 }
676
677 /* Initialize all fields */
678 m_stream = false;
679 m_server = false;
680
681 /* Create the socket */
682 m_fd = socket(m_local->m_realfamily, SOCK_DGRAM, 0);
683
684 if (m_fd == INVALID_SOCKET)
685 {
686 m_error = GSOCK_IOERR;
687 return GSOCK_IOERR;
688 }
689
690 ioctlsocket(m_fd, FIONBIO, (u_long FAR *) &arg);
691 gs_gui_functions->Enable_Events(this);
692
693 /* Bind to the local address,
694 * and retrieve the actual address bound.
695 */
696 if ((bind(m_fd, m_local->m_addr, m_local->m_len) != 0) ||
697 (getsockname(m_fd,
698 m_local->m_addr,
699 (WX_SOCKLEN_T *)&m_local->m_len) != 0))
700 {
701 Close();
702 m_error = GSOCK_IOERR;
703 return GSOCK_IOERR;
704 }
705
706 return GSOCK_NOERROR;
707 }
708
709 /* Generic IO */
710
711 /* Like recv(), send(), ... */
712 int GSocket::Read(char *buffer, int size)
713 {
714 int ret;
715
716 assert(this);
717
718 /* Reenable INPUT events */
719 m_detected &= ~GSOCK_INPUT_FLAG;
720
721 if (m_fd == INVALID_SOCKET || m_server)
722 {
723 m_error = GSOCK_INVSOCK;
724 return -1;
725 }
726
727 /* If the socket is blocking, wait for data (with a timeout) */
728 if (Input_Timeout() == GSOCK_TIMEDOUT)
729 {
730 m_error = GSOCK_TIMEDOUT;
731 return -1;
732 }
733
734 /* Read the data */
735 if (m_stream)
736 ret = Recv_Stream(buffer, size);
737 else
738 ret = Recv_Dgram(buffer, size);
739
740 if (ret == SOCKET_ERROR)
741 {
742 if (WSAGetLastError() != WSAEWOULDBLOCK)
743 m_error = GSOCK_IOERR;
744 else
745 m_error = GSOCK_WOULDBLOCK;
746 return -1;
747 }
748
749 return ret;
750 }
751
752 int GSocket::Write(const char *buffer, int size)
753 {
754 int ret;
755
756 assert(this);
757
758 if (m_fd == INVALID_SOCKET || m_server)
759 {
760 m_error = GSOCK_INVSOCK;
761 return -1;
762 }
763
764 /* If the socket is blocking, wait for writability (with a timeout) */
765 if (Output_Timeout() == GSOCK_TIMEDOUT)
766 return -1;
767
768 /* Write the data */
769 if (m_stream)
770 ret = Send_Stream(buffer, size);
771 else
772 ret = Send_Dgram(buffer, size);
773
774 if (ret == SOCKET_ERROR)
775 {
776 if (WSAGetLastError() != WSAEWOULDBLOCK)
777 m_error = GSOCK_IOERR;
778 else
779 m_error = GSOCK_WOULDBLOCK;
780
781 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
782 * does). Once the first OUTPUT event is received, users can assume
783 * that the socket is writable until a read operation fails. Only then
784 * will further OUTPUT events be posted.
785 */
786 m_detected &= ~GSOCK_OUTPUT_FLAG;
787 return -1;
788 }
789
790 return ret;
791 }
792
793 /* GSocket_Select:
794 * Polls the socket to determine its status. This function will
795 * check for the events specified in the 'flags' parameter, and
796 * it will return a mask indicating which operations can be
797 * performed. This function won't block, regardless of the
798 * mode (blocking | nonblocking) of the socket.
799 */
800 GSocketEventFlags GSocket::Select(GSocketEventFlags flags)
801 {
802 if (!gs_gui_functions->CanUseEventLoop())
803 {
804 GSocketEventFlags result = 0;
805 fd_set readfds;
806 fd_set writefds;
807 fd_set exceptfds;
808
809 assert(this);
810
811 FD_ZERO(&readfds);
812 FD_ZERO(&writefds);
813 FD_ZERO(&exceptfds);
814 FD_SET(m_fd, &readfds);
815 if (flags & GSOCK_OUTPUT_FLAG || flags & GSOCK_CONNECTION_FLAG)
816 FD_SET(m_fd, &writefds);
817 FD_SET(m_fd, &exceptfds);
818
819 /* Check 'sticky' CONNECTION flag first */
820 result |= (GSOCK_CONNECTION_FLAG & m_detected);
821
822 /* If we have already detected a LOST event, then don't try
823 * to do any further processing.
824 */
825 if ((m_detected & GSOCK_LOST_FLAG) != 0)
826 {
827 m_establishing = false;
828
829 return (GSOCK_LOST_FLAG & flags);
830 }
831
832 /* Try select now */
833 if (select(m_fd + 1, &readfds, &writefds, &exceptfds,
834 &m_timeout) <= 0)
835 {
836 /* What to do here? */
837 return (result & flags);
838 }
839
840 /* Check for readability */
841 if (FD_ISSET(m_fd, &readfds))
842 {
843 char c;
844
845 if (!m_stream || recv(m_fd, &c, 1, MSG_PEEK) > 0)
846 {
847 result |= GSOCK_INPUT_FLAG;
848 }
849 else
850 {
851 if (m_server && m_stream)
852 {
853 result |= GSOCK_CONNECTION_FLAG;
854 m_detected |= GSOCK_CONNECTION_FLAG;
855 }
856 else
857 {
858 m_detected = GSOCK_LOST_FLAG;
859 m_establishing = false;
860
861 /* LOST event: Abort any further processing */
862 return (GSOCK_LOST_FLAG & flags);
863 }
864 }
865 }
866
867 /* Check for writability */
868 if (FD_ISSET(m_fd, &writefds))
869 {
870 if (m_establishing && !m_server)
871 {
872 int error;
873 WX_SOCKLEN_T len = sizeof(error);
874
875 m_establishing = false;
876
877 getsockopt(m_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
878
879 if (error)
880 {
881 m_detected = GSOCK_LOST_FLAG;
882
883 /* LOST event: Abort any further processing */
884 return (GSOCK_LOST_FLAG & flags);
885 }
886 else
887 {
888 result |= GSOCK_CONNECTION_FLAG;
889 m_detected |= GSOCK_CONNECTION_FLAG;
890 }
891 }
892 else
893 {
894 result |= GSOCK_OUTPUT_FLAG;
895 }
896 }
897
898 /* Check for exceptions and errors (is this useful in Unices?) */
899 if (FD_ISSET(m_fd, &exceptfds))
900 {
901 m_establishing = false;
902 m_detected = GSOCK_LOST_FLAG;
903
904 /* LOST event: Abort any further processing */
905 return (GSOCK_LOST_FLAG & flags);
906 }
907
908 return (result & flags);
909 }
910 else /* USE_GUI() */
911 {
912 assert(this);
913 return flags & m_detected;
914 }
915 }
916
917 /* Attributes */
918
919 /* GSocket_SetNonBlocking:
920 * Sets the socket to non-blocking mode. All IO calls will return
921 * immediately.
922 */
923 void GSocket::SetNonBlocking(bool non_block)
924 {
925 assert(this);
926
927 m_non_blocking = non_block;
928 }
929
930 /* GSocket_SetTimeout:
931 * Sets the timeout for blocking calls. Time is expressed in
932 * milliseconds.
933 */
934 void GSocket::SetTimeout(unsigned long millis)
935 {
936 assert(this);
937
938 m_timeout.tv_sec = (millis / 1000);
939 m_timeout.tv_usec = (millis % 1000) * 1000;
940 }
941
942 /* GSocket_GetError:
943 * Returns the last error occurred for this socket. Note that successful
944 * operations do not clear this back to GSOCK_NOERROR, so use it only
945 * after an error.
946 */
947 GSocketError WXDLLIMPEXP_NET GSocket::GetError()
948 {
949 assert(this);
950
951 return m_error;
952 }
953
954 /* Callbacks */
955
956 /* GSOCK_INPUT:
957 * There is data to be read in the input buffer. If, after a read
958 * operation, there is still data available, the callback function will
959 * be called again.
960 * GSOCK_OUTPUT:
961 * The socket is available for writing. That is, the next write call
962 * won't block. This event is generated only once, when the connection is
963 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
964 * when the output buffer empties again. This means that the app should
965 * assume that it can write since the first OUTPUT event, and no more
966 * OUTPUT events will be generated unless an error occurs.
967 * GSOCK_CONNECTION:
968 * Connection successfully established, for client sockets, or incoming
969 * client connection, for server sockets. Wait for this event (also watch
970 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
971 * GSOCK_LOST:
972 * The connection is lost (or a connection request failed); this could
973 * be due to a failure, or due to the peer closing it gracefully.
974 */
975
976 /* GSocket_SetCallback:
977 * Enables the callbacks specified by 'flags'. Note that 'flags'
978 * may be a combination of flags OR'ed toghether, so the same
979 * callback function can be made to accept different events.
980 * The callback function must have the following prototype:
981 *
982 * void function(GSocket *socket, GSocketEvent event, char *cdata)
983 */
984 void GSocket::SetCallback(GSocketEventFlags flags,
985 GSocketCallback callback, char *cdata)
986 {
987 int count;
988
989 assert(this);
990
991 for (count = 0; count < GSOCK_MAX_EVENT; count++)
992 {
993 if ((flags & (1 << count)) != 0)
994 {
995 m_cbacks[count] = callback;
996 m_data[count] = cdata;
997 }
998 }
999 }
1000
1001 /* GSocket_UnsetCallback:
1002 * Disables all callbacks specified by 'flags', which may be a
1003 * combination of flags OR'ed toghether.
1004 */
1005 void GSocket::UnsetCallback(GSocketEventFlags flags)
1006 {
1007 int count;
1008
1009 assert(this);
1010
1011 for (count = 0; count < GSOCK_MAX_EVENT; count++)
1012 {
1013 if ((flags & (1 << count)) != 0)
1014 {
1015 m_cbacks[count] = NULL;
1016 m_data[count] = NULL;
1017 }
1018 }
1019 }
1020
1021 GSocketError GSocket::GetSockOpt(int level, int optname,
1022 void *optval, int *optlen)
1023 {
1024 if (getsockopt(m_fd, level, optname, (char*)optval, optlen) == 0)
1025 {
1026 return GSOCK_NOERROR;
1027 }
1028 return GSOCK_OPTERR;
1029 }
1030
1031 GSocketError GSocket::SetSockOpt(int level, int optname,
1032 const void *optval, int optlen)
1033 {
1034 if (setsockopt(m_fd, level, optname, (char*)optval, optlen) == 0)
1035 {
1036 return GSOCK_NOERROR;
1037 }
1038 return GSOCK_OPTERR;
1039 }
1040
1041 /* Internals (IO) */
1042
1043 /* _GSocket_Input_Timeout:
1044 * For blocking sockets, wait until data is available or
1045 * until timeout ellapses.
1046 */
1047 GSocketError GSocket::Input_Timeout()
1048 {
1049 fd_set readfds;
1050
1051 if (!m_non_blocking)
1052 {
1053 FD_ZERO(&readfds);
1054 FD_SET(m_fd, &readfds);
1055 if (select(0, &readfds, NULL, NULL, &m_timeout) == 0)
1056 {
1057 m_error = GSOCK_TIMEDOUT;
1058 return GSOCK_TIMEDOUT;
1059 }
1060 }
1061 return GSOCK_NOERROR;
1062 }
1063
1064 /* _GSocket_Output_Timeout:
1065 * For blocking sockets, wait until data can be sent without
1066 * blocking or until timeout ellapses.
1067 */
1068 GSocketError GSocket::Output_Timeout()
1069 {
1070 fd_set writefds;
1071
1072 if (!m_non_blocking)
1073 {
1074 FD_ZERO(&writefds);
1075 FD_SET(m_fd, &writefds);
1076 if (select(0, NULL, &writefds, NULL, &m_timeout) == 0)
1077 {
1078 m_error = GSOCK_TIMEDOUT;
1079 return GSOCK_TIMEDOUT;
1080 }
1081 }
1082 return GSOCK_NOERROR;
1083 }
1084
1085 /* _GSocket_Connect_Timeout:
1086 * For blocking sockets, wait until the connection is
1087 * established or fails, or until timeout ellapses.
1088 */
1089 GSocketError GSocket::Connect_Timeout()
1090 {
1091 fd_set writefds;
1092 fd_set exceptfds;
1093
1094 FD_ZERO(&writefds);
1095 FD_ZERO(&exceptfds);
1096 FD_SET(m_fd, &writefds);
1097 FD_SET(m_fd, &exceptfds);
1098 if (select(0, NULL, &writefds, &exceptfds, &m_timeout) == 0)
1099 {
1100 m_error = GSOCK_TIMEDOUT;
1101 return GSOCK_TIMEDOUT;
1102 }
1103 if (!FD_ISSET(m_fd, &writefds))
1104 {
1105 m_error = GSOCK_IOERR;
1106 return GSOCK_IOERR;
1107 }
1108
1109 return GSOCK_NOERROR;
1110 }
1111
1112 int GSocket::Recv_Stream(char *buffer, int size)
1113 {
1114 return recv(m_fd, buffer, size, 0);
1115 }
1116
1117 int GSocket::Recv_Dgram(char *buffer, int size)
1118 {
1119 struct sockaddr from;
1120 WX_SOCKLEN_T fromlen = sizeof(from);
1121 int ret;
1122 GSocketError err;
1123
1124 ret = recvfrom(m_fd, buffer, size, 0, &from, &fromlen);
1125
1126 if (ret == SOCKET_ERROR)
1127 return SOCKET_ERROR;
1128
1129 /* Translate a system address into a GSocket address */
1130 if (!m_peer)
1131 {
1132 m_peer = GAddress_new();
1133 if (!m_peer)
1134 {
1135 m_error = GSOCK_MEMERR;
1136 return -1;
1137 }
1138 }
1139 err = _GAddress_translate_from(m_peer, &from, fromlen);
1140 if (err != GSOCK_NOERROR)
1141 {
1142 GAddress_destroy(m_peer);
1143 m_peer = NULL;
1144 m_error = err;
1145 return -1;
1146 }
1147
1148 return ret;
1149 }
1150
1151 int GSocket::Send_Stream(const char *buffer, int size)
1152 {
1153 return send(m_fd, buffer, size, 0);
1154 }
1155
1156 int GSocket::Send_Dgram(const char *buffer, int size)
1157 {
1158 struct sockaddr *addr;
1159 int len, ret;
1160 GSocketError err;
1161
1162 if (!m_peer)
1163 {
1164 m_error = GSOCK_INVADDR;
1165 return -1;
1166 }
1167
1168 err = _GAddress_translate_to(m_peer, &addr, &len);
1169 if (err != GSOCK_NOERROR)
1170 {
1171 m_error = err;
1172 return -1;
1173 }
1174
1175 ret = sendto(m_fd, buffer, size, 0, addr, len);
1176
1177 /* Frees memory allocated by _GAddress_translate_to */
1178 free(addr);
1179
1180 return ret;
1181 }
1182
1183 /* Compatibility functions for GSocket */
1184 GSocket *GSocket_new(void)
1185 {
1186 GSocket *newsocket = new GSocket();
1187 if(newsocket->IsOk())
1188 return newsocket;
1189 delete newsocket;
1190 return NULL;
1191 }
1192
1193
1194 /*
1195 * -------------------------------------------------------------------------
1196 * GAddress
1197 * -------------------------------------------------------------------------
1198 */
1199
1200 /* CHECK_ADDRESS verifies that the current address family is either
1201 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1202 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1203 * an appropiate error code.
1204 *
1205 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1206 */
1207 #define CHECK_ADDRESS(address, family) \
1208 { \
1209 if (address->m_family == GSOCK_NOFAMILY) \
1210 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1211 return address->m_error; \
1212 if (address->m_family != GSOCK_##family) \
1213 { \
1214 address->m_error = GSOCK_INVADDR; \
1215 return GSOCK_INVADDR; \
1216 } \
1217 }
1218
1219 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1220 { \
1221 if (address->m_family == GSOCK_NOFAMILY) \
1222 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1223 return retval; \
1224 if (address->m_family != GSOCK_##family) \
1225 { \
1226 address->m_error = GSOCK_INVADDR; \
1227 return retval; \
1228 } \
1229 }
1230
1231
1232 GAddress *GAddress_new(void)
1233 {
1234 GAddress *address;
1235
1236 if ((address = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1237 return NULL;
1238
1239 address->m_family = GSOCK_NOFAMILY;
1240 address->m_addr = NULL;
1241 address->m_len = 0;
1242
1243 return address;
1244 }
1245
1246 GAddress *GAddress_copy(GAddress *address)
1247 {
1248 GAddress *addr2;
1249
1250 assert(address != NULL);
1251
1252 if ((addr2 = (GAddress *) malloc(sizeof(GAddress))) == NULL)
1253 return NULL;
1254
1255 memcpy(addr2, address, sizeof(GAddress));
1256
1257 if (address->m_addr)
1258 {
1259 addr2->m_addr = (struct sockaddr *) malloc(addr2->m_len);
1260 if (addr2->m_addr == NULL)
1261 {
1262 free(addr2);
1263 return NULL;
1264 }
1265 memcpy(addr2->m_addr, address->m_addr, addr2->m_len);
1266 }
1267
1268 return addr2;
1269 }
1270
1271 void GAddress_destroy(GAddress *address)
1272 {
1273 assert(address != NULL);
1274
1275 if (address->m_addr)
1276 free(address->m_addr);
1277
1278 free(address);
1279 }
1280
1281 void GAddress_SetFamily(GAddress *address, GAddressType type)
1282 {
1283 assert(address != NULL);
1284
1285 address->m_family = type;
1286 }
1287
1288 GAddressType GAddress_GetFamily(GAddress *address)
1289 {
1290 assert(address != NULL);
1291
1292 return address->m_family;
1293 }
1294
1295 GSocketError _GAddress_translate_from(GAddress *address,
1296 struct sockaddr *addr, int len)
1297 {
1298 address->m_realfamily = addr->sa_family;
1299 switch (addr->sa_family)
1300 {
1301 case AF_INET:
1302 address->m_family = GSOCK_INET;
1303 break;
1304 case AF_UNIX:
1305 address->m_family = GSOCK_UNIX;
1306 break;
1307 #ifdef AF_INET6
1308 case AF_INET6:
1309 address->m_family = GSOCK_INET6;
1310 break;
1311 #endif
1312 default:
1313 {
1314 address->m_error = GSOCK_INVOP;
1315 return GSOCK_INVOP;
1316 }
1317 }
1318
1319 if (address->m_addr)
1320 free(address->m_addr);
1321
1322 address->m_len = len;
1323 address->m_addr = (struct sockaddr *) malloc(len);
1324
1325 if (address->m_addr == NULL)
1326 {
1327 address->m_error = GSOCK_MEMERR;
1328 return GSOCK_MEMERR;
1329 }
1330 memcpy(address->m_addr, addr, len);
1331
1332 return GSOCK_NOERROR;
1333 }
1334
1335 GSocketError _GAddress_translate_to(GAddress *address,
1336 struct sockaddr **addr, int *len)
1337 {
1338 if (!address->m_addr)
1339 {
1340 address->m_error = GSOCK_INVADDR;
1341 return GSOCK_INVADDR;
1342 }
1343
1344 *len = address->m_len;
1345 *addr = (struct sockaddr *) malloc(address->m_len);
1346 if (*addr == NULL)
1347 {
1348 address->m_error = GSOCK_MEMERR;
1349 return GSOCK_MEMERR;
1350 }
1351
1352 memcpy(*addr, address->m_addr, address->m_len);
1353 return GSOCK_NOERROR;
1354 }
1355
1356 /*
1357 * -------------------------------------------------------------------------
1358 * Internet address family
1359 * -------------------------------------------------------------------------
1360 */
1361
1362 GSocketError _GAddress_Init_INET(GAddress *address)
1363 {
1364 address->m_len = sizeof(struct sockaddr_in);
1365 address->m_addr = (struct sockaddr *) malloc(address->m_len);
1366 if (address->m_addr == NULL)
1367 {
1368 address->m_error = GSOCK_MEMERR;
1369 return GSOCK_MEMERR;
1370 }
1371
1372 address->m_family = GSOCK_INET;
1373 address->m_realfamily = AF_INET;
1374 ((struct sockaddr_in *)address->m_addr)->sin_family = AF_INET;
1375 ((struct sockaddr_in *)address->m_addr)->sin_addr.s_addr = INADDR_ANY;
1376
1377 return GSOCK_NOERROR;
1378 }
1379
1380 GSocketError GAddress_INET_SetHostName(GAddress *address, const char *hostname)
1381 {
1382 struct hostent *he;
1383 struct in_addr *addr;
1384
1385 assert(address != NULL);
1386
1387 CHECK_ADDRESS(address, INET);
1388
1389 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1390
1391 addr->s_addr = inet_addr(hostname);
1392
1393 /* If it is a numeric host name, convert it now */
1394 if (addr->s_addr == INADDR_NONE)
1395 {
1396 struct in_addr *array_addr;
1397
1398 /* It is a real name, we solve it */
1399 if ((he = gethostbyname(hostname)) == NULL)
1400 {
1401 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1402 address->m_error = GSOCK_NOHOST;
1403 return GSOCK_NOHOST;
1404 }
1405 array_addr = (struct in_addr *) *(he->h_addr_list);
1406 addr->s_addr = array_addr[0].s_addr;
1407 }
1408 return GSOCK_NOERROR;
1409 }
1410
1411 GSocketError GAddress_INET_SetAnyAddress(GAddress *address)
1412 {
1413 return GAddress_INET_SetHostAddress(address, INADDR_ANY);
1414 }
1415
1416 GSocketError GAddress_INET_SetHostAddress(GAddress *address,
1417 unsigned long hostaddr)
1418 {
1419 struct in_addr *addr;
1420
1421 assert(address != NULL);
1422
1423 CHECK_ADDRESS(address, INET);
1424
1425 addr = &(((struct sockaddr_in *)address->m_addr)->sin_addr);
1426 addr->s_addr = htonl(hostaddr);
1427
1428 return GSOCK_NOERROR;
1429 }
1430
1431 GSocketError GAddress_INET_SetPortName(GAddress *address, const char *port,
1432 const char *protocol)
1433 {
1434 struct servent *se;
1435 struct sockaddr_in *addr;
1436
1437 assert(address != NULL);
1438 CHECK_ADDRESS(address, INET);
1439
1440 if (!port)
1441 {
1442 address->m_error = GSOCK_INVPORT;
1443 return GSOCK_INVPORT;
1444 }
1445
1446 se = getservbyname(port, protocol);
1447 if (!se)
1448 {
1449 if (isdigit(port[0]))
1450 {
1451 int port_int;
1452
1453 port_int = atoi(port);
1454 addr = (struct sockaddr_in *)address->m_addr;
1455 addr->sin_port = htons((u_short) port_int);
1456 return GSOCK_NOERROR;
1457 }
1458
1459 address->m_error = GSOCK_INVPORT;
1460 return GSOCK_INVPORT;
1461 }
1462
1463 addr = (struct sockaddr_in *)address->m_addr;
1464 addr->sin_port = se->s_port;
1465
1466 return GSOCK_NOERROR;
1467 }
1468
1469 GSocketError GAddress_INET_SetPort(GAddress *address, unsigned short port)
1470 {
1471 struct sockaddr_in *addr;
1472
1473 assert(address != NULL);
1474 CHECK_ADDRESS(address, INET);
1475
1476 addr = (struct sockaddr_in *)address->m_addr;
1477 addr->sin_port = htons(port);
1478
1479 return GSOCK_NOERROR;
1480 }
1481
1482 GSocketError GAddress_INET_GetHostName(GAddress *address, char *hostname, size_t sbuf)
1483 {
1484 struct hostent *he;
1485 char *addr_buf;
1486 struct sockaddr_in *addr;
1487
1488 assert(address != NULL);
1489 CHECK_ADDRESS(address, INET);
1490
1491 addr = (struct sockaddr_in *)address->m_addr;
1492 addr_buf = (char *)&(addr->sin_addr);
1493
1494 he = gethostbyaddr(addr_buf, sizeof(addr->sin_addr), AF_INET);
1495 if (he == NULL)
1496 {
1497 address->m_error = GSOCK_NOHOST;
1498 return GSOCK_NOHOST;
1499 }
1500
1501 strncpy(hostname, he->h_name, sbuf);
1502
1503 return GSOCK_NOERROR;
1504 }
1505
1506 unsigned long GAddress_INET_GetHostAddress(GAddress *address)
1507 {
1508 struct sockaddr_in *addr;
1509
1510 assert(address != NULL);
1511 CHECK_ADDRESS_RETVAL(address, INET, 0);
1512
1513 addr = (struct sockaddr_in *)address->m_addr;
1514
1515 return ntohl(addr->sin_addr.s_addr);
1516 }
1517
1518 unsigned short GAddress_INET_GetPort(GAddress *address)
1519 {
1520 struct sockaddr_in *addr;
1521
1522 assert(address != NULL);
1523 CHECK_ADDRESS_RETVAL(address, INET, 0);
1524
1525 addr = (struct sockaddr_in *)address->m_addr;
1526 return ntohs(addr->sin_port);
1527 }
1528
1529 /*
1530 * -------------------------------------------------------------------------
1531 * Unix address family
1532 * -------------------------------------------------------------------------
1533 */
1534
1535 GSocketError _GAddress_Init_UNIX(GAddress *address)
1536 {
1537 assert (address != NULL);
1538 address->m_error = GSOCK_INVADDR;
1539 return GSOCK_INVADDR;
1540 }
1541
1542 GSocketError GAddress_UNIX_SetPath(GAddress *address, const char *WXUNUSED(path))
1543 {
1544 assert (address != NULL);
1545 address->m_error = GSOCK_INVADDR;
1546 return GSOCK_INVADDR;
1547 }
1548
1549 GSocketError GAddress_UNIX_GetPath(GAddress *address, char *WXUNUSED(path), size_t WXUNUSED(sbuf))
1550 {
1551 assert (address != NULL);
1552 address->m_error = GSOCK_INVADDR;
1553 return GSOCK_INVADDR;
1554 }
1555
1556 #else /* !wxUSE_SOCKETS */
1557
1558 /*
1559 * Translation unit shouldn't be empty, so include this typedef to make the
1560 * compiler (VC++ 6.0, for example) happy
1561 */
1562 typedef void (*wxDummy)();
1563
1564 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */
1565