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