1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Authors: David Elliott (C++ conversion, maintainer)
6 * Guillermo Rodriguez Garcia <guille@iies.es>
7 * Purpose: GSocket main Unix and OS/2 file
8 * Licence: The wxWindows licence
10 * -------------------------------------------------------------------------
14 * PLEASE don't put C++ comments here - this is a C source file.
17 #ifndef __GSOCKET_STANDALONE__
21 #if defined(__VISAGECPP__)
22 /* Seems to be needed by Visual Age C++, though I don't see how it manages
23 to not break on including a C++ header into a plain C source file */
25 #define BSD_SELECT /* use Berkley Sockets select */
28 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
31 #include <sys/types.h>
36 #include <netinet/in.h>
39 #include <sys/ioctl.h>
45 u_char sun_len
; /* sockaddr len including null */
46 u_char sun_family
; /* AF_UNIX */
47 char sun_path
[108]; /* path name (gag) */
50 #include <sys/socket.h>
56 #include <netinet/in.h>
57 #include <arpa/inet.h>
64 #include <machine/endian.h>
70 #define EBADF SOCEBADF
76 #include <sys/socket.h>
77 #include <sys/ioctl.h>
78 #include <sys/select.h>
80 #define close(a) soclose(a)
81 #define select(a,b,c,d,e) bsdselect(a,b,c,d,e)
82 int _System
bsdselect(int,
87 int _System
soclose(int);
91 #include <sys/select.h>
99 # include <sys/filio.h>
102 # include <bstring.h>
105 # include <strings.h>
112 # define SOCKLEN_T unsigned int
116 # define SOCKLEN_T socklen_t
119 # define SOCKLEN_T int
123 #endif /* SOCKLEN_T */
126 #define SOCKOPTLEN_T SOCKLEN_T
130 * OSX 10.2 has int args instead of SOCKLENXXX_T
132 #if defined( __WXMAC__ ) || defined ( __WXCOCOA__ )
133 # if ( MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_2 )
136 # define SOCKOPTLEN_T int
137 # define SOCKLEN_T int
142 * MSW defines this, Unices don't.
144 #ifndef INVALID_SOCKET
145 #define INVALID_SOCKET -1
148 /* UnixWare reportedly needs this for FIONBIO definition */
150 #include <sys/filio.h>
154 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
155 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
158 #define INADDR_NONE INADDR_BROADCAST
161 #define MASK_SIGNAL() \
163 void (*old_handler)(int); \
165 old_handler = signal(SIGPIPE, SIG_IGN);
167 #define UNMASK_SIGNAL() \
168 signal(SIGPIPE, old_handler); \
172 # define GSOCKET_MSG_NOSIGNAL MSG_NOSIGNAL
173 #else /* MSG_NOSIGNAL not available (FreeBSD including OS X) */
174 # define GSOCKET_MSG_NOSIGNAL 0
175 #endif /* MSG_NOSIGNAL */
177 #ifndef __GSOCKET_STANDALONE__
178 # include "wx/unix/gsockunx.h"
179 # include "wx/gsocket.h"
181 # include "gsockunx.h"
182 # include "gsocket.h"
183 #endif /* __GSOCKET_STANDALONE__ */
185 /* debugging helpers */
186 #ifdef __GSOCKET_DEBUG__
187 # define GSocket_Debug(args) printf args
189 # define GSocket_Debug(args)
190 #endif /* __GSOCKET_DEBUG__ */
192 /* Table of GUI-related functions. We must call them indirectly because
193 * of wxBase and GUI separation: */
195 static GSocketGUIFunctionsTable
*gs_gui_functions
;
197 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
200 virtual bool OnInit();
201 virtual void OnExit();
202 virtual bool CanUseEventLoop();
203 virtual bool Init_Socket(GSocket
*socket
);
204 virtual void Destroy_Socket(GSocket
*socket
);
205 virtual void Install_Callback(GSocket
*socket
, GSocketEvent event
);
206 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
207 virtual void Enable_Events(GSocket
*socket
);
208 virtual void Disable_Events(GSocket
*socket
);
211 bool GSocketGUIFunctionsTableNull::OnInit()
213 void GSocketGUIFunctionsTableNull::OnExit()
215 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
217 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*socket
)
219 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*socket
)
221 void GSocketGUIFunctionsTableNull::Install_Callback(GSocket
*socket
, GSocketEvent event
)
223 void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
225 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*socket
)
227 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*socket
)
229 /* Global initialisers */
231 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
233 gs_gui_functions
= guifunc
;
236 int GSocket_Init(void)
238 if (!gs_gui_functions
)
240 static GSocketGUIFunctionsTableNull table
;
241 gs_gui_functions
= &table
;
243 if ( !gs_gui_functions
->OnInit() )
248 void GSocket_Cleanup(void)
250 if (gs_gui_functions
)
252 gs_gui_functions
->OnExit();
256 /* Constructors / Destructors for GSocket */
262 m_fd
= INVALID_SOCKET
;
263 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
270 m_error
= GSOCK_NOERROR
;
273 m_gui_dependent
= NULL
;
274 m_non_blocking
= false;
276 m_timeout
= 10*60*1000;
277 /* 10 minutes * 60 sec * 1000 millisec */
278 m_establishing
= false;
280 assert(gs_gui_functions
);
281 /* Per-socket GUI-specific initialization */
282 m_ok
= gs_gui_functions
->Init_Socket(this);
285 void GSocket::Close()
287 gs_gui_functions
->Disable_Events(this);
288 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
289 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
292 m_fd
= INVALID_SOCKET
;
299 /* Check that the socket is really shutdowned */
300 if (m_fd
!= INVALID_SOCKET
)
303 /* Per-socket GUI-specific cleanup */
304 gs_gui_functions
->Destroy_Socket(this);
306 /* Destroy private addresses */
308 GAddress_destroy(m_local
);
311 GAddress_destroy(m_peer
);
315 * Disallow further read/write operations on this socket, close
316 * the fd and disable all callbacks.
318 void GSocket::Shutdown()
324 /* If socket has been created, shutdown it */
325 if (m_fd
!= INVALID_SOCKET
)
331 /* Disable GUI callbacks */
332 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
333 m_cbacks
[evt
] = NULL
;
335 m_detected
= GSOCK_LOST_FLAG
;
338 /* Address handling */
344 * Set or get the local or peer address for this socket. The 'set'
345 * functions return GSOCK_NOERROR on success, an error code otherwise.
346 * The 'get' functions return a pointer to a GAddress object on success,
347 * or NULL otherwise, in which case they set the error code of the
348 * corresponding GSocket.
351 * GSOCK_INVSOCK - the socket is not valid.
352 * GSOCK_INVADDR - the address is not valid.
354 GSocketError
GSocket::SetLocal(GAddress
*address
)
358 /* the socket must be initialized, or it must be a server */
359 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
361 m_error
= GSOCK_INVSOCK
;
362 return GSOCK_INVSOCK
;
366 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
368 m_error
= GSOCK_INVADDR
;
369 return GSOCK_INVADDR
;
373 GAddress_destroy(m_local
);
375 m_local
= GAddress_copy(address
);
377 return GSOCK_NOERROR
;
380 GSocketError
GSocket::SetPeer(GAddress
*address
)
385 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
387 m_error
= GSOCK_INVADDR
;
388 return GSOCK_INVADDR
;
392 GAddress_destroy(m_peer
);
394 m_peer
= GAddress_copy(address
);
396 return GSOCK_NOERROR
;
399 GAddress
*GSocket::GetLocal()
402 struct sockaddr addr
;
403 SOCKLEN_T size
= sizeof(addr
);
408 /* try to get it from the m_local var first */
410 return GAddress_copy(m_local
);
412 /* else, if the socket is initialized, try getsockname */
413 if (m_fd
== INVALID_SOCKET
)
415 m_error
= GSOCK_INVSOCK
;
419 if (getsockname(m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
421 m_error
= GSOCK_IOERR
;
425 /* got a valid address from getsockname, create a GAddress object */
426 address
= GAddress_new();
429 m_error
= GSOCK_MEMERR
;
433 err
= _GAddress_translate_from(address
, &addr
, size
);
434 if (err
!= GSOCK_NOERROR
)
436 GAddress_destroy(address
);
444 GAddress
*GSocket::GetPeer()
448 /* try to get it from the m_peer var */
450 return GAddress_copy(m_peer
);
455 /* Server specific parts */
457 /* GSocket_SetServer:
458 * Sets up this socket as a server. The local address must have been
459 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
460 * Returns GSOCK_NOERROR on success, one of the following otherwise:
463 * GSOCK_INVSOCK - the socket is in use.
464 * GSOCK_INVADDR - the local address has not been set.
465 * GSOCK_IOERR - low-level error.
467 GSocketError
GSocket::SetServer()
473 /* must not be in use */
474 if (m_fd
!= INVALID_SOCKET
)
476 m_error
= GSOCK_INVSOCK
;
477 return GSOCK_INVSOCK
;
480 /* the local addr must have been set */
483 m_error
= GSOCK_INVADDR
;
484 return GSOCK_INVADDR
;
487 /* Initialize all fields */
491 /* Create the socket */
492 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
494 if (m_fd
== INVALID_SOCKET
)
496 m_error
= GSOCK_IOERR
;
500 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
502 setsockopt(m_fd
, SOL_SOCKET
, SO_NOSIGPIPE
, (const char*)&arg
, sizeof(u_long
));
505 ioctl(m_fd
, FIONBIO
, &arg
);
506 gs_gui_functions
->Enable_Events(this);
508 /* allow a socket to re-bind if the socket is in the TIME_WAIT
509 state after being previously closed.
512 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
514 /* Bind to the local address,
515 * retrieve the actual address bound,
516 * and listen up to 5 connections.
518 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
521 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
522 (listen(m_fd
, 5) != 0))
525 m_error
= GSOCK_IOERR
;
529 return GSOCK_NOERROR
;
532 /* GSocket_WaitConnection:
533 * Waits for an incoming client connection. Returns a pointer to
534 * a GSocket object, or NULL if there was an error, in which case
535 * the last error field will be updated for the calling GSocket.
537 * Error codes (set in the calling GSocket)
538 * GSOCK_INVSOCK - the socket is not valid or not a server.
539 * GSOCK_TIMEDOUT - timeout, no incoming connections.
540 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
541 * GSOCK_MEMERR - couldn't allocate memory.
542 * GSOCK_IOERR - low-level error.
544 GSocket
*GSocket::WaitConnection()
546 struct sockaddr from
;
547 SOCKLEN_T fromlen
= sizeof(from
);
555 /* Reenable CONNECTION events */
556 Enable(GSOCK_CONNECTION
);
559 /* If the socket has already been created, we exit immediately */
560 if (m_fd
== INVALID_SOCKET
|| !m_server
)
562 m_error
= GSOCK_INVSOCK
;
566 /* Create a GSocket object for the new connection */
567 connection
= GSocket_new();
571 m_error
= GSOCK_MEMERR
;
575 /* Wait for a connection (with timeout) */
576 if (Input_Timeout() == GSOCK_TIMEDOUT
)
579 /* m_error set by _GSocket_Input_Timeout */
583 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
586 /* Reenable CONNECTION events */
587 Enable(GSOCK_CONNECTION
);
590 if (connection
->m_fd
== INVALID_SOCKET
)
592 if (errno
== EWOULDBLOCK
)
593 m_error
= GSOCK_WOULDBLOCK
;
595 m_error
= GSOCK_IOERR
;
601 /* Initialize all fields */
602 connection
->m_server
= false;
603 connection
->m_stream
= true;
605 /* Setup the peer address field */
606 connection
->m_peer
= GAddress_new();
607 if (!connection
->m_peer
)
610 m_error
= GSOCK_MEMERR
;
613 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
614 if (err
!= GSOCK_NOERROR
)
620 #if defined(__EMX__) || defined(__VISAGECPP__)
621 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
623 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
625 gs_gui_functions
->Enable_Events(connection
);
630 bool GSocket::SetReusable()
632 /* socket must not be null, and must not be in use/already bound */
633 if (this && m_fd
== INVALID_SOCKET
) {
640 /* Client specific parts */
643 * For stream (connection oriented) sockets, GSocket_Connect() tries
644 * to establish a client connection to a server using the peer address
645 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
646 * connection has been succesfully established, or one of the error
647 * codes listed below. Note that for nonblocking sockets, a return
648 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
649 * request can be completed later; you should use GSocket_Select()
650 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
651 * corresponding asynchronous events.
653 * For datagram (non connection oriented) sockets, GSocket_Connect()
654 * just sets the peer address established with GSocket_SetPeer() as
655 * default destination.
658 * GSOCK_INVSOCK - the socket is in use or not valid.
659 * GSOCK_INVADDR - the peer address has not been established.
660 * GSOCK_TIMEDOUT - timeout, the connection failed.
661 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
662 * GSOCK_MEMERR - couldn't allocate memory.
663 * GSOCK_IOERR - low-level error.
665 GSocketError
GSocket::Connect(GSocketStream stream
)
672 /* Enable CONNECTION events (needed for nonblocking connections) */
673 Enable(GSOCK_CONNECTION
);
675 if (m_fd
!= INVALID_SOCKET
)
677 m_error
= GSOCK_INVSOCK
;
678 return GSOCK_INVSOCK
;
683 m_error
= GSOCK_INVADDR
;
684 return GSOCK_INVADDR
;
687 /* Streamed or dgram socket? */
688 m_stream
= (stream
== GSOCK_STREAMED
);
690 m_establishing
= false;
692 /* Create the socket */
693 m_fd
= socket(m_peer
->m_realfamily
,
694 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
696 if (m_fd
== INVALID_SOCKET
)
698 m_error
= GSOCK_IOERR
;
702 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
704 setsockopt(m_fd
, SOL_SOCKET
, SO_NOSIGPIPE
, (const char*)&arg
, sizeof(u_long
));
707 #if defined(__EMX__) || defined(__VISAGECPP__)
708 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
710 ioctl(m_fd
, FIONBIO
, &arg
);
713 /* Connect it to the peer address, with a timeout (see below) */
714 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
718 gs_gui_functions
->Enable_Events(this);
725 /* If connect failed with EINPROGRESS and the GSocket object
726 * is in blocking mode, we select() for the specified timeout
727 * checking for writability to see if the connection request
730 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
732 if (Output_Timeout() == GSOCK_TIMEDOUT
)
735 /* m_error is set in _GSocket_Output_Timeout */
736 return GSOCK_TIMEDOUT
;
741 SOCKOPTLEN_T len
= sizeof(error
);
743 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*) &error
, &len
);
745 gs_gui_functions
->Enable_Events(this);
748 return GSOCK_NOERROR
;
752 /* If connect failed with EINPROGRESS and the GSocket object
753 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
754 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
755 * this way if the connection completes, a GSOCK_CONNECTION
756 * event will be generated, if enabled.
758 if ((err
== EINPROGRESS
) && (m_non_blocking
))
760 m_establishing
= true;
761 m_error
= GSOCK_WOULDBLOCK
;
762 return GSOCK_WOULDBLOCK
;
765 /* If connect failed with an error other than EINPROGRESS,
766 * then the call to GSocket_Connect has failed.
769 m_error
= GSOCK_IOERR
;
773 return GSOCK_NOERROR
;
776 /* Datagram sockets */
778 /* GSocket_SetNonOriented:
779 * Sets up this socket as a non-connection oriented (datagram) socket.
780 * Before using this function, the local address must have been set
781 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
782 * on success, or one of the following otherwise.
785 * GSOCK_INVSOCK - the socket is in use.
786 * GSOCK_INVADDR - the local address has not been set.
787 * GSOCK_IOERR - low-level error.
789 GSocketError
GSocket::SetNonOriented()
795 if (m_fd
!= INVALID_SOCKET
)
797 m_error
= GSOCK_INVSOCK
;
798 return GSOCK_INVSOCK
;
803 m_error
= GSOCK_INVADDR
;
804 return GSOCK_INVADDR
;
807 /* Initialize all fields */
811 /* Create the socket */
812 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
814 if (m_fd
== INVALID_SOCKET
)
816 m_error
= GSOCK_IOERR
;
819 #if defined(__EMX__) || defined(__VISAGECPP__)
820 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
822 ioctl(m_fd
, FIONBIO
, &arg
);
824 gs_gui_functions
->Enable_Events(this);
826 /* Bind to the local address,
827 * and retrieve the actual address bound.
829 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
832 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
835 m_error
= GSOCK_IOERR
;
839 return GSOCK_NOERROR
;
844 /* Like recv(), send(), ... */
845 int GSocket::Read(char *buffer
, int size
)
851 if (m_fd
== INVALID_SOCKET
|| m_server
)
853 m_error
= GSOCK_INVSOCK
;
857 /* Disable events during query of socket status */
858 Disable(GSOCK_INPUT
);
860 /* If the socket is blocking, wait for data (with a timeout) */
861 if (Input_Timeout() == GSOCK_TIMEDOUT
)
862 /* We no longer return here immediately, otherwise socket events would not be re-enabled! */
867 ret
= Recv_Stream(buffer
, size
);
869 ret
= Recv_Dgram(buffer
, size
);
874 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
))
875 m_error
= GSOCK_WOULDBLOCK
;
877 m_error
= GSOCK_IOERR
;
880 /* Enable events again now that we are done processing */
886 int GSocket::Write(const char *buffer
, int size
)
892 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
894 if (m_fd
== INVALID_SOCKET
|| m_server
)
896 m_error
= GSOCK_INVSOCK
;
900 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
902 /* If the socket is blocking, wait for writability (with a timeout) */
903 if (Output_Timeout() == GSOCK_TIMEDOUT
)
906 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
910 ret
= Send_Stream(buffer
, size
);
912 ret
= Send_Dgram(buffer
, size
);
914 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
918 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
))
920 m_error
= GSOCK_WOULDBLOCK
;
921 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
925 m_error
= GSOCK_IOERR
;
926 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
929 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
930 * in MSW). Once the first OUTPUT event is received, users can assume
931 * that the socket is writable until a read operation fails. Only then
932 * will further OUTPUT events be posted.
934 Enable(GSOCK_OUTPUT
);
938 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
944 * Polls the socket to determine its status. This function will
945 * check for the events specified in the 'flags' parameter, and
946 * it will return a mask indicating which operations can be
947 * performed. This function won't block, regardless of the
948 * mode (blocking | nonblocking) of the socket.
950 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
952 if (!gs_gui_functions
->CanUseEventLoop())
955 GSocketEventFlags result
= 0;
963 /* Do not use a static struct, Linux can garble it */
964 tv
.tv_sec
= m_timeout
/ 1000;
965 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
970 FD_SET(m_fd
, &readfds
);
971 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
972 FD_SET(m_fd
, &writefds
);
973 FD_SET(m_fd
, &exceptfds
);
975 /* Check 'sticky' CONNECTION flag first */
976 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
978 /* If we have already detected a LOST event, then don't try
979 * to do any further processing.
981 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
983 m_establishing
= false;
985 return (GSOCK_LOST_FLAG
& flags
);
989 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
991 /* What to do here? */
992 return (result
& flags
);
995 /* Check for readability */
996 if (FD_ISSET(m_fd
, &readfds
))
1000 int num
= recv(m_fd
, &c
, 1, MSG_PEEK
| GSOCKET_MSG_NOSIGNAL
);
1004 result
|= GSOCK_INPUT_FLAG
;
1008 if (m_server
&& m_stream
)
1010 result
|= GSOCK_CONNECTION_FLAG
;
1011 m_detected
|= GSOCK_CONNECTION_FLAG
;
1013 else if ((errno
!= EWOULDBLOCK
) && (errno
!= EAGAIN
) && (errno
!= EINTR
))
1015 m_detected
= GSOCK_LOST_FLAG
;
1016 m_establishing
= false;
1018 /* LOST event: Abort any further processing */
1019 return (GSOCK_LOST_FLAG
& flags
);
1024 /* Check for writability */
1025 if (FD_ISSET(m_fd
, &writefds
))
1027 if (m_establishing
&& !m_server
)
1030 SOCKOPTLEN_T len
= sizeof(error
);
1032 m_establishing
= false;
1034 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1038 m_detected
= GSOCK_LOST_FLAG
;
1040 /* LOST event: Abort any further processing */
1041 return (GSOCK_LOST_FLAG
& flags
);
1045 result
|= GSOCK_CONNECTION_FLAG
;
1046 m_detected
|= GSOCK_CONNECTION_FLAG
;
1051 result
|= GSOCK_OUTPUT_FLAG
;
1055 /* Check for exceptions and errors (is this useful in Unices?) */
1056 if (FD_ISSET(m_fd
, &exceptfds
))
1058 m_establishing
= false;
1059 m_detected
= GSOCK_LOST_FLAG
;
1061 /* LOST event: Abort any further processing */
1062 return (GSOCK_LOST_FLAG
& flags
);
1065 return (result
& flags
);
1072 return flags
& m_detected
;
1079 /* GSocket_SetNonBlocking:
1080 * Sets the socket to non-blocking mode. All IO calls will return
1083 void GSocket::SetNonBlocking(bool non_block
)
1087 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1089 m_non_blocking
= non_block
;
1092 /* GSocket_SetTimeout:
1093 * Sets the timeout for blocking calls. Time is expressed in
1096 void GSocket::SetTimeout(unsigned long millisec
)
1100 m_timeout
= millisec
;
1103 /* GSocket_GetError:
1104 * Returns the last error occured for this socket. Note that successful
1105 * operations do not clear this back to GSOCK_NOERROR, so use it only
1108 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1118 * There is data to be read in the input buffer. If, after a read
1119 * operation, there is still data available, the callback function will
1122 * The socket is available for writing. That is, the next write call
1123 * won't block. This event is generated only once, when the connection is
1124 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1125 * when the output buffer empties again. This means that the app should
1126 * assume that it can write since the first OUTPUT event, and no more
1127 * OUTPUT events will be generated unless an error occurs.
1129 * Connection succesfully established, for client sockets, or incoming
1130 * client connection, for server sockets. Wait for this event (also watch
1131 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1133 * The connection is lost (or a connection request failed); this could
1134 * be due to a failure, or due to the peer closing it gracefully.
1137 /* GSocket_SetCallback:
1138 * Enables the callbacks specified by 'flags'. Note that 'flags'
1139 * may be a combination of flags OR'ed toghether, so the same
1140 * callback function can be made to accept different events.
1141 * The callback function must have the following prototype:
1143 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1145 void GSocket::SetCallback(GSocketEventFlags flags
,
1146 GSocketCallback callback
, char *cdata
)
1152 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1154 if ((flags
& (1 << count
)) != 0)
1156 m_cbacks
[count
] = callback
;
1157 m_data
[count
] = cdata
;
1162 /* GSocket_UnsetCallback:
1163 * Disables all callbacks specified by 'flags', which may be a
1164 * combination of flags OR'ed toghether.
1166 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1172 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1174 if ((flags
& (1 << count
)) != 0)
1176 m_cbacks
[count
] = NULL
;
1177 m_data
[count
] = NULL
;
1182 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1183 void *optval
, int *optlen
)
1185 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, (SOCKOPTLEN_T
*)optlen
) == 0)
1187 return GSOCK_NOERROR
;
1189 return GSOCK_OPTERR
;
1192 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1193 const void *optval
, int optlen
)
1195 if (setsockopt(m_fd
, level
, optname
, (const char*)optval
, optlen
) == 0)
1197 return GSOCK_NOERROR
;
1199 return GSOCK_OPTERR
;
1202 #define CALL_CALLBACK(socket, event) { \
1203 socket->Disable(event); \
1204 if (socket->m_cbacks[event]) \
1205 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1209 void GSocket::Enable(GSocketEvent event
)
1211 m_detected
&= ~(1 << event
);
1212 gs_gui_functions
->Install_Callback(this, event
);
1215 void GSocket::Disable(GSocketEvent event
)
1217 m_detected
|= (1 << event
);
1218 gs_gui_functions
->Uninstall_Callback(this, event
);
1221 /* _GSocket_Input_Timeout:
1222 * For blocking sockets, wait until data is available or
1223 * until timeout ellapses.
1225 GSocketError
GSocket::Input_Timeout()
1231 /* Linux select() will overwrite the struct on return */
1232 tv
.tv_sec
= (m_timeout
/ 1000);
1233 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1235 if (!m_non_blocking
)
1238 FD_SET(m_fd
, &readfds
);
1239 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1242 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1243 m_error
= GSOCK_TIMEDOUT
;
1244 return GSOCK_TIMEDOUT
;
1248 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1249 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1250 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1251 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1252 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1253 m_error
= GSOCK_TIMEDOUT
;
1254 return GSOCK_TIMEDOUT
;
1257 return GSOCK_NOERROR
;
1260 /* _GSocket_Output_Timeout:
1261 * For blocking sockets, wait until data can be sent without
1262 * blocking or until timeout ellapses.
1264 GSocketError
GSocket::Output_Timeout()
1270 /* Linux select() will overwrite the struct on return */
1271 tv
.tv_sec
= (m_timeout
/ 1000);
1272 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1274 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1276 if (!m_non_blocking
)
1279 FD_SET(m_fd
, &writefds
);
1280 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1283 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1284 m_error
= GSOCK_TIMEDOUT
;
1285 return GSOCK_TIMEDOUT
;
1289 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1290 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1291 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1292 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1293 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1294 m_error
= GSOCK_TIMEDOUT
;
1295 return GSOCK_TIMEDOUT
;
1297 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1298 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1301 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1306 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1309 return GSOCK_NOERROR
;
1312 int GSocket::Recv_Stream(char *buffer
, int size
)
1317 ret
= recv(m_fd
, buffer
, size
, GSOCKET_MSG_NOSIGNAL
);
1318 } while (ret
== -1 && errno
== EINTR
);
1322 int GSocket::Recv_Dgram(char *buffer
, int size
)
1324 struct sockaddr from
;
1325 SOCKLEN_T fromlen
= sizeof(from
);
1329 fromlen
= sizeof(from
);
1333 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1334 } while (ret
== -1 && errno
== EINTR
);
1339 /* Translate a system address into a GSocket address */
1342 m_peer
= GAddress_new();
1345 m_error
= GSOCK_MEMERR
;
1349 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1350 if (err
!= GSOCK_NOERROR
)
1352 GAddress_destroy(m_peer
);
1361 int GSocket::Send_Stream(const char *buffer
, int size
)
1365 #ifndef __VISAGECPP__
1370 ret
= send(m_fd
, (char *)buffer
, size
, GSOCKET_MSG_NOSIGNAL
);
1371 } while (ret
== -1 && errno
== EINTR
);
1372 #ifndef __VISAGECPP__
1379 int GSocket::Send_Dgram(const char *buffer
, int size
)
1381 struct sockaddr
*addr
;
1387 m_error
= GSOCK_INVADDR
;
1391 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1392 if (err
!= GSOCK_NOERROR
)
1398 #ifndef __VISAGECPP__
1403 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1404 } while (ret
== -1 && errno
== EINTR
);
1405 #ifndef __VISAGECPP__
1409 /* Frees memory allocated from _GAddress_translate_to */
1415 void GSocket::Detected_Read()
1419 /* Safeguard against straggling call to Detected_Read */
1420 if (m_fd
== INVALID_SOCKET
)
1425 /* If we have already detected a LOST event, then don't try
1426 * to do any further processing.
1428 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1430 m_establishing
= false;
1432 CALL_CALLBACK(this, GSOCK_LOST
);
1437 int num
= recv(m_fd
, &c
, 1, MSG_PEEK
| GSOCKET_MSG_NOSIGNAL
);
1441 CALL_CALLBACK(this, GSOCK_INPUT
);
1445 if (m_server
&& m_stream
)
1447 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1451 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
) || (errno
== EINTR
))
1453 CALL_CALLBACK(this, GSOCK_INPUT
);
1457 CALL_CALLBACK(this, GSOCK_LOST
);
1464 void GSocket::Detected_Write()
1466 /* If we have already detected a LOST event, then don't try
1467 * to do any further processing.
1469 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1471 m_establishing
= false;
1473 CALL_CALLBACK(this, GSOCK_LOST
);
1478 if (m_establishing
&& !m_server
)
1481 SOCKOPTLEN_T len
= sizeof(error
);
1483 m_establishing
= false;
1485 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1489 CALL_CALLBACK(this, GSOCK_LOST
);
1494 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1495 /* We have to fire this event by hand because CONNECTION (for clients)
1496 * and OUTPUT are internally the same and we just disabled CONNECTION
1497 * events with the above macro.
1499 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1504 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1508 /* Compatibility functions for GSocket */
1509 GSocket
*GSocket_new(void)
1511 GSocket
*newsocket
= new GSocket();
1512 if(newsocket
->IsOk())
1519 * -------------------------------------------------------------------------
1521 * -------------------------------------------------------------------------
1524 /* CHECK_ADDRESS verifies that the current address family is either
1525 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1526 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1527 * an appropiate error code.
1529 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1531 #define CHECK_ADDRESS(address, family) \
1533 if (address->m_family == GSOCK_NOFAMILY) \
1534 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1535 return address->m_error; \
1536 if (address->m_family != GSOCK_##family) \
1538 address->m_error = GSOCK_INVADDR; \
1539 return GSOCK_INVADDR; \
1543 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1545 if (address->m_family == GSOCK_NOFAMILY) \
1546 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1548 if (address->m_family != GSOCK_##family) \
1550 address->m_error = GSOCK_INVADDR; \
1556 GAddress
*GAddress_new(void)
1560 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1563 address
->m_family
= GSOCK_NOFAMILY
;
1564 address
->m_addr
= NULL
;
1570 GAddress
*GAddress_copy(GAddress
*address
)
1574 assert(address
!= NULL
);
1576 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1579 memcpy(addr2
, address
, sizeof(GAddress
));
1581 if (address
->m_addr
&& address
->m_len
> 0)
1583 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1584 if (addr2
->m_addr
== NULL
)
1589 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1595 void GAddress_destroy(GAddress
*address
)
1597 assert(address
!= NULL
);
1599 if (address
->m_addr
)
1600 free(address
->m_addr
);
1605 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1607 assert(address
!= NULL
);
1609 address
->m_family
= type
;
1612 GAddressType
GAddress_GetFamily(GAddress
*address
)
1614 assert(address
!= NULL
);
1616 return address
->m_family
;
1619 GSocketError
_GAddress_translate_from(GAddress
*address
,
1620 struct sockaddr
*addr
, int len
)
1622 address
->m_realfamily
= addr
->sa_family
;
1623 switch (addr
->sa_family
)
1626 address
->m_family
= GSOCK_INET
;
1629 address
->m_family
= GSOCK_UNIX
;
1633 address
->m_family
= GSOCK_INET6
;
1638 address
->m_error
= GSOCK_INVOP
;
1643 if (address
->m_addr
)
1644 free(address
->m_addr
);
1646 address
->m_len
= len
;
1647 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1649 if (address
->m_addr
== NULL
)
1651 address
->m_error
= GSOCK_MEMERR
;
1652 return GSOCK_MEMERR
;
1654 memcpy(address
->m_addr
, addr
, len
);
1656 return GSOCK_NOERROR
;
1659 GSocketError
_GAddress_translate_to(GAddress
*address
,
1660 struct sockaddr
**addr
, int *len
)
1662 if (!address
->m_addr
)
1664 address
->m_error
= GSOCK_INVADDR
;
1665 return GSOCK_INVADDR
;
1668 *len
= address
->m_len
;
1669 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1672 address
->m_error
= GSOCK_MEMERR
;
1673 return GSOCK_MEMERR
;
1676 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1677 return GSOCK_NOERROR
;
1681 * -------------------------------------------------------------------------
1682 * Internet address family
1683 * -------------------------------------------------------------------------
1686 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1688 address
->m_len
= sizeof(struct sockaddr_in
);
1689 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1690 if (address
->m_addr
== NULL
)
1692 address
->m_error
= GSOCK_MEMERR
;
1693 return GSOCK_MEMERR
;
1696 address
->m_family
= GSOCK_INET
;
1697 address
->m_realfamily
= PF_INET
;
1698 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1699 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1701 return GSOCK_NOERROR
;
1704 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1707 struct in_addr
*addr
;
1709 assert(address
!= NULL
);
1711 CHECK_ADDRESS(address
, INET
);
1713 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1715 /* If it is a numeric host name, convert it now */
1716 #if defined(HAVE_INET_ATON)
1717 if (inet_aton(hostname
, addr
) == 0)
1719 #elif defined(HAVE_INET_ADDR)
1720 if ( (addr
->s_addr
= inet_addr(hostname
)) == (in_addr_t
)-1 )
1723 /* Use gethostbyname by default */
1725 int val
= 1; /* VA doesn't like constants in conditional expressions */
1730 struct in_addr
*array_addr
;
1732 /* It is a real name, we solve it */
1733 if ((he
= gethostbyname(hostname
)) == NULL
)
1735 /* Reset to invalid address */
1736 addr
->s_addr
= INADDR_NONE
;
1737 address
->m_error
= GSOCK_NOHOST
;
1738 return GSOCK_NOHOST
;
1740 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1741 addr
->s_addr
= array_addr
[0].s_addr
;
1743 return GSOCK_NOERROR
;
1746 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1748 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1751 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1752 unsigned long hostaddr
)
1754 struct in_addr
*addr
;
1756 assert(address
!= NULL
);
1758 CHECK_ADDRESS(address
, INET
);
1760 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1761 addr
->s_addr
= htonl(hostaddr
);
1763 return GSOCK_NOERROR
;
1766 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1767 const char *protocol
)
1770 struct sockaddr_in
*addr
;
1772 assert(address
!= NULL
);
1773 CHECK_ADDRESS(address
, INET
);
1777 address
->m_error
= GSOCK_INVPORT
;
1778 return GSOCK_INVPORT
;
1781 #if defined(__WXPM__) && defined(__EMX__)
1782 se
= getservbyname(port
, (char*)protocol
);
1784 se
= getservbyname(port
, protocol
);
1788 /* the cast to int suppresses compiler warnings about subscript having the
1790 if (isdigit((int)port
[0]))
1794 port_int
= atoi(port
);
1795 addr
= (struct sockaddr_in
*)address
->m_addr
;
1796 addr
->sin_port
= htons(port_int
);
1797 return GSOCK_NOERROR
;
1800 address
->m_error
= GSOCK_INVPORT
;
1801 return GSOCK_INVPORT
;
1804 addr
= (struct sockaddr_in
*)address
->m_addr
;
1805 addr
->sin_port
= se
->s_port
;
1807 return GSOCK_NOERROR
;
1810 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1812 struct sockaddr_in
*addr
;
1814 assert(address
!= NULL
);
1815 CHECK_ADDRESS(address
, INET
);
1817 addr
= (struct sockaddr_in
*)address
->m_addr
;
1818 addr
->sin_port
= htons(port
);
1820 return GSOCK_NOERROR
;
1823 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1827 struct sockaddr_in
*addr
;
1829 assert(address
!= NULL
);
1830 CHECK_ADDRESS(address
, INET
);
1832 addr
= (struct sockaddr_in
*)address
->m_addr
;
1833 addr_buf
= (char *)&(addr
->sin_addr
);
1835 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1838 address
->m_error
= GSOCK_NOHOST
;
1839 return GSOCK_NOHOST
;
1842 strncpy(hostname
, he
->h_name
, sbuf
);
1844 return GSOCK_NOERROR
;
1847 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1849 struct sockaddr_in
*addr
;
1851 assert(address
!= NULL
);
1852 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1854 addr
= (struct sockaddr_in
*)address
->m_addr
;
1856 return ntohl(addr
->sin_addr
.s_addr
);
1859 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1861 struct sockaddr_in
*addr
;
1863 assert(address
!= NULL
);
1864 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1866 addr
= (struct sockaddr_in
*)address
->m_addr
;
1867 return ntohs(addr
->sin_port
);
1871 * -------------------------------------------------------------------------
1872 * Unix address family
1873 * -------------------------------------------------------------------------
1876 #ifndef __VISAGECPP__
1877 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1879 address
->m_len
= sizeof(struct sockaddr_un
);
1880 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1881 if (address
->m_addr
== NULL
)
1883 address
->m_error
= GSOCK_MEMERR
;
1884 return GSOCK_MEMERR
;
1887 address
->m_family
= GSOCK_UNIX
;
1888 address
->m_realfamily
= PF_UNIX
;
1889 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1890 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1892 return GSOCK_NOERROR
;
1895 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1897 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1899 struct sockaddr_un
*addr
;
1901 assert(address
!= NULL
);
1903 CHECK_ADDRESS(address
, UNIX
);
1905 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1906 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1907 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1909 return GSOCK_NOERROR
;
1912 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1914 struct sockaddr_un
*addr
;
1916 assert(address
!= NULL
);
1917 CHECK_ADDRESS(address
, UNIX
);
1919 addr
= (struct sockaddr_un
*)address
->m_addr
;
1921 strncpy(path
, addr
->sun_path
, sbuf
);
1923 return GSOCK_NOERROR
;
1925 #endif /* !defined(__VISAGECPP__) */
1926 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */