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