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 #ifndef __GSOCKET_STANDALONE__
173 # include "wx/unix/gsockunx.h"
174 # include "wx/gsocket.h"
176 # include "gsockunx.h"
177 # include "gsocket.h"
178 #endif /* __GSOCKET_STANDALONE__ */
180 /* debugging helpers */
181 #ifdef __GSOCKET_DEBUG__
182 # define GSocket_Debug(args) printf args
184 # define GSocket_Debug(args)
185 #endif /* __GSOCKET_DEBUG__ */
187 /* Table of GUI-related functions. We must call them indirectly because
188 * of wxBase and GUI separation: */
190 static GSocketGUIFunctionsTable
*gs_gui_functions
;
192 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
195 virtual bool OnInit();
196 virtual void OnExit();
197 virtual bool CanUseEventLoop();
198 virtual bool Init_Socket(GSocket
*socket
);
199 virtual void Destroy_Socket(GSocket
*socket
);
200 virtual void Install_Callback(GSocket
*socket
, GSocketEvent event
);
201 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
202 virtual void Enable_Events(GSocket
*socket
);
203 virtual void Disable_Events(GSocket
*socket
);
206 bool GSocketGUIFunctionsTableNull::OnInit()
208 void GSocketGUIFunctionsTableNull::OnExit()
210 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
212 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*socket
)
214 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*socket
)
216 void GSocketGUIFunctionsTableNull::Install_Callback(GSocket
*socket
, GSocketEvent event
)
218 void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
220 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*socket
)
222 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*socket
)
224 /* Global initialisers */
226 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
228 gs_gui_functions
= guifunc
;
231 int GSocket_Init(void)
233 if (!gs_gui_functions
)
235 static GSocketGUIFunctionsTableNull table
;
236 gs_gui_functions
= &table
;
238 if ( !gs_gui_functions
->OnInit() )
243 void GSocket_Cleanup(void)
245 if (gs_gui_functions
)
247 gs_gui_functions
->OnExit();
251 /* Constructors / Destructors for GSocket */
257 m_fd
= INVALID_SOCKET
;
258 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
265 m_error
= GSOCK_NOERROR
;
268 m_gui_dependent
= NULL
;
269 m_non_blocking
= false;
271 m_timeout
= 10*60*1000;
272 /* 10 minutes * 60 sec * 1000 millisec */
273 m_establishing
= false;
275 assert(gs_gui_functions
);
276 /* Per-socket GUI-specific initialization */
277 m_ok
= gs_gui_functions
->Init_Socket(this);
280 void GSocket::Close()
282 gs_gui_functions
->Disable_Events(this);
283 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
284 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
287 m_fd
= INVALID_SOCKET
;
294 /* Check that the socket is really shutdowned */
295 if (m_fd
!= INVALID_SOCKET
)
298 /* Per-socket GUI-specific cleanup */
299 gs_gui_functions
->Destroy_Socket(this);
301 /* Destroy private addresses */
303 GAddress_destroy(m_local
);
306 GAddress_destroy(m_peer
);
310 * Disallow further read/write operations on this socket, close
311 * the fd and disable all callbacks.
313 void GSocket::Shutdown()
319 /* If socket has been created, shutdown it */
320 if (m_fd
!= INVALID_SOCKET
)
326 /* Disable GUI callbacks */
327 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
328 m_cbacks
[evt
] = NULL
;
330 m_detected
= GSOCK_LOST_FLAG
;
333 /* Address handling */
339 * Set or get the local or peer address for this socket. The 'set'
340 * functions return GSOCK_NOERROR on success, an error code otherwise.
341 * The 'get' functions return a pointer to a GAddress object on success,
342 * or NULL otherwise, in which case they set the error code of the
343 * corresponding GSocket.
346 * GSOCK_INVSOCK - the socket is not valid.
347 * GSOCK_INVADDR - the address is not valid.
349 GSocketError
GSocket::SetLocal(GAddress
*address
)
353 /* the socket must be initialized, or it must be a server */
354 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
356 m_error
= GSOCK_INVSOCK
;
357 return GSOCK_INVSOCK
;
361 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
363 m_error
= GSOCK_INVADDR
;
364 return GSOCK_INVADDR
;
368 GAddress_destroy(m_local
);
370 m_local
= GAddress_copy(address
);
372 return GSOCK_NOERROR
;
375 GSocketError
GSocket::SetPeer(GAddress
*address
)
380 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
382 m_error
= GSOCK_INVADDR
;
383 return GSOCK_INVADDR
;
387 GAddress_destroy(m_peer
);
389 m_peer
= GAddress_copy(address
);
391 return GSOCK_NOERROR
;
394 GAddress
*GSocket::GetLocal()
397 struct sockaddr addr
;
398 SOCKLEN_T size
= sizeof(addr
);
403 /* try to get it from the m_local var first */
405 return GAddress_copy(m_local
);
407 /* else, if the socket is initialized, try getsockname */
408 if (m_fd
== INVALID_SOCKET
)
410 m_error
= GSOCK_INVSOCK
;
414 if (getsockname(m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
416 m_error
= GSOCK_IOERR
;
420 /* got a valid address from getsockname, create a GAddress object */
421 address
= GAddress_new();
424 m_error
= GSOCK_MEMERR
;
428 err
= _GAddress_translate_from(address
, &addr
, size
);
429 if (err
!= GSOCK_NOERROR
)
431 GAddress_destroy(address
);
439 GAddress
*GSocket::GetPeer()
443 /* try to get it from the m_peer var */
445 return GAddress_copy(m_peer
);
450 /* Server specific parts */
452 /* GSocket_SetServer:
453 * Sets up this socket as a server. The local address must have been
454 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
455 * Returns GSOCK_NOERROR on success, one of the following otherwise:
458 * GSOCK_INVSOCK - the socket is in use.
459 * GSOCK_INVADDR - the local address has not been set.
460 * GSOCK_IOERR - low-level error.
462 GSocketError
GSocket::SetServer()
468 /* must not be in use */
469 if (m_fd
!= INVALID_SOCKET
)
471 m_error
= GSOCK_INVSOCK
;
472 return GSOCK_INVSOCK
;
475 /* the local addr must have been set */
478 m_error
= GSOCK_INVADDR
;
479 return GSOCK_INVADDR
;
482 /* Initialize all fields */
486 /* Create the socket */
487 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
489 if (m_fd
== INVALID_SOCKET
)
491 m_error
= GSOCK_IOERR
;
494 ioctl(m_fd
, FIONBIO
, &arg
);
495 gs_gui_functions
->Enable_Events(this);
497 /* allow a socket to re-bind if the socket is in the TIME_WAIT
498 state after being previously closed.
501 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
503 /* Bind to the local address,
504 * retrieve the actual address bound,
505 * and listen up to 5 connections.
507 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
510 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
511 (listen(m_fd
, 5) != 0))
514 m_error
= GSOCK_IOERR
;
518 return GSOCK_NOERROR
;
521 /* GSocket_WaitConnection:
522 * Waits for an incoming client connection. Returns a pointer to
523 * a GSocket object, or NULL if there was an error, in which case
524 * the last error field will be updated for the calling GSocket.
526 * Error codes (set in the calling GSocket)
527 * GSOCK_INVSOCK - the socket is not valid or not a server.
528 * GSOCK_TIMEDOUT - timeout, no incoming connections.
529 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
530 * GSOCK_MEMERR - couldn't allocate memory.
531 * GSOCK_IOERR - low-level error.
533 GSocket
*GSocket::WaitConnection()
535 struct sockaddr from
;
536 SOCKLEN_T fromlen
= sizeof(from
);
543 /* Reenable CONNECTION events */
544 Enable(GSOCK_CONNECTION
);
546 /* If the socket has already been created, we exit immediately */
547 if (m_fd
== INVALID_SOCKET
|| !m_server
)
549 m_error
= GSOCK_INVSOCK
;
553 /* Create a GSocket object for the new connection */
554 connection
= GSocket_new();
558 m_error
= GSOCK_MEMERR
;
562 /* Wait for a connection (with timeout) */
563 if (Input_Timeout() == GSOCK_TIMEDOUT
)
566 /* m_error set by _GSocket_Input_Timeout */
570 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
572 if (connection
->m_fd
== INVALID_SOCKET
)
574 if (errno
== EWOULDBLOCK
)
575 m_error
= GSOCK_WOULDBLOCK
;
577 m_error
= GSOCK_IOERR
;
583 /* Initialize all fields */
584 connection
->m_server
= false;
585 connection
->m_stream
= true;
587 /* Setup the peer address field */
588 connection
->m_peer
= GAddress_new();
589 if (!connection
->m_peer
)
592 m_error
= GSOCK_MEMERR
;
595 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
596 if (err
!= GSOCK_NOERROR
)
602 #if defined(__EMX__) || defined(__VISAGECPP__)
603 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
605 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
607 gs_gui_functions
->Enable_Events(connection
);
612 bool GSocket::SetReusable()
614 /* socket must not be null, and must not be in use/already bound */
615 if (this && m_fd
== INVALID_SOCKET
) {
622 /* Client specific parts */
625 * For stream (connection oriented) sockets, GSocket_Connect() tries
626 * to establish a client connection to a server using the peer address
627 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
628 * connection has been succesfully established, or one of the error
629 * codes listed below. Note that for nonblocking sockets, a return
630 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
631 * request can be completed later; you should use GSocket_Select()
632 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
633 * corresponding asynchronous events.
635 * For datagram (non connection oriented) sockets, GSocket_Connect()
636 * just sets the peer address established with GSocket_SetPeer() as
637 * default destination.
640 * GSOCK_INVSOCK - the socket is in use or not valid.
641 * GSOCK_INVADDR - the peer address has not been established.
642 * GSOCK_TIMEDOUT - timeout, the connection failed.
643 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
644 * GSOCK_MEMERR - couldn't allocate memory.
645 * GSOCK_IOERR - low-level error.
647 GSocketError
GSocket::Connect(GSocketStream stream
)
654 /* Enable CONNECTION events (needed for nonblocking connections) */
655 Enable(GSOCK_CONNECTION
);
657 if (m_fd
!= INVALID_SOCKET
)
659 m_error
= GSOCK_INVSOCK
;
660 return GSOCK_INVSOCK
;
665 m_error
= GSOCK_INVADDR
;
666 return GSOCK_INVADDR
;
669 /* Streamed or dgram socket? */
670 m_stream
= (stream
== GSOCK_STREAMED
);
672 m_establishing
= false;
674 /* Create the socket */
675 m_fd
= socket(m_peer
->m_realfamily
,
676 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
678 if (m_fd
== INVALID_SOCKET
)
680 m_error
= GSOCK_IOERR
;
683 #if defined(__EMX__) || defined(__VISAGECPP__)
684 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
686 ioctl(m_fd
, FIONBIO
, &arg
);
688 gs_gui_functions
->Enable_Events(this);
690 /* Connect it to the peer address, with a timeout (see below) */
691 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
697 /* If connect failed with EINPROGRESS and the GSocket object
698 * is in blocking mode, we select() for the specified timeout
699 * checking for writability to see if the connection request
702 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
704 if (Output_Timeout() == GSOCK_TIMEDOUT
)
707 /* m_error is set in _GSocket_Output_Timeout */
708 return GSOCK_TIMEDOUT
;
713 SOCKOPTLEN_T len
= sizeof(error
);
715 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*) &error
, &len
);
718 return GSOCK_NOERROR
;
722 /* If connect failed with EINPROGRESS and the GSocket object
723 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
724 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
725 * this way if the connection completes, a GSOCK_CONNECTION
726 * event will be generated, if enabled.
728 if ((err
== EINPROGRESS
) && (m_non_blocking
))
730 m_establishing
= true;
731 m_error
= GSOCK_WOULDBLOCK
;
732 return GSOCK_WOULDBLOCK
;
735 /* If connect failed with an error other than EINPROGRESS,
736 * then the call to GSocket_Connect has failed.
739 m_error
= GSOCK_IOERR
;
743 return GSOCK_NOERROR
;
746 /* Datagram sockets */
748 /* GSocket_SetNonOriented:
749 * Sets up this socket as a non-connection oriented (datagram) socket.
750 * Before using this function, the local address must have been set
751 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
752 * on success, or one of the following otherwise.
755 * GSOCK_INVSOCK - the socket is in use.
756 * GSOCK_INVADDR - the local address has not been set.
757 * GSOCK_IOERR - low-level error.
759 GSocketError
GSocket::SetNonOriented()
765 if (m_fd
!= INVALID_SOCKET
)
767 m_error
= GSOCK_INVSOCK
;
768 return GSOCK_INVSOCK
;
773 m_error
= GSOCK_INVADDR
;
774 return GSOCK_INVADDR
;
777 /* Initialize all fields */
781 /* Create the socket */
782 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
784 if (m_fd
== INVALID_SOCKET
)
786 m_error
= GSOCK_IOERR
;
789 #if defined(__EMX__) || defined(__VISAGECPP__)
790 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
792 ioctl(m_fd
, FIONBIO
, &arg
);
794 gs_gui_functions
->Enable_Events(this);
796 /* Bind to the local address,
797 * and retrieve the actual address bound.
799 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
802 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
805 m_error
= GSOCK_IOERR
;
809 return GSOCK_NOERROR
;
814 /* Like recv(), send(), ... */
815 int GSocket::Read(char *buffer
, int size
)
821 if (m_fd
== INVALID_SOCKET
|| m_server
)
823 m_error
= GSOCK_INVSOCK
;
827 /* Disable events during query of socket status */
828 Disable(GSOCK_INPUT
);
830 /* If the socket is blocking, wait for data (with a timeout) */
831 if (Input_Timeout() == GSOCK_TIMEDOUT
)
832 /* We no longer return here immediately, otherwise socket events would not be re-enabled! */
837 ret
= Recv_Stream(buffer
, size
);
839 ret
= Recv_Dgram(buffer
, size
);
844 if (errno
== EWOULDBLOCK
)
845 m_error
= GSOCK_WOULDBLOCK
;
847 m_error
= GSOCK_IOERR
;
850 /* Enable events again now that we are done processing */
856 int GSocket::Write(const char *buffer
, int size
)
862 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
864 if (m_fd
== INVALID_SOCKET
|| m_server
)
866 m_error
= GSOCK_INVSOCK
;
870 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
872 /* If the socket is blocking, wait for writability (with a timeout) */
873 if (Output_Timeout() == GSOCK_TIMEDOUT
)
876 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
880 ret
= Send_Stream(buffer
, size
);
882 ret
= Send_Dgram(buffer
, size
);
884 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
888 if (errno
== EWOULDBLOCK
)
890 m_error
= GSOCK_WOULDBLOCK
;
891 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
895 m_error
= GSOCK_IOERR
;
896 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
899 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
900 * in MSW). Once the first OUTPUT event is received, users can assume
901 * that the socket is writable until a read operation fails. Only then
902 * will further OUTPUT events be posted.
904 Enable(GSOCK_OUTPUT
);
908 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
914 * Polls the socket to determine its status. This function will
915 * check for the events specified in the 'flags' parameter, and
916 * it will return a mask indicating which operations can be
917 * performed. This function won't block, regardless of the
918 * mode (blocking | nonblocking) of the socket.
920 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
922 if (!gs_gui_functions
->CanUseEventLoop())
925 GSocketEventFlags result
= 0;
933 /* Do not use a static struct, Linux can garble it */
934 tv
.tv_sec
= m_timeout
/ 1000;
935 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
940 FD_SET(m_fd
, &readfds
);
941 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
942 FD_SET(m_fd
, &writefds
);
943 FD_SET(m_fd
, &exceptfds
);
945 /* Check 'sticky' CONNECTION flag first */
946 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
948 /* If we have already detected a LOST event, then don't try
949 * to do any further processing.
951 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
953 m_establishing
= false;
955 return (GSOCK_LOST_FLAG
& flags
);
959 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
961 /* What to do here? */
962 return (result
& flags
);
965 /* Check for readability */
966 if (FD_ISSET(m_fd
, &readfds
))
970 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
972 result
|= GSOCK_INPUT_FLAG
;
976 if (m_server
&& m_stream
)
978 result
|= GSOCK_CONNECTION_FLAG
;
979 m_detected
|= GSOCK_CONNECTION_FLAG
;
983 m_detected
= GSOCK_LOST_FLAG
;
984 m_establishing
= false;
986 /* LOST event: Abort any further processing */
987 return (GSOCK_LOST_FLAG
& flags
);
992 /* Check for writability */
993 if (FD_ISSET(m_fd
, &writefds
))
995 if (m_establishing
&& !m_server
)
998 SOCKOPTLEN_T len
= sizeof(error
);
1000 m_establishing
= false;
1002 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1006 m_detected
= GSOCK_LOST_FLAG
;
1008 /* LOST event: Abort any further processing */
1009 return (GSOCK_LOST_FLAG
& flags
);
1013 result
|= GSOCK_CONNECTION_FLAG
;
1014 m_detected
|= GSOCK_CONNECTION_FLAG
;
1019 result
|= GSOCK_OUTPUT_FLAG
;
1023 /* Check for exceptions and errors (is this useful in Unices?) */
1024 if (FD_ISSET(m_fd
, &exceptfds
))
1026 m_establishing
= false;
1027 m_detected
= GSOCK_LOST_FLAG
;
1029 /* LOST event: Abort any further processing */
1030 return (GSOCK_LOST_FLAG
& flags
);
1033 return (result
& flags
);
1040 return flags
& m_detected
;
1047 /* GSocket_SetNonBlocking:
1048 * Sets the socket to non-blocking mode. All IO calls will return
1051 void GSocket::SetNonBlocking(bool non_block
)
1055 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1057 m_non_blocking
= non_block
;
1060 /* GSocket_SetTimeout:
1061 * Sets the timeout for blocking calls. Time is expressed in
1064 void GSocket::SetTimeout(unsigned long millisec
)
1068 m_timeout
= millisec
;
1071 /* GSocket_GetError:
1072 * Returns the last error occured for this socket. Note that successful
1073 * operations do not clear this back to GSOCK_NOERROR, so use it only
1076 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1086 * There is data to be read in the input buffer. If, after a read
1087 * operation, there is still data available, the callback function will
1090 * The socket is available for writing. That is, the next write call
1091 * won't block. This event is generated only once, when the connection is
1092 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1093 * when the output buffer empties again. This means that the app should
1094 * assume that it can write since the first OUTPUT event, and no more
1095 * OUTPUT events will be generated unless an error occurs.
1097 * Connection succesfully established, for client sockets, or incoming
1098 * client connection, for server sockets. Wait for this event (also watch
1099 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1101 * The connection is lost (or a connection request failed); this could
1102 * be due to a failure, or due to the peer closing it gracefully.
1105 /* GSocket_SetCallback:
1106 * Enables the callbacks specified by 'flags'. Note that 'flags'
1107 * may be a combination of flags OR'ed toghether, so the same
1108 * callback function can be made to accept different events.
1109 * The callback function must have the following prototype:
1111 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1113 void GSocket::SetCallback(GSocketEventFlags flags
,
1114 GSocketCallback callback
, char *cdata
)
1120 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1122 if ((flags
& (1 << count
)) != 0)
1124 m_cbacks
[count
] = callback
;
1125 m_data
[count
] = cdata
;
1130 /* GSocket_UnsetCallback:
1131 * Disables all callbacks specified by 'flags', which may be a
1132 * combination of flags OR'ed toghether.
1134 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1140 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1142 if ((flags
& (1 << count
)) != 0)
1144 m_cbacks
[count
] = NULL
;
1145 m_data
[count
] = NULL
;
1150 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1151 void *optval
, int *optlen
)
1153 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, (SOCKOPTLEN_T
*)optlen
) == 0)
1155 return GSOCK_NOERROR
;
1157 return GSOCK_OPTERR
;
1160 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1161 const void *optval
, int optlen
)
1163 if (setsockopt(m_fd
, level
, optname
, (const char*)optval
, optlen
) == 0)
1165 return GSOCK_NOERROR
;
1167 return GSOCK_OPTERR
;
1170 #define CALL_CALLBACK(socket, event) { \
1171 socket->Disable(event); \
1172 if (socket->m_cbacks[event]) \
1173 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1177 void GSocket::Enable(GSocketEvent event
)
1179 m_detected
&= ~(1 << event
);
1180 gs_gui_functions
->Install_Callback(this, event
);
1183 void GSocket::Disable(GSocketEvent event
)
1185 m_detected
|= (1 << event
);
1186 gs_gui_functions
->Uninstall_Callback(this, event
);
1189 /* _GSocket_Input_Timeout:
1190 * For blocking sockets, wait until data is available or
1191 * until timeout ellapses.
1193 GSocketError
GSocket::Input_Timeout()
1199 /* Linux select() will overwrite the struct on return */
1200 tv
.tv_sec
= (m_timeout
/ 1000);
1201 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1203 if (!m_non_blocking
)
1206 FD_SET(m_fd
, &readfds
);
1207 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1210 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1211 m_error
= GSOCK_TIMEDOUT
;
1212 return GSOCK_TIMEDOUT
;
1216 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1217 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1218 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1219 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1220 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1221 m_error
= GSOCK_TIMEDOUT
;
1222 return GSOCK_TIMEDOUT
;
1225 return GSOCK_NOERROR
;
1228 /* _GSocket_Output_Timeout:
1229 * For blocking sockets, wait until data can be sent without
1230 * blocking or until timeout ellapses.
1232 GSocketError
GSocket::Output_Timeout()
1238 /* Linux select() will overwrite the struct on return */
1239 tv
.tv_sec
= (m_timeout
/ 1000);
1240 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1242 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1244 if (!m_non_blocking
)
1247 FD_SET(m_fd
, &writefds
);
1248 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1251 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1252 m_error
= GSOCK_TIMEDOUT
;
1253 return GSOCK_TIMEDOUT
;
1257 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1258 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1259 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1260 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1261 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1262 m_error
= GSOCK_TIMEDOUT
;
1263 return GSOCK_TIMEDOUT
;
1265 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1266 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1269 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1274 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1277 return GSOCK_NOERROR
;
1280 int GSocket::Recv_Stream(char *buffer
, int size
)
1282 return recv(m_fd
, buffer
, size
, 0);
1285 int GSocket::Recv_Dgram(char *buffer
, int size
)
1287 struct sockaddr from
;
1288 SOCKLEN_T fromlen
= sizeof(from
);
1292 fromlen
= sizeof(from
);
1294 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1299 /* Translate a system address into a GSocket address */
1302 m_peer
= GAddress_new();
1305 m_error
= GSOCK_MEMERR
;
1309 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1310 if (err
!= GSOCK_NOERROR
)
1312 GAddress_destroy(m_peer
);
1321 int GSocket::Send_Stream(const char *buffer
, int size
)
1325 #ifndef __VISAGECPP__
1327 ret
= send(m_fd
, buffer
, size
, 0);
1330 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1336 int GSocket::Send_Dgram(const char *buffer
, int size
)
1338 struct sockaddr
*addr
;
1344 m_error
= GSOCK_INVADDR
;
1348 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1349 if (err
!= GSOCK_NOERROR
)
1355 #ifndef __VISAGECPP__
1357 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1360 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1363 /* Frees memory allocated from _GAddress_translate_to */
1369 void GSocket::Detected_Read()
1373 /* If we have already detected a LOST event, then don't try
1374 * to do any further processing.
1376 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1378 m_establishing
= false;
1380 CALL_CALLBACK(this, GSOCK_LOST
);
1385 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1387 CALL_CALLBACK(this, GSOCK_INPUT
);
1391 if (m_server
&& m_stream
)
1393 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1397 CALL_CALLBACK(this, GSOCK_LOST
);
1403 void GSocket::Detected_Write()
1405 /* If we have already detected a LOST event, then don't try
1406 * to do any further processing.
1408 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1410 m_establishing
= false;
1412 CALL_CALLBACK(this, GSOCK_LOST
);
1417 if (m_establishing
&& !m_server
)
1420 SOCKOPTLEN_T len
= sizeof(error
);
1422 m_establishing
= false;
1424 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1428 CALL_CALLBACK(this, GSOCK_LOST
);
1433 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1434 /* We have to fire this event by hand because CONNECTION (for clients)
1435 * and OUTPUT are internally the same and we just disabled CONNECTION
1436 * events with the above macro.
1438 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1443 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1447 /* Compatibility functions for GSocket */
1448 GSocket
*GSocket_new(void)
1450 GSocket
*newsocket
= new GSocket();
1451 if(newsocket
->IsOk())
1458 * -------------------------------------------------------------------------
1460 * -------------------------------------------------------------------------
1463 /* CHECK_ADDRESS verifies that the current address family is either
1464 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1465 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1466 * an appropiate error code.
1468 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1470 #define CHECK_ADDRESS(address, family) \
1472 if (address->m_family == GSOCK_NOFAMILY) \
1473 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1474 return address->m_error; \
1475 if (address->m_family != GSOCK_##family) \
1477 address->m_error = GSOCK_INVADDR; \
1478 return GSOCK_INVADDR; \
1482 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1484 if (address->m_family == GSOCK_NOFAMILY) \
1485 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1487 if (address->m_family != GSOCK_##family) \
1489 address->m_error = GSOCK_INVADDR; \
1495 GAddress
*GAddress_new(void)
1499 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1502 address
->m_family
= GSOCK_NOFAMILY
;
1503 address
->m_addr
= NULL
;
1509 GAddress
*GAddress_copy(GAddress
*address
)
1513 assert(address
!= NULL
);
1515 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1518 memcpy(addr2
, address
, sizeof(GAddress
));
1520 if (address
->m_addr
&& address
->m_len
> 0)
1522 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1523 if (addr2
->m_addr
== NULL
)
1528 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1534 void GAddress_destroy(GAddress
*address
)
1536 assert(address
!= NULL
);
1538 if (address
->m_addr
)
1539 free(address
->m_addr
);
1544 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1546 assert(address
!= NULL
);
1548 address
->m_family
= type
;
1551 GAddressType
GAddress_GetFamily(GAddress
*address
)
1553 assert(address
!= NULL
);
1555 return address
->m_family
;
1558 GSocketError
_GAddress_translate_from(GAddress
*address
,
1559 struct sockaddr
*addr
, int len
)
1561 address
->m_realfamily
= addr
->sa_family
;
1562 switch (addr
->sa_family
)
1565 address
->m_family
= GSOCK_INET
;
1568 address
->m_family
= GSOCK_UNIX
;
1572 address
->m_family
= GSOCK_INET6
;
1577 address
->m_error
= GSOCK_INVOP
;
1582 if (address
->m_addr
)
1583 free(address
->m_addr
);
1585 address
->m_len
= len
;
1586 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1588 if (address
->m_addr
== NULL
)
1590 address
->m_error
= GSOCK_MEMERR
;
1591 return GSOCK_MEMERR
;
1593 memcpy(address
->m_addr
, addr
, len
);
1595 return GSOCK_NOERROR
;
1598 GSocketError
_GAddress_translate_to(GAddress
*address
,
1599 struct sockaddr
**addr
, int *len
)
1601 if (!address
->m_addr
)
1603 address
->m_error
= GSOCK_INVADDR
;
1604 return GSOCK_INVADDR
;
1607 *len
= address
->m_len
;
1608 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1611 address
->m_error
= GSOCK_MEMERR
;
1612 return GSOCK_MEMERR
;
1615 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1616 return GSOCK_NOERROR
;
1620 * -------------------------------------------------------------------------
1621 * Internet address family
1622 * -------------------------------------------------------------------------
1625 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1627 address
->m_len
= sizeof(struct sockaddr_in
);
1628 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1629 if (address
->m_addr
== NULL
)
1631 address
->m_error
= GSOCK_MEMERR
;
1632 return GSOCK_MEMERR
;
1635 address
->m_family
= GSOCK_INET
;
1636 address
->m_realfamily
= PF_INET
;
1637 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1638 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1640 return GSOCK_NOERROR
;
1643 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1646 struct in_addr
*addr
;
1648 assert(address
!= NULL
);
1650 CHECK_ADDRESS(address
, INET
);
1652 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1654 /* If it is a numeric host name, convert it now */
1655 #if defined(HAVE_INET_ATON)
1656 if (inet_aton(hostname
, addr
) == 0)
1658 #elif defined(HAVE_INET_ADDR)
1659 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1662 /* Use gethostbyname by default */
1664 int val
= 1; /* VA doesn't like constants in conditional expressions */
1669 struct in_addr
*array_addr
;
1671 /* It is a real name, we solve it */
1672 if ((he
= gethostbyname(hostname
)) == NULL
)
1674 /* Reset to invalid address */
1675 addr
->s_addr
= INADDR_NONE
;
1676 address
->m_error
= GSOCK_NOHOST
;
1677 return GSOCK_NOHOST
;
1679 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1680 addr
->s_addr
= array_addr
[0].s_addr
;
1682 return GSOCK_NOERROR
;
1685 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1687 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1690 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1691 unsigned long hostaddr
)
1693 struct in_addr
*addr
;
1695 assert(address
!= NULL
);
1697 CHECK_ADDRESS(address
, INET
);
1699 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1700 addr
->s_addr
= htonl(hostaddr
);
1702 return GSOCK_NOERROR
;
1705 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1706 const char *protocol
)
1709 struct sockaddr_in
*addr
;
1711 assert(address
!= NULL
);
1712 CHECK_ADDRESS(address
, INET
);
1716 address
->m_error
= GSOCK_INVPORT
;
1717 return GSOCK_INVPORT
;
1720 #if defined(__WXPM__) && defined(__EMX__)
1721 se
= getservbyname(port
, (char*)protocol
);
1723 se
= getservbyname(port
, protocol
);
1727 /* the cast to int suppresses compiler warnings about subscript having the
1729 if (isdigit((int)port
[0]))
1733 port_int
= atoi(port
);
1734 addr
= (struct sockaddr_in
*)address
->m_addr
;
1735 addr
->sin_port
= htons(port_int
);
1736 return GSOCK_NOERROR
;
1739 address
->m_error
= GSOCK_INVPORT
;
1740 return GSOCK_INVPORT
;
1743 addr
= (struct sockaddr_in
*)address
->m_addr
;
1744 addr
->sin_port
= se
->s_port
;
1746 return GSOCK_NOERROR
;
1749 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1751 struct sockaddr_in
*addr
;
1753 assert(address
!= NULL
);
1754 CHECK_ADDRESS(address
, INET
);
1756 addr
= (struct sockaddr_in
*)address
->m_addr
;
1757 addr
->sin_port
= htons(port
);
1759 return GSOCK_NOERROR
;
1762 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1766 struct sockaddr_in
*addr
;
1768 assert(address
!= NULL
);
1769 CHECK_ADDRESS(address
, INET
);
1771 addr
= (struct sockaddr_in
*)address
->m_addr
;
1772 addr_buf
= (char *)&(addr
->sin_addr
);
1774 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1777 address
->m_error
= GSOCK_NOHOST
;
1778 return GSOCK_NOHOST
;
1781 strncpy(hostname
, he
->h_name
, sbuf
);
1783 return GSOCK_NOERROR
;
1786 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1788 struct sockaddr_in
*addr
;
1790 assert(address
!= NULL
);
1791 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1793 addr
= (struct sockaddr_in
*)address
->m_addr
;
1795 return ntohl(addr
->sin_addr
.s_addr
);
1798 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1800 struct sockaddr_in
*addr
;
1802 assert(address
!= NULL
);
1803 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1805 addr
= (struct sockaddr_in
*)address
->m_addr
;
1806 return ntohs(addr
->sin_port
);
1810 * -------------------------------------------------------------------------
1811 * Unix address family
1812 * -------------------------------------------------------------------------
1815 #ifndef __VISAGECPP__
1816 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1818 address
->m_len
= sizeof(struct sockaddr_un
);
1819 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1820 if (address
->m_addr
== NULL
)
1822 address
->m_error
= GSOCK_MEMERR
;
1823 return GSOCK_MEMERR
;
1826 address
->m_family
= GSOCK_UNIX
;
1827 address
->m_realfamily
= PF_UNIX
;
1828 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1829 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1831 return GSOCK_NOERROR
;
1834 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1836 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1838 struct sockaddr_un
*addr
;
1840 assert(address
!= NULL
);
1842 CHECK_ADDRESS(address
, UNIX
);
1844 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1845 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1846 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1848 return GSOCK_NOERROR
;
1851 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1853 struct sockaddr_un
*addr
;
1855 assert(address
!= NULL
);
1856 CHECK_ADDRESS(address
, UNIX
);
1858 addr
= (struct sockaddr_un
*)address
->m_addr
;
1860 strncpy(path
, addr
->sun_path
, sbuf
);
1862 return GSOCK_NOERROR
;
1864 #endif /* !defined(__VISAGECPP__) */
1865 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */