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__ ) && ( MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_2 )
135 #define SOCKOPTLEN_T int
136 #define SOCKLEN_T int
140 * MSW defines this, Unices don't.
142 #ifndef INVALID_SOCKET
143 #define INVALID_SOCKET -1
146 /* UnixWare reportedly needs this for FIONBIO definition */
148 #include <sys/filio.h>
152 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
153 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
156 #define INADDR_NONE INADDR_BROADCAST
159 #define MASK_SIGNAL() \
161 void (*old_handler)(int); \
163 old_handler = signal(SIGPIPE, SIG_IGN);
165 #define UNMASK_SIGNAL() \
166 signal(SIGPIPE, old_handler); \
170 #ifndef __GSOCKET_STANDALONE__
171 # include "wx/unix/gsockunx.h"
172 # include "wx/gsocket.h"
174 # include "gsockunx.h"
175 # include "gsocket.h"
176 #endif /* __GSOCKET_STANDALONE__ */
178 /* debugging helpers */
179 #ifdef __GSOCKET_DEBUG__
180 # define GSocket_Debug(args) printf args
182 # define GSocket_Debug(args)
183 #endif /* __GSOCKET_DEBUG__ */
185 /* Table of GUI-related functions. We must call them indirectly because
186 * of wxBase and GUI separation: */
188 static GSocketGUIFunctionsTable
*gs_gui_functions
;
190 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
193 virtual bool OnInit();
194 virtual void OnExit();
195 virtual bool CanUseEventLoop();
196 virtual bool Init_Socket(GSocket
*socket
);
197 virtual void Destroy_Socket(GSocket
*socket
);
198 virtual void Install_Callback(GSocket
*socket
, GSocketEvent event
);
199 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
200 virtual void Enable_Events(GSocket
*socket
);
201 virtual void Disable_Events(GSocket
*socket
);
204 bool GSocketGUIFunctionsTableNull::OnInit()
206 void GSocketGUIFunctionsTableNull::OnExit()
208 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
210 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*socket
)
212 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*socket
)
214 void GSocketGUIFunctionsTableNull::Install_Callback(GSocket
*socket
, GSocketEvent event
)
216 void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
218 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*socket
)
220 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*socket
)
222 /* Global initialisers */
224 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
226 gs_gui_functions
= guifunc
;
229 int GSocket_Init(void)
231 if (!gs_gui_functions
)
233 static GSocketGUIFunctionsTableNull table
;
234 gs_gui_functions
= &table
;
236 if ( !gs_gui_functions
->OnInit() )
241 void GSocket_Cleanup(void)
243 if (gs_gui_functions
)
245 gs_gui_functions
->OnExit();
249 /* Constructors / Destructors for GSocket */
255 m_fd
= INVALID_SOCKET
;
256 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
263 m_error
= GSOCK_NOERROR
;
266 m_gui_dependent
= NULL
;
267 m_non_blocking
= false;
269 m_timeout
= 10*60*1000;
270 /* 10 minutes * 60 sec * 1000 millisec */
271 m_establishing
= false;
273 assert(gs_gui_functions
);
274 /* Per-socket GUI-specific initialization */
275 m_ok
= gs_gui_functions
->Init_Socket(this);
278 void GSocket::Close()
280 gs_gui_functions
->Disable_Events(this);
281 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
282 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
285 m_fd
= INVALID_SOCKET
;
292 /* Check that the socket is really shutdowned */
293 if (m_fd
!= INVALID_SOCKET
)
296 /* Per-socket GUI-specific cleanup */
297 gs_gui_functions
->Destroy_Socket(this);
299 /* Destroy private addresses */
301 GAddress_destroy(m_local
);
304 GAddress_destroy(m_peer
);
308 * Disallow further read/write operations on this socket, close
309 * the fd and disable all callbacks.
311 void GSocket::Shutdown()
317 /* If socket has been created, shutdown it */
318 if (m_fd
!= INVALID_SOCKET
)
324 /* Disable GUI callbacks */
325 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
326 m_cbacks
[evt
] = NULL
;
328 m_detected
= GSOCK_LOST_FLAG
;
331 /* Address handling */
337 * Set or get the local or peer address for this socket. The 'set'
338 * functions return GSOCK_NOERROR on success, an error code otherwise.
339 * The 'get' functions return a pointer to a GAddress object on success,
340 * or NULL otherwise, in which case they set the error code of the
341 * corresponding GSocket.
344 * GSOCK_INVSOCK - the socket is not valid.
345 * GSOCK_INVADDR - the address is not valid.
347 GSocketError
GSocket::SetLocal(GAddress
*address
)
351 /* the socket must be initialized, or it must be a server */
352 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
354 m_error
= GSOCK_INVSOCK
;
355 return GSOCK_INVSOCK
;
359 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
361 m_error
= GSOCK_INVADDR
;
362 return GSOCK_INVADDR
;
366 GAddress_destroy(m_local
);
368 m_local
= GAddress_copy(address
);
370 return GSOCK_NOERROR
;
373 GSocketError
GSocket::SetPeer(GAddress
*address
)
378 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
380 m_error
= GSOCK_INVADDR
;
381 return GSOCK_INVADDR
;
385 GAddress_destroy(m_peer
);
387 m_peer
= GAddress_copy(address
);
389 return GSOCK_NOERROR
;
392 GAddress
*GSocket::GetLocal()
395 struct sockaddr addr
;
396 SOCKLEN_T size
= sizeof(addr
);
401 /* try to get it from the m_local var first */
403 return GAddress_copy(m_local
);
405 /* else, if the socket is initialized, try getsockname */
406 if (m_fd
== INVALID_SOCKET
)
408 m_error
= GSOCK_INVSOCK
;
412 if (getsockname(m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
414 m_error
= GSOCK_IOERR
;
418 /* got a valid address from getsockname, create a GAddress object */
419 address
= GAddress_new();
422 m_error
= GSOCK_MEMERR
;
426 err
= _GAddress_translate_from(address
, &addr
, size
);
427 if (err
!= GSOCK_NOERROR
)
429 GAddress_destroy(address
);
437 GAddress
*GSocket::GetPeer()
441 /* try to get it from the m_peer var */
443 return GAddress_copy(m_peer
);
448 /* Server specific parts */
450 /* GSocket_SetServer:
451 * Sets up this socket as a server. The local address must have been
452 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
453 * Returns GSOCK_NOERROR on success, one of the following otherwise:
456 * GSOCK_INVSOCK - the socket is in use.
457 * GSOCK_INVADDR - the local address has not been set.
458 * GSOCK_IOERR - low-level error.
460 GSocketError
GSocket::SetServer()
466 /* must not be in use */
467 if (m_fd
!= INVALID_SOCKET
)
469 m_error
= GSOCK_INVSOCK
;
470 return GSOCK_INVSOCK
;
473 /* the local addr must have been set */
476 m_error
= GSOCK_INVADDR
;
477 return GSOCK_INVADDR
;
480 /* Initialize all fields */
484 /* Create the socket */
485 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
487 if (m_fd
== INVALID_SOCKET
)
489 m_error
= GSOCK_IOERR
;
492 ioctl(m_fd
, FIONBIO
, &arg
);
493 gs_gui_functions
->Enable_Events(this);
495 /* allow a socket to re-bind if the socket is in the TIME_WAIT
496 state after being previously closed.
499 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
501 /* Bind to the local address,
502 * retrieve the actual address bound,
503 * and listen up to 5 connections.
505 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
508 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
509 (listen(m_fd
, 5) != 0))
512 m_error
= GSOCK_IOERR
;
516 return GSOCK_NOERROR
;
519 /* GSocket_WaitConnection:
520 * Waits for an incoming client connection. Returns a pointer to
521 * a GSocket object, or NULL if there was an error, in which case
522 * the last error field will be updated for the calling GSocket.
524 * Error codes (set in the calling GSocket)
525 * GSOCK_INVSOCK - the socket is not valid or not a server.
526 * GSOCK_TIMEDOUT - timeout, no incoming connections.
527 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
528 * GSOCK_MEMERR - couldn't allocate memory.
529 * GSOCK_IOERR - low-level error.
531 GSocket
*GSocket::WaitConnection()
533 struct sockaddr from
;
534 SOCKLEN_T fromlen
= sizeof(from
);
541 /* Reenable CONNECTION events */
542 Enable(GSOCK_CONNECTION
);
544 /* If the socket has already been created, we exit immediately */
545 if (m_fd
== INVALID_SOCKET
|| !m_server
)
547 m_error
= GSOCK_INVSOCK
;
551 /* Create a GSocket object for the new connection */
552 connection
= GSocket_new();
556 m_error
= GSOCK_MEMERR
;
560 /* Wait for a connection (with timeout) */
561 if (Input_Timeout() == GSOCK_TIMEDOUT
)
564 /* m_error set by _GSocket_Input_Timeout */
568 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
570 if (connection
->m_fd
== INVALID_SOCKET
)
572 if (errno
== EWOULDBLOCK
)
573 m_error
= GSOCK_WOULDBLOCK
;
575 m_error
= GSOCK_IOERR
;
581 /* Initialize all fields */
582 connection
->m_server
= false;
583 connection
->m_stream
= true;
585 /* Setup the peer address field */
586 connection
->m_peer
= GAddress_new();
587 if (!connection
->m_peer
)
590 m_error
= GSOCK_MEMERR
;
593 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
594 if (err
!= GSOCK_NOERROR
)
600 #if defined(__EMX__) || defined(__VISAGECPP__)
601 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
603 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
605 gs_gui_functions
->Enable_Events(connection
);
610 bool GSocket::SetReusable()
612 /* socket must not be null, and must not be in use/already bound */
613 if (this && m_fd
== INVALID_SOCKET
) {
620 /* Client specific parts */
623 * For stream (connection oriented) sockets, GSocket_Connect() tries
624 * to establish a client connection to a server using the peer address
625 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
626 * connection has been succesfully established, or one of the error
627 * codes listed below. Note that for nonblocking sockets, a return
628 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
629 * request can be completed later; you should use GSocket_Select()
630 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
631 * corresponding asynchronous events.
633 * For datagram (non connection oriented) sockets, GSocket_Connect()
634 * just sets the peer address established with GSocket_SetPeer() as
635 * default destination.
638 * GSOCK_INVSOCK - the socket is in use or not valid.
639 * GSOCK_INVADDR - the peer address has not been established.
640 * GSOCK_TIMEDOUT - timeout, the connection failed.
641 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
642 * GSOCK_MEMERR - couldn't allocate memory.
643 * GSOCK_IOERR - low-level error.
645 GSocketError
GSocket::Connect(GSocketStream stream
)
652 /* Enable CONNECTION events (needed for nonblocking connections) */
653 Enable(GSOCK_CONNECTION
);
655 if (m_fd
!= INVALID_SOCKET
)
657 m_error
= GSOCK_INVSOCK
;
658 return GSOCK_INVSOCK
;
663 m_error
= GSOCK_INVADDR
;
664 return GSOCK_INVADDR
;
667 /* Streamed or dgram socket? */
668 m_stream
= (stream
== GSOCK_STREAMED
);
670 m_establishing
= false;
672 /* Create the socket */
673 m_fd
= socket(m_peer
->m_realfamily
,
674 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
676 if (m_fd
== INVALID_SOCKET
)
678 m_error
= GSOCK_IOERR
;
681 #if defined(__EMX__) || defined(__VISAGECPP__)
682 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
684 ioctl(m_fd
, FIONBIO
, &arg
);
686 gs_gui_functions
->Enable_Events(this);
688 /* Connect it to the peer address, with a timeout (see below) */
689 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
695 /* If connect failed with EINPROGRESS and the GSocket object
696 * is in blocking mode, we select() for the specified timeout
697 * checking for writability to see if the connection request
700 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
702 if (Output_Timeout() == GSOCK_TIMEDOUT
)
705 /* m_error is set in _GSocket_Output_Timeout */
706 return GSOCK_TIMEDOUT
;
711 SOCKOPTLEN_T len
= sizeof(error
);
713 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*) &error
, &len
);
716 return GSOCK_NOERROR
;
720 /* If connect failed with EINPROGRESS and the GSocket object
721 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
722 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
723 * this way if the connection completes, a GSOCK_CONNECTION
724 * event will be generated, if enabled.
726 if ((err
== EINPROGRESS
) && (m_non_blocking
))
728 m_establishing
= true;
729 m_error
= GSOCK_WOULDBLOCK
;
730 return GSOCK_WOULDBLOCK
;
733 /* If connect failed with an error other than EINPROGRESS,
734 * then the call to GSocket_Connect has failed.
737 m_error
= GSOCK_IOERR
;
741 return GSOCK_NOERROR
;
744 /* Datagram sockets */
746 /* GSocket_SetNonOriented:
747 * Sets up this socket as a non-connection oriented (datagram) socket.
748 * Before using this function, the local address must have been set
749 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
750 * on success, or one of the following otherwise.
753 * GSOCK_INVSOCK - the socket is in use.
754 * GSOCK_INVADDR - the local address has not been set.
755 * GSOCK_IOERR - low-level error.
757 GSocketError
GSocket::SetNonOriented()
763 if (m_fd
!= INVALID_SOCKET
)
765 m_error
= GSOCK_INVSOCK
;
766 return GSOCK_INVSOCK
;
771 m_error
= GSOCK_INVADDR
;
772 return GSOCK_INVADDR
;
775 /* Initialize all fields */
779 /* Create the socket */
780 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
782 if (m_fd
== INVALID_SOCKET
)
784 m_error
= GSOCK_IOERR
;
787 #if defined(__EMX__) || defined(__VISAGECPP__)
788 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
790 ioctl(m_fd
, FIONBIO
, &arg
);
792 gs_gui_functions
->Enable_Events(this);
794 /* Bind to the local address,
795 * and retrieve the actual address bound.
797 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
800 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
803 m_error
= GSOCK_IOERR
;
807 return GSOCK_NOERROR
;
812 /* Like recv(), send(), ... */
813 int GSocket::Read(char *buffer
, int size
)
819 if (m_fd
== INVALID_SOCKET
|| m_server
)
821 m_error
= GSOCK_INVSOCK
;
825 /* Disable events during query of socket status */
826 Disable(GSOCK_INPUT
);
828 /* If the socket is blocking, wait for data (with a timeout) */
829 if (Input_Timeout() == GSOCK_TIMEDOUT
)
830 /* We no longer return here immediately, otherwise socket events would not be re-enabled! */
835 ret
= Recv_Stream(buffer
, size
);
837 ret
= Recv_Dgram(buffer
, size
);
842 if (errno
== EWOULDBLOCK
)
843 m_error
= GSOCK_WOULDBLOCK
;
845 m_error
= GSOCK_IOERR
;
848 /* Enable events again now that we are done processing */
854 int GSocket::Write(const char *buffer
, int size
)
860 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
862 if (m_fd
== INVALID_SOCKET
|| m_server
)
864 m_error
= GSOCK_INVSOCK
;
868 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
870 /* If the socket is blocking, wait for writability (with a timeout) */
871 if (Output_Timeout() == GSOCK_TIMEDOUT
)
874 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
878 ret
= Send_Stream(buffer
, size
);
880 ret
= Send_Dgram(buffer
, size
);
882 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
886 if (errno
== EWOULDBLOCK
)
888 m_error
= GSOCK_WOULDBLOCK
;
889 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
893 m_error
= GSOCK_IOERR
;
894 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
897 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
898 * in MSW). Once the first OUTPUT event is received, users can assume
899 * that the socket is writable until a read operation fails. Only then
900 * will further OUTPUT events be posted.
902 Enable(GSOCK_OUTPUT
);
906 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
912 * Polls the socket to determine its status. This function will
913 * check for the events specified in the 'flags' parameter, and
914 * it will return a mask indicating which operations can be
915 * performed. This function won't block, regardless of the
916 * mode (blocking | nonblocking) of the socket.
918 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
920 if (!gs_gui_functions
->CanUseEventLoop())
923 GSocketEventFlags result
= 0;
931 /* Do not use a static struct, Linux can garble it */
932 tv
.tv_sec
= m_timeout
/ 1000;
933 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
938 FD_SET(m_fd
, &readfds
);
939 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
940 FD_SET(m_fd
, &writefds
);
941 FD_SET(m_fd
, &exceptfds
);
943 /* Check 'sticky' CONNECTION flag first */
944 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
946 /* If we have already detected a LOST event, then don't try
947 * to do any further processing.
949 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
951 m_establishing
= false;
953 return (GSOCK_LOST_FLAG
& flags
);
957 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
959 /* What to do here? */
960 return (result
& flags
);
963 /* Check for readability */
964 if (FD_ISSET(m_fd
, &readfds
))
968 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
970 result
|= GSOCK_INPUT_FLAG
;
974 if (m_server
&& m_stream
)
976 result
|= GSOCK_CONNECTION_FLAG
;
977 m_detected
|= GSOCK_CONNECTION_FLAG
;
981 m_detected
= GSOCK_LOST_FLAG
;
982 m_establishing
= false;
984 /* LOST event: Abort any further processing */
985 return (GSOCK_LOST_FLAG
& flags
);
990 /* Check for writability */
991 if (FD_ISSET(m_fd
, &writefds
))
993 if (m_establishing
&& !m_server
)
996 SOCKOPTLEN_T len
= sizeof(error
);
998 m_establishing
= false;
1000 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1004 m_detected
= GSOCK_LOST_FLAG
;
1006 /* LOST event: Abort any further processing */
1007 return (GSOCK_LOST_FLAG
& flags
);
1011 result
|= GSOCK_CONNECTION_FLAG
;
1012 m_detected
|= GSOCK_CONNECTION_FLAG
;
1017 result
|= GSOCK_OUTPUT_FLAG
;
1021 /* Check for exceptions and errors (is this useful in Unices?) */
1022 if (FD_ISSET(m_fd
, &exceptfds
))
1024 m_establishing
= false;
1025 m_detected
= GSOCK_LOST_FLAG
;
1027 /* LOST event: Abort any further processing */
1028 return (GSOCK_LOST_FLAG
& flags
);
1031 return (result
& flags
);
1038 return flags
& m_detected
;
1045 /* GSocket_SetNonBlocking:
1046 * Sets the socket to non-blocking mode. All IO calls will return
1049 void GSocket::SetNonBlocking(bool non_block
)
1053 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1055 m_non_blocking
= non_block
;
1058 /* GSocket_SetTimeout:
1059 * Sets the timeout for blocking calls. Time is expressed in
1062 void GSocket::SetTimeout(unsigned long millisec
)
1066 m_timeout
= millisec
;
1069 /* GSocket_GetError:
1070 * Returns the last error occured for this socket. Note that successful
1071 * operations do not clear this back to GSOCK_NOERROR, so use it only
1074 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1084 * There is data to be read in the input buffer. If, after a read
1085 * operation, there is still data available, the callback function will
1088 * The socket is available for writing. That is, the next write call
1089 * won't block. This event is generated only once, when the connection is
1090 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1091 * when the output buffer empties again. This means that the app should
1092 * assume that it can write since the first OUTPUT event, and no more
1093 * OUTPUT events will be generated unless an error occurs.
1095 * Connection succesfully established, for client sockets, or incoming
1096 * client connection, for server sockets. Wait for this event (also watch
1097 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1099 * The connection is lost (or a connection request failed); this could
1100 * be due to a failure, or due to the peer closing it gracefully.
1103 /* GSocket_SetCallback:
1104 * Enables the callbacks specified by 'flags'. Note that 'flags'
1105 * may be a combination of flags OR'ed toghether, so the same
1106 * callback function can be made to accept different events.
1107 * The callback function must have the following prototype:
1109 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1111 void GSocket::SetCallback(GSocketEventFlags flags
,
1112 GSocketCallback callback
, char *cdata
)
1118 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1120 if ((flags
& (1 << count
)) != 0)
1122 m_cbacks
[count
] = callback
;
1123 m_data
[count
] = cdata
;
1128 /* GSocket_UnsetCallback:
1129 * Disables all callbacks specified by 'flags', which may be a
1130 * combination of flags OR'ed toghether.
1132 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1138 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1140 if ((flags
& (1 << count
)) != 0)
1142 m_cbacks
[count
] = NULL
;
1143 m_data
[count
] = NULL
;
1148 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1149 void *optval
, int *optlen
)
1151 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, (SOCKOPTLEN_T
*)optlen
) == 0)
1153 return GSOCK_NOERROR
;
1155 return GSOCK_OPTERR
;
1158 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1159 const void *optval
, int optlen
)
1161 if (setsockopt(m_fd
, level
, optname
, (const char*)optval
, optlen
) == 0)
1163 return GSOCK_NOERROR
;
1165 return GSOCK_OPTERR
;
1168 #define CALL_CALLBACK(socket, event) { \
1169 socket->Disable(event); \
1170 if (socket->m_cbacks[event]) \
1171 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1175 void GSocket::Enable(GSocketEvent event
)
1177 m_detected
&= ~(1 << event
);
1178 gs_gui_functions
->Install_Callback(this, event
);
1181 void GSocket::Disable(GSocketEvent event
)
1183 m_detected
|= (1 << event
);
1184 gs_gui_functions
->Uninstall_Callback(this, event
);
1187 /* _GSocket_Input_Timeout:
1188 * For blocking sockets, wait until data is available or
1189 * until timeout ellapses.
1191 GSocketError
GSocket::Input_Timeout()
1197 /* Linux select() will overwrite the struct on return */
1198 tv
.tv_sec
= (m_timeout
/ 1000);
1199 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1201 if (!m_non_blocking
)
1204 FD_SET(m_fd
, &readfds
);
1205 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1208 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1209 m_error
= GSOCK_TIMEDOUT
;
1210 return GSOCK_TIMEDOUT
;
1214 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1215 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1216 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1217 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1218 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1219 m_error
= GSOCK_TIMEDOUT
;
1220 return GSOCK_TIMEDOUT
;
1223 return GSOCK_NOERROR
;
1226 /* _GSocket_Output_Timeout:
1227 * For blocking sockets, wait until data can be sent without
1228 * blocking or until timeout ellapses.
1230 GSocketError
GSocket::Output_Timeout()
1236 /* Linux select() will overwrite the struct on return */
1237 tv
.tv_sec
= (m_timeout
/ 1000);
1238 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1240 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1242 if (!m_non_blocking
)
1245 FD_SET(m_fd
, &writefds
);
1246 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1249 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1250 m_error
= GSOCK_TIMEDOUT
;
1251 return GSOCK_TIMEDOUT
;
1255 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1256 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1257 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1258 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1259 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1260 m_error
= GSOCK_TIMEDOUT
;
1261 return GSOCK_TIMEDOUT
;
1263 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1264 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1267 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1272 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1275 return GSOCK_NOERROR
;
1278 int GSocket::Recv_Stream(char *buffer
, int size
)
1280 return recv(m_fd
, buffer
, size
, 0);
1283 int GSocket::Recv_Dgram(char *buffer
, int size
)
1285 struct sockaddr from
;
1286 SOCKLEN_T fromlen
= sizeof(from
);
1290 fromlen
= sizeof(from
);
1292 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1297 /* Translate a system address into a GSocket address */
1300 m_peer
= GAddress_new();
1303 m_error
= GSOCK_MEMERR
;
1307 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1308 if (err
!= GSOCK_NOERROR
)
1310 GAddress_destroy(m_peer
);
1319 int GSocket::Send_Stream(const char *buffer
, int size
)
1323 #ifndef __VISAGECPP__
1325 ret
= send(m_fd
, buffer
, size
, 0);
1328 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1334 int GSocket::Send_Dgram(const char *buffer
, int size
)
1336 struct sockaddr
*addr
;
1342 m_error
= GSOCK_INVADDR
;
1346 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1347 if (err
!= GSOCK_NOERROR
)
1353 #ifndef __VISAGECPP__
1355 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1358 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1361 /* Frees memory allocated from _GAddress_translate_to */
1367 void GSocket::Detected_Read()
1371 /* If we have already detected a LOST event, then don't try
1372 * to do any further processing.
1374 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1376 m_establishing
= false;
1378 CALL_CALLBACK(this, GSOCK_LOST
);
1383 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1385 CALL_CALLBACK(this, GSOCK_INPUT
);
1389 if (m_server
&& m_stream
)
1391 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1395 CALL_CALLBACK(this, GSOCK_LOST
);
1401 void GSocket::Detected_Write()
1403 /* If we have already detected a LOST event, then don't try
1404 * to do any further processing.
1406 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1408 m_establishing
= false;
1410 CALL_CALLBACK(this, GSOCK_LOST
);
1415 if (m_establishing
&& !m_server
)
1418 SOCKOPTLEN_T len
= sizeof(error
);
1420 m_establishing
= false;
1422 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1426 CALL_CALLBACK(this, GSOCK_LOST
);
1431 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1432 /* We have to fire this event by hand because CONNECTION (for clients)
1433 * and OUTPUT are internally the same and we just disabled CONNECTION
1434 * events with the above macro.
1436 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1441 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1445 /* Compatibility functions for GSocket */
1446 GSocket
*GSocket_new(void)
1448 GSocket
*newsocket
= new GSocket();
1449 if(newsocket
->IsOk())
1456 * -------------------------------------------------------------------------
1458 * -------------------------------------------------------------------------
1461 /* CHECK_ADDRESS verifies that the current address family is either
1462 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1463 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1464 * an appropiate error code.
1466 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1468 #define CHECK_ADDRESS(address, family) \
1470 if (address->m_family == GSOCK_NOFAMILY) \
1471 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1472 return address->m_error; \
1473 if (address->m_family != GSOCK_##family) \
1475 address->m_error = GSOCK_INVADDR; \
1476 return GSOCK_INVADDR; \
1480 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1482 if (address->m_family == GSOCK_NOFAMILY) \
1483 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1485 if (address->m_family != GSOCK_##family) \
1487 address->m_error = GSOCK_INVADDR; \
1493 GAddress
*GAddress_new(void)
1497 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1500 address
->m_family
= GSOCK_NOFAMILY
;
1501 address
->m_addr
= NULL
;
1507 GAddress
*GAddress_copy(GAddress
*address
)
1511 assert(address
!= NULL
);
1513 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1516 memcpy(addr2
, address
, sizeof(GAddress
));
1518 if (address
->m_addr
&& address
->m_len
> 0)
1520 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1521 if (addr2
->m_addr
== NULL
)
1526 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1532 void GAddress_destroy(GAddress
*address
)
1534 assert(address
!= NULL
);
1536 if (address
->m_addr
)
1537 free(address
->m_addr
);
1542 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1544 assert(address
!= NULL
);
1546 address
->m_family
= type
;
1549 GAddressType
GAddress_GetFamily(GAddress
*address
)
1551 assert(address
!= NULL
);
1553 return address
->m_family
;
1556 GSocketError
_GAddress_translate_from(GAddress
*address
,
1557 struct sockaddr
*addr
, int len
)
1559 address
->m_realfamily
= addr
->sa_family
;
1560 switch (addr
->sa_family
)
1563 address
->m_family
= GSOCK_INET
;
1566 address
->m_family
= GSOCK_UNIX
;
1570 address
->m_family
= GSOCK_INET6
;
1575 address
->m_error
= GSOCK_INVOP
;
1580 if (address
->m_addr
)
1581 free(address
->m_addr
);
1583 address
->m_len
= len
;
1584 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1586 if (address
->m_addr
== NULL
)
1588 address
->m_error
= GSOCK_MEMERR
;
1589 return GSOCK_MEMERR
;
1591 memcpy(address
->m_addr
, addr
, len
);
1593 return GSOCK_NOERROR
;
1596 GSocketError
_GAddress_translate_to(GAddress
*address
,
1597 struct sockaddr
**addr
, int *len
)
1599 if (!address
->m_addr
)
1601 address
->m_error
= GSOCK_INVADDR
;
1602 return GSOCK_INVADDR
;
1605 *len
= address
->m_len
;
1606 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1609 address
->m_error
= GSOCK_MEMERR
;
1610 return GSOCK_MEMERR
;
1613 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1614 return GSOCK_NOERROR
;
1618 * -------------------------------------------------------------------------
1619 * Internet address family
1620 * -------------------------------------------------------------------------
1623 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1625 address
->m_len
= sizeof(struct sockaddr_in
);
1626 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1627 if (address
->m_addr
== NULL
)
1629 address
->m_error
= GSOCK_MEMERR
;
1630 return GSOCK_MEMERR
;
1633 address
->m_family
= GSOCK_INET
;
1634 address
->m_realfamily
= PF_INET
;
1635 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1636 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1638 return GSOCK_NOERROR
;
1641 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1644 struct in_addr
*addr
;
1646 assert(address
!= NULL
);
1648 CHECK_ADDRESS(address
, INET
);
1650 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1652 /* If it is a numeric host name, convert it now */
1653 #if defined(HAVE_INET_ATON)
1654 if (inet_aton(hostname
, addr
) == 0)
1656 #elif defined(HAVE_INET_ADDR)
1657 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1660 /* Use gethostbyname by default */
1662 int val
= 1; /* VA doesn't like constants in conditional expressions */
1667 struct in_addr
*array_addr
;
1669 /* It is a real name, we solve it */
1670 if ((he
= gethostbyname(hostname
)) == NULL
)
1672 /* Reset to invalid address */
1673 addr
->s_addr
= INADDR_NONE
;
1674 address
->m_error
= GSOCK_NOHOST
;
1675 return GSOCK_NOHOST
;
1677 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1678 addr
->s_addr
= array_addr
[0].s_addr
;
1680 return GSOCK_NOERROR
;
1683 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1685 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1688 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1689 unsigned long hostaddr
)
1691 struct in_addr
*addr
;
1693 assert(address
!= NULL
);
1695 CHECK_ADDRESS(address
, INET
);
1697 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1698 addr
->s_addr
= htonl(hostaddr
);
1700 return GSOCK_NOERROR
;
1703 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1704 const char *protocol
)
1707 struct sockaddr_in
*addr
;
1709 assert(address
!= NULL
);
1710 CHECK_ADDRESS(address
, INET
);
1714 address
->m_error
= GSOCK_INVPORT
;
1715 return GSOCK_INVPORT
;
1718 #if defined(__WXPM__) && defined(__EMX__)
1719 se
= getservbyname(port
, (char*)protocol
);
1721 se
= getservbyname(port
, protocol
);
1725 /* the cast to int suppresses compiler warnings about subscript having the
1727 if (isdigit((int)port
[0]))
1731 port_int
= atoi(port
);
1732 addr
= (struct sockaddr_in
*)address
->m_addr
;
1733 addr
->sin_port
= htons(port_int
);
1734 return GSOCK_NOERROR
;
1737 address
->m_error
= GSOCK_INVPORT
;
1738 return GSOCK_INVPORT
;
1741 addr
= (struct sockaddr_in
*)address
->m_addr
;
1742 addr
->sin_port
= se
->s_port
;
1744 return GSOCK_NOERROR
;
1747 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1749 struct sockaddr_in
*addr
;
1751 assert(address
!= NULL
);
1752 CHECK_ADDRESS(address
, INET
);
1754 addr
= (struct sockaddr_in
*)address
->m_addr
;
1755 addr
->sin_port
= htons(port
);
1757 return GSOCK_NOERROR
;
1760 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1764 struct sockaddr_in
*addr
;
1766 assert(address
!= NULL
);
1767 CHECK_ADDRESS(address
, INET
);
1769 addr
= (struct sockaddr_in
*)address
->m_addr
;
1770 addr_buf
= (char *)&(addr
->sin_addr
);
1772 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1775 address
->m_error
= GSOCK_NOHOST
;
1776 return GSOCK_NOHOST
;
1779 strncpy(hostname
, he
->h_name
, sbuf
);
1781 return GSOCK_NOERROR
;
1784 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1786 struct sockaddr_in
*addr
;
1788 assert(address
!= NULL
);
1789 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1791 addr
= (struct sockaddr_in
*)address
->m_addr
;
1793 return ntohl(addr
->sin_addr
.s_addr
);
1796 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1798 struct sockaddr_in
*addr
;
1800 assert(address
!= NULL
);
1801 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1803 addr
= (struct sockaddr_in
*)address
->m_addr
;
1804 return ntohs(addr
->sin_port
);
1808 * -------------------------------------------------------------------------
1809 * Unix address family
1810 * -------------------------------------------------------------------------
1813 #ifndef __VISAGECPP__
1814 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1816 address
->m_len
= sizeof(struct sockaddr_un
);
1817 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1818 if (address
->m_addr
== NULL
)
1820 address
->m_error
= GSOCK_MEMERR
;
1821 return GSOCK_MEMERR
;
1824 address
->m_family
= GSOCK_UNIX
;
1825 address
->m_realfamily
= PF_UNIX
;
1826 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1827 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1829 return GSOCK_NOERROR
;
1832 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1834 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1836 struct sockaddr_un
*addr
;
1838 assert(address
!= NULL
);
1840 CHECK_ADDRESS(address
, UNIX
);
1842 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1843 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1844 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1846 return GSOCK_NOERROR
;
1849 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1851 struct sockaddr_un
*addr
;
1853 assert(address
!= NULL
);
1854 CHECK_ADDRESS(address
, UNIX
);
1856 addr
= (struct sockaddr_un
*)address
->m_addr
;
1858 strncpy(path
, addr
->sun_path
, sbuf
);
1860 return GSOCK_NOERROR
;
1862 #endif /* !defined(__VISAGECPP__) */
1863 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */