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>
109 # define SOCKLEN_T unsigned int
113 # define SOCKLEN_T socklen_t
116 # define SOCKLEN_T int
121 /* undefine for OSX - its really an int */
124 # define SOCKLEN_T int
126 #endif /* SOCKLEN_T */
129 * MSW defines this, Unices don't.
131 #ifndef INVALID_SOCKET
132 #define INVALID_SOCKET -1
135 /* UnixWare reportedly needs this for FIONBIO definition */
137 #include <sys/filio.h>
141 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
142 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
145 #define INADDR_NONE INADDR_BROADCAST
148 #define MASK_SIGNAL() \
150 void (*old_handler)(int); \
152 old_handler = signal(SIGPIPE, SIG_IGN);
154 #define UNMASK_SIGNAL() \
155 signal(SIGPIPE, old_handler); \
159 #ifndef __GSOCKET_STANDALONE__
160 # include "wx/unix/gsockunx.h"
161 # include "wx/gsocket.h"
163 # include "gsockunx.h"
164 # include "gsocket.h"
165 #endif /* __GSOCKET_STANDALONE__ */
167 /* debugging helpers */
168 #ifdef __GSOCKET_DEBUG__
169 # define GSocket_Debug(args) printf args
171 # define GSocket_Debug(args)
172 #endif /* __GSOCKET_DEBUG__ */
174 /* Table of GUI-related functions. We must call them indirectly because
175 * of wxBase and GUI separation: */
177 static GSocketGUIFunctionsTable
*gs_gui_functions
;
179 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
182 virtual bool OnInit();
183 virtual void OnExit();
184 virtual bool CanUseEventLoop();
185 virtual bool Init_Socket(GSocket
*socket
);
186 virtual void Destroy_Socket(GSocket
*socket
);
187 virtual void Install_Callback(GSocket
*socket
, GSocketEvent event
);
188 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
189 virtual void Enable_Events(GSocket
*socket
);
190 virtual void Disable_Events(GSocket
*socket
);
193 bool GSocketGUIFunctionsTableNull::OnInit()
195 void GSocketGUIFunctionsTableNull::OnExit()
197 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
199 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*socket
)
201 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*socket
)
203 void GSocketGUIFunctionsTableNull::Install_Callback(GSocket
*socket
, GSocketEvent event
)
205 void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
207 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*socket
)
209 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*socket
)
211 /* Global initialisers */
213 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
215 gs_gui_functions
= guifunc
;
218 int GSocket_Init(void)
220 if (!gs_gui_functions
)
222 static GSocketGUIFunctionsTableNull table
;
223 gs_gui_functions
= &table
;
225 if ( !gs_gui_functions
->OnInit() )
230 void GSocket_Cleanup(void)
232 if (gs_gui_functions
)
234 gs_gui_functions
->OnExit();
238 /* Constructors / Destructors for GSocket */
244 m_fd
= INVALID_SOCKET
;
245 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
252 m_error
= GSOCK_NOERROR
;
255 m_gui_dependent
= NULL
;
256 m_non_blocking
= false;
257 m_timeout
= 10*60*1000;
258 /* 10 minutes * 60 sec * 1000 millisec */
259 m_establishing
= false;
261 assert(gs_gui_functions
);
262 /* Per-socket GUI-specific initialization */
263 m_ok
= gs_gui_functions
->Init_Socket(this);
266 void GSocket::Close()
268 gs_gui_functions
->Disable_Events(this);
269 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
270 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
273 m_fd
= INVALID_SOCKET
;
280 /* Check that the socket is really shutdowned */
281 if (m_fd
!= INVALID_SOCKET
)
284 /* Per-socket GUI-specific cleanup */
285 gs_gui_functions
->Destroy_Socket(this);
287 /* Destroy private addresses */
289 GAddress_destroy(m_local
);
292 GAddress_destroy(m_peer
);
296 * Disallow further read/write operations on this socket, close
297 * the fd and disable all callbacks.
299 void GSocket::Shutdown()
305 /* If socket has been created, shutdown it */
306 if (m_fd
!= INVALID_SOCKET
)
312 /* Disable GUI callbacks */
313 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
314 m_cbacks
[evt
] = NULL
;
316 m_detected
= GSOCK_LOST_FLAG
;
319 /* Address handling */
325 * Set or get the local or peer address for this socket. The 'set'
326 * functions return GSOCK_NOERROR on success, an error code otherwise.
327 * The 'get' functions return a pointer to a GAddress object on success,
328 * or NULL otherwise, in which case they set the error code of the
329 * corresponding GSocket.
332 * GSOCK_INVSOCK - the socket is not valid.
333 * GSOCK_INVADDR - the address is not valid.
335 GSocketError
GSocket::SetLocal(GAddress
*address
)
339 /* the socket must be initialized, or it must be a server */
340 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
342 m_error
= GSOCK_INVSOCK
;
343 return GSOCK_INVSOCK
;
347 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
349 m_error
= GSOCK_INVADDR
;
350 return GSOCK_INVADDR
;
354 GAddress_destroy(m_local
);
356 m_local
= GAddress_copy(address
);
358 return GSOCK_NOERROR
;
361 GSocketError
GSocket::SetPeer(GAddress
*address
)
366 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
368 m_error
= GSOCK_INVADDR
;
369 return GSOCK_INVADDR
;
373 GAddress_destroy(m_peer
);
375 m_peer
= GAddress_copy(address
);
377 return GSOCK_NOERROR
;
380 GAddress
*GSocket::GetLocal()
383 struct sockaddr addr
;
384 SOCKLEN_T size
= sizeof(addr
);
389 /* try to get it from the m_local var first */
391 return GAddress_copy(m_local
);
393 /* else, if the socket is initialized, try getsockname */
394 if (m_fd
== INVALID_SOCKET
)
396 m_error
= GSOCK_INVSOCK
;
400 if (getsockname(m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
402 m_error
= GSOCK_IOERR
;
406 /* got a valid address from getsockname, create a GAddress object */
407 address
= GAddress_new();
410 m_error
= GSOCK_MEMERR
;
414 err
= _GAddress_translate_from(address
, &addr
, size
);
415 if (err
!= GSOCK_NOERROR
)
417 GAddress_destroy(address
);
425 GAddress
*GSocket::GetPeer()
429 /* try to get it from the m_peer var */
431 return GAddress_copy(m_peer
);
436 /* Server specific parts */
438 /* GSocket_SetServer:
439 * Sets up this socket as a server. The local address must have been
440 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
441 * Returns GSOCK_NOERROR on success, one of the following otherwise:
444 * GSOCK_INVSOCK - the socket is in use.
445 * GSOCK_INVADDR - the local address has not been set.
446 * GSOCK_IOERR - low-level error.
448 GSocketError
GSocket::SetServer()
454 /* must not be in use */
455 if (m_fd
!= INVALID_SOCKET
)
457 m_error
= GSOCK_INVSOCK
;
458 return GSOCK_INVSOCK
;
461 /* the local addr must have been set */
464 m_error
= GSOCK_INVADDR
;
465 return GSOCK_INVADDR
;
468 /* Initialize all fields */
472 /* Create the socket */
473 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
475 if (m_fd
== INVALID_SOCKET
)
477 m_error
= GSOCK_IOERR
;
480 #if defined(__EMX__) || defined(__VISAGECPP__)
481 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
483 ioctl(m_fd
, FIONBIO
, &arg
);
485 gs_gui_functions
->Enable_Events(this);
487 /* allow a socket to re-bind if the socket is in the TIME_WAIT
488 state after being previously closed.
491 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
493 /* Bind to the local address,
494 * retrieve the actual address bound,
495 * and listen up to 5 connections.
497 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
500 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
501 (listen(m_fd
, 5) != 0))
504 m_error
= GSOCK_IOERR
;
508 return GSOCK_NOERROR
;
511 /* GSocket_WaitConnection:
512 * Waits for an incoming client connection. Returns a pointer to
513 * a GSocket object, or NULL if there was an error, in which case
514 * the last error field will be updated for the calling GSocket.
516 * Error codes (set in the calling GSocket)
517 * GSOCK_INVSOCK - the socket is not valid or not a server.
518 * GSOCK_TIMEDOUT - timeout, no incoming connections.
519 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
520 * GSOCK_MEMERR - couldn't allocate memory.
521 * GSOCK_IOERR - low-level error.
523 GSocket
*GSocket::WaitConnection()
525 struct sockaddr from
;
526 SOCKLEN_T fromlen
= sizeof(from
);
533 /* Reenable CONNECTION events */
534 Enable(GSOCK_CONNECTION
);
536 /* If the socket has already been created, we exit immediately */
537 if (m_fd
== INVALID_SOCKET
|| !m_server
)
539 m_error
= GSOCK_INVSOCK
;
543 /* Create a GSocket object for the new connection */
544 connection
= GSocket_new();
548 m_error
= GSOCK_MEMERR
;
552 /* Wait for a connection (with timeout) */
553 if (Input_Timeout() == GSOCK_TIMEDOUT
)
556 /* m_error set by _GSocket_Input_Timeout */
560 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
562 if (connection
->m_fd
== INVALID_SOCKET
)
564 if (errno
== EWOULDBLOCK
)
565 m_error
= GSOCK_WOULDBLOCK
;
567 m_error
= GSOCK_IOERR
;
573 /* Initialize all fields */
574 connection
->m_server
= false;
575 connection
->m_stream
= true;
577 /* Setup the peer address field */
578 connection
->m_peer
= GAddress_new();
579 if (!connection
->m_peer
)
582 m_error
= GSOCK_MEMERR
;
585 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
586 if (err
!= GSOCK_NOERROR
)
588 GAddress_destroy(connection
->m_peer
);
593 #if defined(__EMX__) || defined(__VISAGECPP__)
594 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
596 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
598 gs_gui_functions
->Enable_Events(connection
);
603 bool GSocket::SetReusable()
605 /* socket must not be null, and must not be in use/already bound */
606 if (this && m_fd
== INVALID_SOCKET
) {
613 /* Client specific parts */
616 * For stream (connection oriented) sockets, GSocket_Connect() tries
617 * to establish a client connection to a server using the peer address
618 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
619 * connection has been succesfully established, or one of the error
620 * codes listed below. Note that for nonblocking sockets, a return
621 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
622 * request can be completed later; you should use GSocket_Select()
623 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
624 * corresponding asynchronous events.
626 * For datagram (non connection oriented) sockets, GSocket_Connect()
627 * just sets the peer address established with GSocket_SetPeer() as
628 * default destination.
631 * GSOCK_INVSOCK - the socket is in use or not valid.
632 * GSOCK_INVADDR - the peer address has not been established.
633 * GSOCK_TIMEDOUT - timeout, the connection failed.
634 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
635 * GSOCK_MEMERR - couldn't allocate memory.
636 * GSOCK_IOERR - low-level error.
638 GSocketError
GSocket::Connect(GSocketStream stream
)
645 /* Enable CONNECTION events (needed for nonblocking connections) */
646 Enable(GSOCK_CONNECTION
);
648 if (m_fd
!= INVALID_SOCKET
)
650 m_error
= GSOCK_INVSOCK
;
651 return GSOCK_INVSOCK
;
656 m_error
= GSOCK_INVADDR
;
657 return GSOCK_INVADDR
;
660 /* Streamed or dgram socket? */
661 m_stream
= (stream
== GSOCK_STREAMED
);
663 m_establishing
= false;
665 /* Create the socket */
666 m_fd
= socket(m_peer
->m_realfamily
,
667 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
669 if (m_fd
== INVALID_SOCKET
)
671 m_error
= GSOCK_IOERR
;
674 #if defined(__EMX__) || defined(__VISAGECPP__)
675 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
677 ioctl(m_fd
, FIONBIO
, &arg
);
679 gs_gui_functions
->Enable_Events(this);
681 /* Connect it to the peer address, with a timeout (see below) */
682 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
688 /* If connect failed with EINPROGRESS and the GSocket object
689 * is in blocking mode, we select() for the specified timeout
690 * checking for writability to see if the connection request
693 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
695 if (Output_Timeout() == GSOCK_TIMEDOUT
)
698 /* m_error is set in _GSocket_Output_Timeout */
699 return GSOCK_TIMEDOUT
;
704 SOCKLEN_T len
= sizeof(error
);
706 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
709 return GSOCK_NOERROR
;
713 /* If connect failed with EINPROGRESS and the GSocket object
714 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
715 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
716 * this way if the connection completes, a GSOCK_CONNECTION
717 * event will be generated, if enabled.
719 if ((err
== EINPROGRESS
) && (m_non_blocking
))
721 m_establishing
= true;
722 m_error
= GSOCK_WOULDBLOCK
;
723 return GSOCK_WOULDBLOCK
;
726 /* If connect failed with an error other than EINPROGRESS,
727 * then the call to GSocket_Connect has failed.
730 m_error
= GSOCK_IOERR
;
734 return GSOCK_NOERROR
;
737 /* Datagram sockets */
739 /* GSocket_SetNonOriented:
740 * Sets up this socket as a non-connection oriented (datagram) socket.
741 * Before using this function, the local address must have been set
742 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
743 * on success, or one of the following otherwise.
746 * GSOCK_INVSOCK - the socket is in use.
747 * GSOCK_INVADDR - the local address has not been set.
748 * GSOCK_IOERR - low-level error.
750 GSocketError
GSocket::SetNonOriented()
756 if (m_fd
!= INVALID_SOCKET
)
758 m_error
= GSOCK_INVSOCK
;
759 return GSOCK_INVSOCK
;
764 m_error
= GSOCK_INVADDR
;
765 return GSOCK_INVADDR
;
768 /* Initialize all fields */
772 /* Create the socket */
773 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
775 if (m_fd
== INVALID_SOCKET
)
777 m_error
= GSOCK_IOERR
;
780 #if defined(__EMX__) || defined(__VISAGECPP__)
781 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
783 ioctl(m_fd
, FIONBIO
, &arg
);
785 gs_gui_functions
->Enable_Events(this);
787 /* Bind to the local address,
788 * and retrieve the actual address bound.
790 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
793 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
796 m_error
= GSOCK_IOERR
;
800 return GSOCK_NOERROR
;
805 /* Like recv(), send(), ... */
806 int GSocket::Read(char *buffer
, int size
)
812 if (m_fd
== INVALID_SOCKET
|| m_server
)
814 m_error
= GSOCK_INVSOCK
;
818 /* Disable events during query of socket status */
819 Disable(GSOCK_INPUT
);
821 /* If the socket is blocking, wait for data (with a timeout) */
822 if (Input_Timeout() == GSOCK_TIMEDOUT
)
823 /* We no longer return here immediately, otherwise socket events would not be re-enabled! */
828 ret
= Recv_Stream(buffer
, size
);
830 ret
= Recv_Dgram(buffer
, size
);
835 if (errno
== EWOULDBLOCK
)
836 m_error
= GSOCK_WOULDBLOCK
;
838 m_error
= GSOCK_IOERR
;
841 /* Enable events again now that we are done processing */
847 int GSocket::Write(const char *buffer
, int size
)
853 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
855 if (m_fd
== INVALID_SOCKET
|| m_server
)
857 m_error
= GSOCK_INVSOCK
;
861 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
863 /* If the socket is blocking, wait for writability (with a timeout) */
864 if (Output_Timeout() == GSOCK_TIMEDOUT
)
867 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
871 ret
= Send_Stream(buffer
, size
);
873 ret
= Send_Dgram(buffer
, size
);
875 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
879 if (errno
== EWOULDBLOCK
)
881 m_error
= GSOCK_WOULDBLOCK
;
882 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
886 m_error
= GSOCK_IOERR
;
887 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
890 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
891 * in MSW). Once the first OUTPUT event is received, users can assume
892 * that the socket is writable until a read operation fails. Only then
893 * will further OUTPUT events be posted.
895 Enable(GSOCK_OUTPUT
);
899 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
905 * Polls the socket to determine its status. This function will
906 * check for the events specified in the 'flags' parameter, and
907 * it will return a mask indicating which operations can be
908 * performed. This function won't block, regardless of the
909 * mode (blocking | nonblocking) of the socket.
911 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
913 if (!gs_gui_functions
->CanUseEventLoop())
916 GSocketEventFlags result
= 0;
924 /* Do not use a static struct, Linux can garble it */
925 tv
.tv_sec
= m_timeout
/ 1000;
926 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
931 FD_SET(m_fd
, &readfds
);
932 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
933 FD_SET(m_fd
, &writefds
);
934 FD_SET(m_fd
, &exceptfds
);
936 /* Check 'sticky' CONNECTION flag first */
937 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
939 /* If we have already detected a LOST event, then don't try
940 * to do any further processing.
942 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
944 m_establishing
= false;
946 return (GSOCK_LOST_FLAG
& flags
);
950 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
952 /* What to do here? */
953 return (result
& flags
);
956 /* Check for readability */
957 if (FD_ISSET(m_fd
, &readfds
))
961 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
963 result
|= GSOCK_INPUT_FLAG
;
967 if (m_server
&& m_stream
)
969 result
|= GSOCK_CONNECTION_FLAG
;
970 m_detected
|= GSOCK_CONNECTION_FLAG
;
974 m_detected
= GSOCK_LOST_FLAG
;
975 m_establishing
= false;
977 /* LOST event: Abort any further processing */
978 return (GSOCK_LOST_FLAG
& flags
);
983 /* Check for writability */
984 if (FD_ISSET(m_fd
, &writefds
))
986 if (m_establishing
&& !m_server
)
989 SOCKLEN_T len
= sizeof(error
);
991 m_establishing
= false;
993 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
997 m_detected
= GSOCK_LOST_FLAG
;
999 /* LOST event: Abort any further processing */
1000 return (GSOCK_LOST_FLAG
& flags
);
1004 result
|= GSOCK_CONNECTION_FLAG
;
1005 m_detected
|= GSOCK_CONNECTION_FLAG
;
1010 result
|= GSOCK_OUTPUT_FLAG
;
1014 /* Check for exceptions and errors (is this useful in Unices?) */
1015 if (FD_ISSET(m_fd
, &exceptfds
))
1017 m_establishing
= false;
1018 m_detected
= GSOCK_LOST_FLAG
;
1020 /* LOST event: Abort any further processing */
1021 return (GSOCK_LOST_FLAG
& flags
);
1024 return (result
& flags
);
1031 return flags
& m_detected
;
1038 /* GSocket_SetNonBlocking:
1039 * Sets the socket to non-blocking mode. All IO calls will return
1042 void GSocket::SetNonBlocking(bool non_block
)
1046 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1048 m_non_blocking
= non_block
;
1051 /* GSocket_SetTimeout:
1052 * Sets the timeout for blocking calls. Time is expressed in
1055 void GSocket::SetTimeout(unsigned long millisec
)
1059 m_timeout
= millisec
;
1062 /* GSocket_GetError:
1063 * Returns the last error occured for this socket. Note that successful
1064 * operations do not clear this back to GSOCK_NOERROR, so use it only
1067 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1077 * There is data to be read in the input buffer. If, after a read
1078 * operation, there is still data available, the callback function will
1081 * The socket is available for writing. That is, the next write call
1082 * won't block. This event is generated only once, when the connection is
1083 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1084 * when the output buffer empties again. This means that the app should
1085 * assume that it can write since the first OUTPUT event, and no more
1086 * OUTPUT events will be generated unless an error occurs.
1088 * Connection succesfully established, for client sockets, or incoming
1089 * client connection, for server sockets. Wait for this event (also watch
1090 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1092 * The connection is lost (or a connection request failed); this could
1093 * be due to a failure, or due to the peer closing it gracefully.
1096 /* GSocket_SetCallback:
1097 * Enables the callbacks specified by 'flags'. Note that 'flags'
1098 * may be a combination of flags OR'ed toghether, so the same
1099 * callback function can be made to accept different events.
1100 * The callback function must have the following prototype:
1102 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1104 void GSocket::SetCallback(GSocketEventFlags flags
,
1105 GSocketCallback callback
, char *cdata
)
1111 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1113 if ((flags
& (1 << count
)) != 0)
1115 m_cbacks
[count
] = callback
;
1116 m_data
[count
] = cdata
;
1121 /* GSocket_UnsetCallback:
1122 * Disables all callbacks specified by 'flags', which may be a
1123 * combination of flags OR'ed toghether.
1125 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1131 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1133 if ((flags
& (1 << count
)) != 0)
1135 m_cbacks
[count
] = NULL
;
1136 m_data
[count
] = NULL
;
1141 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1142 void *optval
, int *optlen
)
1144 if (getsockopt(m_fd
, level
, optname
, optval
, (SOCKLEN_T
*)optlen
) == 0)
1146 return GSOCK_NOERROR
;
1148 return GSOCK_OPTERR
;
1151 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1152 const void *optval
, int optlen
)
1154 if (setsockopt(m_fd
, level
, optname
, optval
, optlen
) == 0)
1156 return GSOCK_NOERROR
;
1158 return GSOCK_OPTERR
;
1161 #define CALL_CALLBACK(socket, event) { \
1162 socket->Disable(event); \
1163 if (socket->m_cbacks[event]) \
1164 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1168 void GSocket::Enable(GSocketEvent event
)
1170 m_detected
&= ~(1 << event
);
1171 gs_gui_functions
->Install_Callback(this, event
);
1174 void GSocket::Disable(GSocketEvent event
)
1176 m_detected
|= (1 << event
);
1177 gs_gui_functions
->Uninstall_Callback(this, event
);
1180 /* _GSocket_Input_Timeout:
1181 * For blocking sockets, wait until data is available or
1182 * until timeout ellapses.
1184 GSocketError
GSocket::Input_Timeout()
1190 /* Linux select() will overwrite the struct on return */
1191 tv
.tv_sec
= (m_timeout
/ 1000);
1192 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1194 if (!m_non_blocking
)
1197 FD_SET(m_fd
, &readfds
);
1198 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1201 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1202 m_error
= GSOCK_TIMEDOUT
;
1203 return GSOCK_TIMEDOUT
;
1207 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1208 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1209 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1210 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1211 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1212 m_error
= GSOCK_TIMEDOUT
;
1213 return GSOCK_TIMEDOUT
;
1216 return GSOCK_NOERROR
;
1219 /* _GSocket_Output_Timeout:
1220 * For blocking sockets, wait until data can be sent without
1221 * blocking or until timeout ellapses.
1223 GSocketError
GSocket::Output_Timeout()
1229 /* Linux select() will overwrite the struct on return */
1230 tv
.tv_sec
= (m_timeout
/ 1000);
1231 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1233 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1235 if (!m_non_blocking
)
1238 FD_SET(m_fd
, &writefds
);
1239 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1242 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1243 m_error
= GSOCK_TIMEDOUT
;
1244 return GSOCK_TIMEDOUT
;
1248 GSocket_Debug(( "GSocket_Output_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
;
1256 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1257 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1260 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1265 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1268 return GSOCK_NOERROR
;
1271 int GSocket::Recv_Stream(char *buffer
, int size
)
1273 return recv(m_fd
, buffer
, size
, 0);
1276 int GSocket::Recv_Dgram(char *buffer
, int size
)
1278 struct sockaddr from
;
1279 SOCKLEN_T fromlen
= sizeof(from
);
1283 fromlen
= sizeof(from
);
1285 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1290 /* Translate a system address into a GSocket address */
1293 m_peer
= GAddress_new();
1296 m_error
= GSOCK_MEMERR
;
1300 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1301 if (err
!= GSOCK_NOERROR
)
1303 GAddress_destroy(m_peer
);
1312 int GSocket::Send_Stream(const char *buffer
, int size
)
1316 #ifndef __VISAGECPP__
1318 ret
= send(m_fd
, buffer
, size
, 0);
1321 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1327 int GSocket::Send_Dgram(const char *buffer
, int size
)
1329 struct sockaddr
*addr
;
1335 m_error
= GSOCK_INVADDR
;
1339 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1340 if (err
!= GSOCK_NOERROR
)
1346 #ifndef __VISAGECPP__
1348 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1351 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1354 /* Frees memory allocated from _GAddress_translate_to */
1360 void GSocket::Detected_Read()
1364 /* If we have already detected a LOST event, then don't try
1365 * to do any further processing.
1367 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1369 m_establishing
= false;
1371 CALL_CALLBACK(this, GSOCK_LOST
);
1376 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1378 CALL_CALLBACK(this, GSOCK_INPUT
);
1382 if (m_server
&& m_stream
)
1384 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1388 CALL_CALLBACK(this, GSOCK_LOST
);
1394 void GSocket::Detected_Write()
1396 /* If we have already detected a LOST event, then don't try
1397 * to do any further processing.
1399 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1401 m_establishing
= false;
1403 CALL_CALLBACK(this, GSOCK_LOST
);
1408 if (m_establishing
&& !m_server
)
1411 SOCKLEN_T len
= sizeof(error
);
1413 m_establishing
= false;
1415 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1419 CALL_CALLBACK(this, GSOCK_LOST
);
1424 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1425 /* We have to fire this event by hand because CONNECTION (for clients)
1426 * and OUTPUT are internally the same and we just disabled CONNECTION
1427 * events with the above macro.
1429 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1434 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1438 /* Compatibility functions for GSocket */
1439 GSocket
*GSocket_new(void)
1441 GSocket
*newsocket
= new GSocket();
1442 if(newsocket
->IsOk())
1449 * -------------------------------------------------------------------------
1451 * -------------------------------------------------------------------------
1454 /* CHECK_ADDRESS verifies that the current address family is either
1455 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1456 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1457 * an appropiate error code.
1459 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1461 #define CHECK_ADDRESS(address, family) \
1463 if (address->m_family == GSOCK_NOFAMILY) \
1464 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1465 return address->m_error; \
1466 if (address->m_family != GSOCK_##family) \
1468 address->m_error = GSOCK_INVADDR; \
1469 return GSOCK_INVADDR; \
1473 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1475 if (address->m_family == GSOCK_NOFAMILY) \
1476 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1478 if (address->m_family != GSOCK_##family) \
1480 address->m_error = GSOCK_INVADDR; \
1486 GAddress
*GAddress_new(void)
1490 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1493 address
->m_family
= GSOCK_NOFAMILY
;
1494 address
->m_addr
= NULL
;
1500 GAddress
*GAddress_copy(GAddress
*address
)
1504 assert(address
!= NULL
);
1506 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1509 memcpy(addr2
, address
, sizeof(GAddress
));
1511 if (address
->m_addr
&& address
->m_len
> 0)
1513 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1514 if (addr2
->m_addr
== NULL
)
1519 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1525 void GAddress_destroy(GAddress
*address
)
1527 assert(address
!= NULL
);
1529 if (address
->m_addr
)
1530 free(address
->m_addr
);
1535 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1537 assert(address
!= NULL
);
1539 address
->m_family
= type
;
1542 GAddressType
GAddress_GetFamily(GAddress
*address
)
1544 assert(address
!= NULL
);
1546 return address
->m_family
;
1549 GSocketError
_GAddress_translate_from(GAddress
*address
,
1550 struct sockaddr
*addr
, int len
)
1552 address
->m_realfamily
= addr
->sa_family
;
1553 switch (addr
->sa_family
)
1556 address
->m_family
= GSOCK_INET
;
1559 address
->m_family
= GSOCK_UNIX
;
1563 address
->m_family
= GSOCK_INET6
;
1568 address
->m_error
= GSOCK_INVOP
;
1573 if (address
->m_addr
)
1574 free(address
->m_addr
);
1576 address
->m_len
= len
;
1577 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1579 if (address
->m_addr
== NULL
)
1581 address
->m_error
= GSOCK_MEMERR
;
1582 return GSOCK_MEMERR
;
1584 memcpy(address
->m_addr
, addr
, len
);
1586 return GSOCK_NOERROR
;
1589 GSocketError
_GAddress_translate_to(GAddress
*address
,
1590 struct sockaddr
**addr
, int *len
)
1592 if (!address
->m_addr
)
1594 address
->m_error
= GSOCK_INVADDR
;
1595 return GSOCK_INVADDR
;
1598 *len
= address
->m_len
;
1599 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1602 address
->m_error
= GSOCK_MEMERR
;
1603 return GSOCK_MEMERR
;
1606 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1607 return GSOCK_NOERROR
;
1611 * -------------------------------------------------------------------------
1612 * Internet address family
1613 * -------------------------------------------------------------------------
1616 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1618 address
->m_len
= sizeof(struct sockaddr_in
);
1619 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1620 if (address
->m_addr
== NULL
)
1622 address
->m_error
= GSOCK_MEMERR
;
1623 return GSOCK_MEMERR
;
1626 address
->m_family
= GSOCK_INET
;
1627 address
->m_realfamily
= PF_INET
;
1628 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1629 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1631 return GSOCK_NOERROR
;
1634 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1637 struct in_addr
*addr
;
1639 assert(address
!= NULL
);
1641 CHECK_ADDRESS(address
, INET
);
1643 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1645 /* If it is a numeric host name, convert it now */
1646 #if defined(HAVE_INET_ATON)
1647 if (inet_aton(hostname
, addr
) == 0)
1649 #elif defined(HAVE_INET_ADDR)
1650 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1653 /* Use gethostbyname by default */
1655 int val
= 1; /* VA doesn't like constants in conditional expressions */
1660 struct in_addr
*array_addr
;
1662 /* It is a real name, we solve it */
1663 if ((he
= gethostbyname(hostname
)) == NULL
)
1665 /* Reset to invalid address */
1666 addr
->s_addr
= INADDR_NONE
;
1667 address
->m_error
= GSOCK_NOHOST
;
1668 return GSOCK_NOHOST
;
1670 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1671 addr
->s_addr
= array_addr
[0].s_addr
;
1673 return GSOCK_NOERROR
;
1676 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1678 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1681 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1682 unsigned long hostaddr
)
1684 struct in_addr
*addr
;
1686 assert(address
!= NULL
);
1688 CHECK_ADDRESS(address
, INET
);
1690 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1691 addr
->s_addr
= htonl(hostaddr
);
1693 return GSOCK_NOERROR
;
1696 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1697 const char *protocol
)
1700 struct sockaddr_in
*addr
;
1702 assert(address
!= NULL
);
1703 CHECK_ADDRESS(address
, INET
);
1707 address
->m_error
= GSOCK_INVPORT
;
1708 return GSOCK_INVPORT
;
1711 se
= getservbyname(port
, protocol
);
1714 /* the cast to int suppresses compiler warnings about subscript having the
1716 if (isdigit((int)port
[0]))
1720 port_int
= atoi(port
);
1721 addr
= (struct sockaddr_in
*)address
->m_addr
;
1722 addr
->sin_port
= htons(port_int
);
1723 return GSOCK_NOERROR
;
1726 address
->m_error
= GSOCK_INVPORT
;
1727 return GSOCK_INVPORT
;
1730 addr
= (struct sockaddr_in
*)address
->m_addr
;
1731 addr
->sin_port
= se
->s_port
;
1733 return GSOCK_NOERROR
;
1736 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1738 struct sockaddr_in
*addr
;
1740 assert(address
!= NULL
);
1741 CHECK_ADDRESS(address
, INET
);
1743 addr
= (struct sockaddr_in
*)address
->m_addr
;
1744 addr
->sin_port
= htons(port
);
1746 return GSOCK_NOERROR
;
1749 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1753 struct sockaddr_in
*addr
;
1755 assert(address
!= NULL
);
1756 CHECK_ADDRESS(address
, INET
);
1758 addr
= (struct sockaddr_in
*)address
->m_addr
;
1759 addr_buf
= (char *)&(addr
->sin_addr
);
1761 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1764 address
->m_error
= GSOCK_NOHOST
;
1765 return GSOCK_NOHOST
;
1768 strncpy(hostname
, he
->h_name
, sbuf
);
1770 return GSOCK_NOERROR
;
1773 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1775 struct sockaddr_in
*addr
;
1777 assert(address
!= NULL
);
1778 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1780 addr
= (struct sockaddr_in
*)address
->m_addr
;
1782 return ntohl(addr
->sin_addr
.s_addr
);
1785 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1787 struct sockaddr_in
*addr
;
1789 assert(address
!= NULL
);
1790 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1792 addr
= (struct sockaddr_in
*)address
->m_addr
;
1793 return ntohs(addr
->sin_port
);
1797 * -------------------------------------------------------------------------
1798 * Unix address family
1799 * -------------------------------------------------------------------------
1802 #ifndef __VISAGECPP__
1803 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1805 address
->m_len
= sizeof(struct sockaddr_un
);
1806 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1807 if (address
->m_addr
== NULL
)
1809 address
->m_error
= GSOCK_MEMERR
;
1810 return GSOCK_MEMERR
;
1813 address
->m_family
= GSOCK_UNIX
;
1814 address
->m_realfamily
= PF_UNIX
;
1815 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1816 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1818 return GSOCK_NOERROR
;
1821 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1823 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1825 struct sockaddr_un
*addr
;
1827 assert(address
!= NULL
);
1829 CHECK_ADDRESS(address
, UNIX
);
1831 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1832 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1833 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1835 return GSOCK_NOERROR
;
1838 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1840 struct sockaddr_un
*addr
;
1842 assert(address
!= NULL
);
1843 CHECK_ADDRESS(address
, UNIX
);
1845 addr
= (struct sockaddr_un
*)address
->m_addr
;
1847 strncpy(path
, addr
->sun_path
, sbuf
);
1849 return GSOCK_NOERROR
;
1851 #endif /* !defined(__VISAGECPP__) */
1852 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */