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