]>
git.saurik.com Git - wxWidgets.git/blob - src/unix/gsocket.c
1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Authors: Guilhem Lavaux,
5 * Guillermo Rodriguez Garcia <guille@iies.es> (maintainer)
6 * Purpose: GSocket main Unix file
7 * Licence: The wxWindows licence
9 * -------------------------------------------------------------------------
13 * PLEASE don't put C++ comments here - this is a C source file.
16 #ifndef __GSOCKET_STANDALONE__
20 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
23 #include <sys/types.h>
25 #include <sys/ioctl.h>
31 u_char sun_len
; /* sockaddr len including null */
32 u_char sun_family
; /* AF_UNIX */
33 char sun_path
[108]; /* path name (gag) */
36 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
51 # include <sys/filio.h>
61 # define SOCKLEN_T unsigned int
65 # define SOCKLEN_T socklen_t
68 # define SOCKLEN_T int
72 #endif /* SOCKLEN_T */
75 * MSW defines this, Unices don't.
77 #ifndef INVALID_SOCKET
78 #define INVALID_SOCKET -1
81 /* UnixWare reportedly needs this for FIONBIO definition */
83 #include <sys/filio.h>
87 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
88 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
91 #define INADDR_NONE INADDR_BROADCAST
94 #define MASK_SIGNAL() \
96 void (*old_handler)(int); \
98 old_handler = signal(SIGPIPE, SIG_IGN);
100 #define UNMASK_SIGNAL() \
101 signal(SIGPIPE, old_handler); \
105 #ifndef __GSOCKET_STANDALONE__
106 # include "wx/unix/gsockunx.h"
107 # include "wx/gsocket.h"
109 # include "gsockunx.h"
110 # include "gsocket.h"
111 #endif /* __GSOCKET_STANDALONE__ */
113 /* redefine some GUI-only functions to do nothing in console mode */
114 #if 1 //defined(wxUSE_GUI) && !wxUSE_GUI
115 // FIXME -- temporary measure
116 # define _GSocket_GUI_Init(socket) (1)
117 # define _GSocket_GUI_Destroy(socket)
118 # define _GSocket_Enable_Events(socket)
119 # define _GSocket_Disable_Events(socket)
120 # define _GSocket_Install_Callback(socket, event)
121 # define _GSocket_Uninstall_Callback(socket, event)
122 #endif /* wxUSE_GUI */
124 /* debugging helpers */
125 #ifdef __GSOCKET_DEBUG__
126 # define GSocket_Debug(args) printf args
128 # define GSocket_Debug(args)
129 #endif /* __GSOCKET_DEBUG__ */
131 /* Global initialisers */
133 int GSocket_Init(void)
138 void GSocket_Cleanup(void)
142 /* Constructors / Destructors for GSocket */
144 GSocket
*GSocket_new(void)
149 socket
= (GSocket
*)malloc(sizeof(GSocket
));
154 socket
->m_fd
= INVALID_SOCKET
;
155 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
157 socket
->m_cbacks
[i
] = NULL
;
159 socket
->m_detected
= 0;
160 socket
->m_local
= NULL
;
161 socket
->m_peer
= NULL
;
162 socket
->m_error
= GSOCK_NOERROR
;
163 socket
->m_server
= FALSE
;
164 socket
->m_stream
= TRUE
;
165 socket
->m_gui_dependent
= NULL
;
166 socket
->m_non_blocking
= FALSE
;
167 socket
->m_timeout
= 10*60*1000;
168 /* 10 minutes * 60 sec * 1000 millisec */
169 socket
->m_establishing
= FALSE
;
171 /* Per-socket GUI-specific initialization */
172 success
= _GSocket_GUI_Init(socket
);
182 void GSocket_close(GSocket
*socket
)
184 _GSocket_Disable_Events(socket
);
186 socket
->m_fd
= INVALID_SOCKET
;
189 void GSocket_destroy(GSocket
*socket
)
191 assert(socket
!= NULL
);
193 /* Check that the socket is really shutdowned */
194 if (socket
->m_fd
!= INVALID_SOCKET
)
195 GSocket_Shutdown(socket
);
197 /* Per-socket GUI-specific cleanup */
198 _GSocket_GUI_Destroy(socket
);
200 /* Destroy private addresses */
202 GAddress_destroy(socket
->m_local
);
205 GAddress_destroy(socket
->m_peer
);
207 /* Destroy the socket itself */
212 * Disallow further read/write operations on this socket, close
213 * the fd and disable all callbacks.
215 void GSocket_Shutdown(GSocket
*socket
)
219 assert(socket
!= NULL
);
221 /* If socket has been created, shutdown it */
222 if (socket
->m_fd
!= INVALID_SOCKET
)
224 shutdown(socket
->m_fd
, 2);
225 GSocket_close(socket
);
228 /* Disable GUI callbacks */
229 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
230 socket
->m_cbacks
[evt
] = NULL
;
232 socket
->m_detected
= GSOCK_LOST_FLAG
;
235 /* Address handling */
241 * Set or get the local or peer address for this socket. The 'set'
242 * functions return GSOCK_NOERROR on success, an error code otherwise.
243 * The 'get' functions return a pointer to a GAddress object on success,
244 * or NULL otherwise, in which case they set the error code of the
245 * corresponding GSocket.
248 * GSOCK_INVSOCK - the socket is not valid.
249 * GSOCK_INVADDR - the address is not valid.
251 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
253 assert(socket
!= NULL
);
255 /* the socket must be initialized, or it must be a server */
256 if ((socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
))
258 socket
->m_error
= GSOCK_INVSOCK
;
259 return GSOCK_INVSOCK
;
263 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
265 socket
->m_error
= GSOCK_INVADDR
;
266 return GSOCK_INVADDR
;
270 GAddress_destroy(socket
->m_local
);
272 socket
->m_local
= GAddress_copy(address
);
274 return GSOCK_NOERROR
;
277 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
279 assert(socket
!= NULL
);
282 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
284 socket
->m_error
= GSOCK_INVADDR
;
285 return GSOCK_INVADDR
;
289 GAddress_destroy(socket
->m_peer
);
291 socket
->m_peer
= GAddress_copy(address
);
293 return GSOCK_NOERROR
;
296 GAddress
*GSocket_GetLocal(GSocket
*socket
)
299 struct sockaddr addr
;
300 SOCKLEN_T size
= sizeof(addr
);
303 assert(socket
!= NULL
);
305 /* try to get it from the m_local var first */
307 return GAddress_copy(socket
->m_local
);
309 /* else, if the socket is initialized, try getsockname */
310 if (socket
->m_fd
== INVALID_SOCKET
)
312 socket
->m_error
= GSOCK_INVSOCK
;
316 if (getsockname(socket
->m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
318 socket
->m_error
= GSOCK_IOERR
;
322 /* got a valid address from getsockname, create a GAddress object */
323 address
= GAddress_new();
326 socket
->m_error
= GSOCK_MEMERR
;
330 err
= _GAddress_translate_from(address
, &addr
, size
);
331 if (err
!= GSOCK_NOERROR
)
333 GAddress_destroy(address
);
334 socket
->m_error
= err
;
341 GAddress
*GSocket_GetPeer(GSocket
*socket
)
343 assert(socket
!= NULL
);
345 /* try to get it from the m_peer var */
347 return GAddress_copy(socket
->m_peer
);
352 /* Server specific parts */
354 /* GSocket_SetServer:
355 * Sets up this socket as a server. The local address must have been
356 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
357 * Returns GSOCK_NOERROR on success, one of the following otherwise:
360 * GSOCK_INVSOCK - the socket is in use.
361 * GSOCK_INVADDR - the local address has not been set.
362 * GSOCK_IOERR - low-level error.
364 GSocketError
GSocket_SetServer(GSocket
*sck
)
370 /* must not be in use */
371 if (sck
->m_fd
!= INVALID_SOCKET
)
373 sck
->m_error
= GSOCK_INVSOCK
;
374 return GSOCK_INVSOCK
;
377 /* the local addr must have been set */
380 sck
->m_error
= GSOCK_INVADDR
;
381 return GSOCK_INVADDR
;
384 /* Initialize all fields */
385 sck
->m_stream
= TRUE
;
386 sck
->m_server
= TRUE
;
387 sck
->m_oriented
= TRUE
;
389 /* Create the socket */
390 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
392 if (sck
->m_fd
== INVALID_SOCKET
)
394 sck
->m_error
= GSOCK_IOERR
;
398 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
399 _GSocket_Enable_Events(sck
);
401 /* Bind to the local address,
402 * retrieve the actual address bound,
403 * and listen up to 5 connections.
405 if ((bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
406 (getsockname(sck
->m_fd
,
407 sck
->m_local
->m_addr
,
408 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
409 (listen(sck
->m_fd
, 5) != 0))
412 sck
->m_error
= GSOCK_IOERR
;
416 return GSOCK_NOERROR
;
419 /* GSocket_WaitConnection:
420 * Waits for an incoming client connection. Returns a pointer to
421 * a GSocket object, or NULL if there was an error, in which case
422 * the last error field will be updated for the calling GSocket.
424 * Error codes (set in the calling GSocket)
425 * GSOCK_INVSOCK - the socket is not valid or not a server.
426 * GSOCK_TIMEDOUT - timeout, no incoming connections.
427 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
428 * GSOCK_MEMERR - couldn't allocate memory.
429 * GSOCK_IOERR - low-level error.
431 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
433 struct sockaddr from
;
434 SOCKLEN_T fromlen
= sizeof(from
);
439 assert(socket
!= NULL
);
441 /* Reenable CONNECTION events */
442 _GSocket_Enable(socket
, GSOCK_CONNECTION
);
444 /* If the socket has already been created, we exit immediately */
445 if (socket
->m_fd
== INVALID_SOCKET
|| !socket
->m_server
)
447 socket
->m_error
= GSOCK_INVSOCK
;
451 /* Create a GSocket object for the new connection */
452 connection
= GSocket_new();
456 socket
->m_error
= GSOCK_MEMERR
;
460 /* Wait for a connection (with timeout) */
461 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
463 GSocket_destroy(connection
);
464 /* socket->m_error set by _GSocket_Input_Timeout */
468 connection
->m_fd
= accept(socket
->m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
470 if (connection
->m_fd
== INVALID_SOCKET
)
472 if (errno
== EWOULDBLOCK
)
473 socket
->m_error
= GSOCK_WOULDBLOCK
;
475 socket
->m_error
= GSOCK_IOERR
;
477 GSocket_destroy(connection
);
481 /* Initialize all fields */
482 connection
->m_server
= FALSE
;
483 connection
->m_stream
= TRUE
;
484 connection
->m_oriented
= TRUE
;
486 /* Setup the peer address field */
487 connection
->m_peer
= GAddress_new();
488 if (!connection
->m_peer
)
490 GSocket_destroy(connection
);
491 socket
->m_error
= GSOCK_MEMERR
;
494 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
495 if (err
!= GSOCK_NOERROR
)
497 GAddress_destroy(connection
->m_peer
);
498 GSocket_destroy(connection
);
499 socket
->m_error
= err
;
503 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
504 _GSocket_Enable_Events(connection
);
509 /* Client specific parts */
512 * For stream (connection oriented) sockets, GSocket_Connect() tries
513 * to establish a client connection to a server using the peer address
514 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
515 * connection has been succesfully established, or one of the error
516 * codes listed below. Note that for nonblocking sockets, a return
517 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
518 * request can be completed later; you should use GSocket_Select()
519 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
520 * corresponding asynchronous events.
522 * For datagram (non connection oriented) sockets, GSocket_Connect()
523 * just sets the peer address established with GSocket_SetPeer() as
524 * default destination.
527 * GSOCK_INVSOCK - the socket is in use or not valid.
528 * GSOCK_INVADDR - the peer address has not been established.
529 * GSOCK_TIMEDOUT - timeout, the connection failed.
530 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
531 * GSOCK_MEMERR - couldn't allocate memory.
532 * GSOCK_IOERR - low-level error.
534 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
541 /* Enable CONNECTION events (needed for nonblocking connections) */
542 _GSocket_Enable(sck
, GSOCK_CONNECTION
);
544 if (sck
->m_fd
!= INVALID_SOCKET
)
546 sck
->m_error
= GSOCK_INVSOCK
;
547 return GSOCK_INVSOCK
;
552 sck
->m_error
= GSOCK_INVADDR
;
553 return GSOCK_INVADDR
;
556 /* Streamed or dgram socket? */
557 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
558 sck
->m_oriented
= TRUE
;
559 sck
->m_server
= FALSE
;
560 sck
->m_establishing
= FALSE
;
562 /* Create the socket */
563 sck
->m_fd
= socket(sck
->m_peer
->m_realfamily
,
564 sck
->m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
566 if (sck
->m_fd
== INVALID_SOCKET
)
568 sck
->m_error
= GSOCK_IOERR
;
572 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
573 _GSocket_Enable_Events(sck
);
575 /* Connect it to the peer address, with a timeout (see below) */
576 ret
= connect(sck
->m_fd
, sck
->m_peer
->m_addr
, sck
->m_peer
->m_len
);
582 /* If connect failed with EINPROGRESS and the GSocket object
583 * is in blocking mode, we select() for the specified timeout
584 * checking for writability to see if the connection request
587 if ((err
== EINPROGRESS
) && (!sck
->m_non_blocking
))
589 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
592 /* sck->m_error is set in _GSocket_Output_Timeout */
593 return GSOCK_TIMEDOUT
;
598 SOCKLEN_T len
= sizeof(error
);
600 getsockopt(sck
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
603 return GSOCK_NOERROR
;
607 /* If connect failed with EINPROGRESS and the GSocket object
608 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
609 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
610 * this way if the connection completes, a GSOCK_CONNECTION
611 * event will be generated, if enabled.
613 if ((err
== EINPROGRESS
) && (sck
->m_non_blocking
))
615 sck
->m_establishing
= TRUE
;
616 sck
->m_error
= GSOCK_WOULDBLOCK
;
617 return GSOCK_WOULDBLOCK
;
620 /* If connect failed with an error other than EINPROGRESS,
621 * then the call to GSocket_Connect has failed.
624 sck
->m_error
= GSOCK_IOERR
;
628 return GSOCK_NOERROR
;
631 /* Datagram sockets */
633 /* GSocket_SetNonOriented:
634 * Sets up this socket as a non-connection oriented (datagram) socket.
635 * Before using this function, the local address must have been set
636 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
637 * on success, or one of the following otherwise.
640 * GSOCK_INVSOCK - the socket is in use.
641 * GSOCK_INVADDR - the local address has not been set.
642 * GSOCK_IOERR - low-level error.
644 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
650 if (sck
->m_fd
!= INVALID_SOCKET
)
652 sck
->m_error
= GSOCK_INVSOCK
;
653 return GSOCK_INVSOCK
;
658 sck
->m_error
= GSOCK_INVADDR
;
659 return GSOCK_INVADDR
;
662 /* Initialize all fields */
663 sck
->m_stream
= FALSE
;
664 sck
->m_server
= FALSE
;
665 sck
->m_oriented
= FALSE
;
667 /* Create the socket */
668 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
670 if (sck
->m_fd
== INVALID_SOCKET
)
672 sck
->m_error
= GSOCK_IOERR
;
676 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
677 _GSocket_Enable_Events(sck
);
679 /* Bind to the local address,
680 * and retrieve the actual address bound.
682 if ((bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
683 (getsockname(sck
->m_fd
,
684 sck
->m_local
->m_addr
,
685 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
688 sck
->m_error
= GSOCK_IOERR
;
692 return GSOCK_NOERROR
;
697 /* Like recv(), send(), ... */
698 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
702 assert(socket
!= NULL
);
704 /* Reenable INPUT events */
705 _GSocket_Enable(socket
, GSOCK_INPUT
);
707 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
709 socket
->m_error
= GSOCK_INVSOCK
;
713 /* If the socket is blocking, wait for data (with a timeout) */
714 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
718 if (socket
->m_stream
)
719 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
721 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
725 if (errno
== EWOULDBLOCK
)
726 socket
->m_error
= GSOCK_WOULDBLOCK
;
728 socket
->m_error
= GSOCK_IOERR
;
734 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
738 assert(socket
!= NULL
);
740 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
742 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
744 socket
->m_error
= GSOCK_INVSOCK
;
748 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
750 /* If the socket is blocking, wait for writability (with a timeout) */
751 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
754 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
757 if (socket
->m_stream
)
758 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
760 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
762 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
766 if (errno
== EWOULDBLOCK
)
768 socket
->m_error
= GSOCK_WOULDBLOCK
;
769 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
773 socket
->m_error
= GSOCK_IOERR
;
774 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
777 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
778 * in MSW). Once the first OUTPUT event is received, users can assume
779 * that the socket is writable until a read operation fails. Only then
780 * will further OUTPUT events be posted.
782 _GSocket_Enable(socket
, GSOCK_OUTPUT
);
786 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
792 * Polls the socket to determine its status. This function will
793 * check for the events specified in the 'flags' parameter, and
794 * it will return a mask indicating which operations can be
795 * performed. This function won't block, regardless of the
796 * mode (blocking | nonblocking) of the socket.
798 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
800 #if defined(wxUSE_GUI) && !wxUSE_GUI
802 GSocketEventFlags result
= 0;
808 /* Do not use a static struct, Linux can garble it */
812 assert(socket
!= NULL
);
817 FD_SET(socket
->m_fd
, &readfds
);
818 FD_SET(socket
->m_fd
, &writefds
);
819 FD_SET(socket
->m_fd
, &exceptfds
);
821 /* Check 'sticky' CONNECTION flag first */
822 result
|= (GSOCK_CONNECTION_FLAG
& socket
->m_detected
);
824 /* If we have already detected a LOST event, then don't try
825 * to do any further processing.
827 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
829 socket
->m_establishing
= FALSE
;
831 return (GSOCK_LOST_FLAG
& flags
);
835 if (select(socket
->m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
837 /* What to do here? */
838 return (result
& flags
);
841 /* Check for readability */
842 if (FD_ISSET(socket
->m_fd
, &readfds
))
846 if (recv(socket
->m_fd
, &c
, 1, MSG_PEEK
) > 0)
848 result
|= GSOCK_INPUT_FLAG
;
852 if (socket
->m_server
&& socket
->m_stream
)
854 result
|= GSOCK_CONNECTION_FLAG
;
855 socket
->m_detected
|= GSOCK_CONNECTION_FLAG
;
859 socket
->m_detected
= GSOCK_LOST_FLAG
;
860 socket
->m_establishing
= FALSE
;
862 /* LOST event: Abort any further processing */
863 return (GSOCK_LOST_FLAG
& flags
);
868 /* Check for writability */
869 if (FD_ISSET(socket
->m_fd
, &writefds
))
871 if (socket
->m_establishing
&& !socket
->m_server
)
874 SOCKLEN_T len
= sizeof(error
);
876 socket
->m_establishing
= FALSE
;
878 getsockopt(socket
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
882 socket
->m_detected
= GSOCK_LOST_FLAG
;
884 /* LOST event: Abort any further processing */
885 return (GSOCK_LOST_FLAG
& flags
);
889 result
|= GSOCK_CONNECTION_FLAG
;
890 socket
->m_detected
|= GSOCK_CONNECTION_FLAG
;
895 result
|= GSOCK_OUTPUT_FLAG
;
899 /* Check for exceptions and errors (is this useful in Unices?) */
900 if (FD_ISSET(socket
->m_fd
, &exceptfds
))
902 socket
->m_establishing
= FALSE
;
903 socket
->m_detected
= GSOCK_LOST_FLAG
;
905 /* LOST event: Abort any further processing */
906 return (GSOCK_LOST_FLAG
& flags
);
909 return (result
& flags
);
913 assert(socket
!= NULL
);
914 return flags
& socket
->m_detected
;
916 #endif /* !wxUSE_GUI */
921 /* GSocket_SetNonBlocking:
922 * Sets the socket to non-blocking mode. All IO calls will return
925 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
927 assert(socket
!= NULL
);
929 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
931 socket
->m_non_blocking
= non_block
;
934 /* GSocket_SetTimeout:
935 * Sets the timeout for blocking calls. Time is expressed in
938 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
940 assert(socket
!= NULL
);
942 socket
->m_timeout
= millisec
;
946 * Returns the last error occured for this socket. Note that successful
947 * operations do not clear this back to GSOCK_NOERROR, so use it only
950 GSocketError
GSocket_GetError(GSocket
*socket
)
952 assert(socket
!= NULL
);
954 return socket
->m_error
;
960 * There is data to be read in the input buffer. If, after a read
961 * operation, there is still data available, the callback function will
964 * The socket is available for writing. That is, the next write call
965 * won't block. This event is generated only once, when the connection is
966 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
967 * when the output buffer empties again. This means that the app should
968 * assume that it can write since the first OUTPUT event, and no more
969 * OUTPUT events will be generated unless an error occurs.
971 * Connection succesfully established, for client sockets, or incoming
972 * client connection, for server sockets. Wait for this event (also watch
973 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
975 * The connection is lost (or a connection request failed); this could
976 * be due to a failure, or due to the peer closing it gracefully.
979 /* GSocket_SetCallback:
980 * Enables the callbacks specified by 'flags'. Note that 'flags'
981 * may be a combination of flags OR'ed toghether, so the same
982 * callback function can be made to accept different events.
983 * The callback function must have the following prototype:
985 * void function(GSocket *socket, GSocketEvent event, char *cdata)
987 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
988 GSocketCallback callback
, char *cdata
)
992 assert(socket
!= NULL
);
994 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
996 if ((flags
& (1 << count
)) != 0)
998 socket
->m_cbacks
[count
] = callback
;
999 socket
->m_data
[count
] = cdata
;
1004 /* GSocket_UnsetCallback:
1005 * Disables all callbacks specified by 'flags', which may be a
1006 * combination of flags OR'ed toghether.
1008 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1012 assert(socket
!= NULL
);
1014 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1016 if ((flags
& (1 << count
)) != 0)
1018 socket
->m_cbacks
[count
] = NULL
;
1019 socket
->m_data
[count
] = NULL
;
1025 #define CALL_CALLBACK(socket, event) { \
1026 _GSocket_Disable(socket, event); \
1027 if (socket->m_cbacks[event]) \
1028 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1032 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
)
1034 socket
->m_detected
&= ~(1 << event
);
1035 _GSocket_Install_Callback(socket
, event
);
1038 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
)
1040 socket
->m_detected
|= (1 << event
);
1041 _GSocket_Uninstall_Callback(socket
, event
);
1044 /* _GSocket_Input_Timeout:
1045 * For blocking sockets, wait until data is available or
1046 * until timeout ellapses.
1048 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1054 /* Linux select() will overwrite the struct on return */
1055 tv
.tv_sec
= (socket
->m_timeout
/ 1000);
1056 tv
.tv_usec
= (socket
->m_timeout
% 1000) * 1000;
1058 if (!socket
->m_non_blocking
)
1061 FD_SET(socket
->m_fd
, &readfds
);
1062 ret
= select(socket
->m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1065 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1066 socket
->m_error
= GSOCK_TIMEDOUT
;
1067 return GSOCK_TIMEDOUT
;
1071 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1072 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1073 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1074 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1075 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1076 socket
->m_error
= GSOCK_TIMEDOUT
;
1077 return GSOCK_TIMEDOUT
;
1080 return GSOCK_NOERROR
;
1083 /* _GSocket_Output_Timeout:
1084 * For blocking sockets, wait until data can be sent without
1085 * blocking or until timeout ellapses.
1087 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1093 /* Linux select() will overwrite the struct on return */
1094 tv
.tv_sec
= (socket
->m_timeout
/ 1000);
1095 tv
.tv_usec
= (socket
->m_timeout
% 1000) * 1000;
1097 GSocket_Debug( ("m_non_blocking has: %d\n", (int)socket
->m_non_blocking
) );
1099 if (!socket
->m_non_blocking
)
1102 FD_SET(socket
->m_fd
, &writefds
);
1103 ret
= select(socket
->m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1106 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1107 socket
->m_error
= GSOCK_TIMEDOUT
;
1108 return GSOCK_TIMEDOUT
;
1112 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1113 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1114 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1115 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1116 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1117 socket
->m_error
= GSOCK_TIMEDOUT
;
1118 return GSOCK_TIMEDOUT
;
1120 if ( ! FD_ISSET(socket
->m_fd
, &writefds
) ) {
1121 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1124 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1129 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1132 return GSOCK_NOERROR
;
1135 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1137 return recv(socket
->m_fd
, buffer
, size
, 0);
1140 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1142 struct sockaddr from
;
1143 SOCKLEN_T fromlen
= sizeof(from
);
1147 fromlen
= sizeof(from
);
1149 ret
= recvfrom(socket
->m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1154 /* Translate a system address into a GSocket address */
1155 if (!socket
->m_peer
)
1157 socket
->m_peer
= GAddress_new();
1158 if (!socket
->m_peer
)
1160 socket
->m_error
= GSOCK_MEMERR
;
1164 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1165 if (err
!= GSOCK_NOERROR
)
1167 GAddress_destroy(socket
->m_peer
);
1168 socket
->m_peer
= NULL
;
1169 socket
->m_error
= err
;
1176 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1181 ret
= send(socket
->m_fd
, buffer
, size
, 0);
1187 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1189 struct sockaddr
*addr
;
1193 if (!socket
->m_peer
)
1195 socket
->m_error
= GSOCK_INVADDR
;
1199 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1200 if (err
!= GSOCK_NOERROR
)
1202 socket
->m_error
= err
;
1207 ret
= sendto(socket
->m_fd
, buffer
, size
, 0, addr
, len
);
1210 /* Frees memory allocated from _GAddress_translate_to */
1216 void _GSocket_Detected_Read(GSocket
*socket
)
1220 /* If we have already detected a LOST event, then don't try
1221 * to do any further processing.
1223 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
1225 socket
->m_establishing
= FALSE
;
1227 CALL_CALLBACK(socket
, GSOCK_LOST
);
1228 GSocket_Shutdown(socket
);
1232 if (recv(socket
->m_fd
, &c
, 1, MSG_PEEK
) > 0)
1234 CALL_CALLBACK(socket
, GSOCK_INPUT
);
1238 if (socket
->m_server
&& socket
->m_stream
)
1240 CALL_CALLBACK(socket
, GSOCK_CONNECTION
);
1244 CALL_CALLBACK(socket
, GSOCK_LOST
);
1245 GSocket_Shutdown(socket
);
1250 void _GSocket_Detected_Write(GSocket
*socket
)
1252 /* If we have already detected a LOST event, then don't try
1253 * to do any further processing.
1255 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
1257 socket
->m_establishing
= FALSE
;
1259 CALL_CALLBACK(socket
, GSOCK_LOST
);
1260 GSocket_Shutdown(socket
);
1264 if (socket
->m_establishing
&& !socket
->m_server
)
1267 SOCKLEN_T len
= sizeof(error
);
1269 socket
->m_establishing
= FALSE
;
1271 getsockopt(socket
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1275 CALL_CALLBACK(socket
, GSOCK_LOST
);
1276 GSocket_Shutdown(socket
);
1280 CALL_CALLBACK(socket
, GSOCK_CONNECTION
);
1281 /* We have to fire this event by hand because CONNECTION (for clients)
1282 * and OUTPUT are internally the same and we just disabled CONNECTION
1283 * events with the above macro.
1285 CALL_CALLBACK(socket
, GSOCK_OUTPUT
);
1290 CALL_CALLBACK(socket
, GSOCK_OUTPUT
);
1295 * -------------------------------------------------------------------------
1297 * -------------------------------------------------------------------------
1300 /* CHECK_ADDRESS verifies that the current address family is either
1301 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1302 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1303 * an appropiate error code.
1305 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1307 #define CHECK_ADDRESS(address, family) \
1309 if (address->m_family == GSOCK_NOFAMILY) \
1310 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1311 return address->m_error; \
1312 if (address->m_family != GSOCK_##family) \
1314 address->m_error = GSOCK_INVADDR; \
1315 return GSOCK_INVADDR; \
1319 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1321 if (address->m_family == GSOCK_NOFAMILY) \
1322 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1324 if (address->m_family != GSOCK_##family) \
1326 address->m_error = GSOCK_INVADDR; \
1332 GAddress
*GAddress_new(void)
1336 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1339 address
->m_family
= GSOCK_NOFAMILY
;
1340 address
->m_addr
= NULL
;
1346 GAddress
*GAddress_copy(GAddress
*address
)
1350 assert(address
!= NULL
);
1352 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1355 memcpy(addr2
, address
, sizeof(GAddress
));
1357 if (address
->m_addr
&& address
->m_len
> 0)
1359 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1360 if (addr2
->m_addr
== NULL
)
1365 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1371 void GAddress_destroy(GAddress
*address
)
1373 assert(address
!= NULL
);
1375 if (address
->m_addr
)
1376 free(address
->m_addr
);
1381 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1383 assert(address
!= NULL
);
1385 address
->m_family
= type
;
1388 GAddressType
GAddress_GetFamily(GAddress
*address
)
1390 assert(address
!= NULL
);
1392 return address
->m_family
;
1395 GSocketError
_GAddress_translate_from(GAddress
*address
,
1396 struct sockaddr
*addr
, int len
)
1398 address
->m_realfamily
= addr
->sa_family
;
1399 switch (addr
->sa_family
)
1402 address
->m_family
= GSOCK_INET
;
1405 address
->m_family
= GSOCK_UNIX
;
1409 address
->m_family
= GSOCK_INET6
;
1414 address
->m_error
= GSOCK_INVOP
;
1419 if (address
->m_addr
)
1420 free(address
->m_addr
);
1422 address
->m_len
= len
;
1423 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1425 if (address
->m_addr
== NULL
)
1427 address
->m_error
= GSOCK_MEMERR
;
1428 return GSOCK_MEMERR
;
1430 memcpy(address
->m_addr
, addr
, len
);
1432 return GSOCK_NOERROR
;
1435 GSocketError
_GAddress_translate_to(GAddress
*address
,
1436 struct sockaddr
**addr
, int *len
)
1438 if (!address
->m_addr
)
1440 address
->m_error
= GSOCK_INVADDR
;
1441 return GSOCK_INVADDR
;
1444 *len
= address
->m_len
;
1445 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1448 address
->m_error
= GSOCK_MEMERR
;
1449 return GSOCK_MEMERR
;
1452 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1453 return GSOCK_NOERROR
;
1457 * -------------------------------------------------------------------------
1458 * Internet address family
1459 * -------------------------------------------------------------------------
1462 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1464 address
->m_len
= sizeof(struct sockaddr_in
);
1465 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1466 if (address
->m_addr
== NULL
)
1468 address
->m_error
= GSOCK_MEMERR
;
1469 return GSOCK_MEMERR
;
1472 address
->m_family
= GSOCK_INET
;
1473 address
->m_realfamily
= PF_INET
;
1474 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1475 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1477 return GSOCK_NOERROR
;
1480 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1483 struct in_addr
*addr
;
1485 assert(address
!= NULL
);
1487 CHECK_ADDRESS(address
, INET
);
1489 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1491 /* If it is a numeric host name, convert it now */
1492 #if defined(HAVE_INET_ATON)
1493 if (inet_aton(hostname
, addr
) == 0)
1495 #elif defined(HAVE_INET_ADDR)
1496 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1499 /* Use gethostbyname by default */
1503 struct in_addr
*array_addr
;
1505 /* It is a real name, we solve it */
1506 if ((he
= gethostbyname(hostname
)) == NULL
)
1508 /* Reset to invalid address */
1509 addr
->s_addr
= INADDR_NONE
;
1510 address
->m_error
= GSOCK_NOHOST
;
1511 return GSOCK_NOHOST
;
1513 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1514 addr
->s_addr
= array_addr
[0].s_addr
;
1516 return GSOCK_NOERROR
;
1519 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1521 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1524 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1525 unsigned long hostaddr
)
1527 struct in_addr
*addr
;
1529 assert(address
!= NULL
);
1531 CHECK_ADDRESS(address
, INET
);
1533 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1534 addr
->s_addr
= hostaddr
;
1536 return GSOCK_NOERROR
;
1539 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1540 const char *protocol
)
1543 struct sockaddr_in
*addr
;
1545 assert(address
!= NULL
);
1546 CHECK_ADDRESS(address
, INET
);
1550 address
->m_error
= GSOCK_INVPORT
;
1551 return GSOCK_INVPORT
;
1554 se
= getservbyname(port
, protocol
);
1557 /* the cast to int suppresses compiler warnings about subscript having the
1559 if (isdigit((int)port
[0]))
1563 port_int
= atoi(port
);
1564 addr
= (struct sockaddr_in
*)address
->m_addr
;
1565 addr
->sin_port
= htons(port_int
);
1566 return GSOCK_NOERROR
;
1569 address
->m_error
= GSOCK_INVPORT
;
1570 return GSOCK_INVPORT
;
1573 addr
= (struct sockaddr_in
*)address
->m_addr
;
1574 addr
->sin_port
= se
->s_port
;
1576 return GSOCK_NOERROR
;
1579 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1581 struct sockaddr_in
*addr
;
1583 assert(address
!= NULL
);
1584 CHECK_ADDRESS(address
, INET
);
1586 addr
= (struct sockaddr_in
*)address
->m_addr
;
1587 addr
->sin_port
= htons(port
);
1589 return GSOCK_NOERROR
;
1592 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1596 struct sockaddr_in
*addr
;
1598 assert(address
!= NULL
);
1599 CHECK_ADDRESS(address
, INET
);
1601 addr
= (struct sockaddr_in
*)address
->m_addr
;
1602 addr_buf
= (char *)&(addr
->sin_addr
);
1604 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1607 address
->m_error
= GSOCK_NOHOST
;
1608 return GSOCK_NOHOST
;
1611 strncpy(hostname
, he
->h_name
, sbuf
);
1613 return GSOCK_NOERROR
;
1616 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1618 struct sockaddr_in
*addr
;
1620 assert(address
!= NULL
);
1621 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1623 addr
= (struct sockaddr_in
*)address
->m_addr
;
1625 return addr
->sin_addr
.s_addr
;
1628 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1630 struct sockaddr_in
*addr
;
1632 assert(address
!= NULL
);
1633 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1635 addr
= (struct sockaddr_in
*)address
->m_addr
;
1636 return ntohs(addr
->sin_port
);
1640 * -------------------------------------------------------------------------
1641 * Unix address family
1642 * -------------------------------------------------------------------------
1645 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1647 address
->m_len
= sizeof(struct sockaddr_un
);
1648 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1649 if (address
->m_addr
== NULL
)
1651 address
->m_error
= GSOCK_MEMERR
;
1652 return GSOCK_MEMERR
;
1655 address
->m_family
= GSOCK_UNIX
;
1656 address
->m_realfamily
= PF_UNIX
;
1657 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1658 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1660 return GSOCK_NOERROR
;
1663 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1665 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1667 struct sockaddr_un
*addr
;
1669 assert(address
!= NULL
);
1671 CHECK_ADDRESS(address
, UNIX
);
1673 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1674 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1675 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1677 return GSOCK_NOERROR
;
1680 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1682 struct sockaddr_un
*addr
;
1684 assert(address
!= NULL
);
1685 CHECK_ADDRESS(address
, UNIX
);
1687 addr
= (struct sockaddr_un
*)address
->m_addr
;
1689 strncpy(path
, addr
->sun_path
, sbuf
);
1691 return GSOCK_NOERROR
;
1694 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */