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
120 #endif /* SOCKLEN_T */
123 * MSW defines this, Unices don't.
125 #ifndef INVALID_SOCKET
126 #define INVALID_SOCKET -1
129 /* UnixWare reportedly needs this for FIONBIO definition */
131 #include <sys/filio.h>
135 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
136 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
139 #define INADDR_NONE INADDR_BROADCAST
142 #define MASK_SIGNAL() \
144 void (*old_handler)(int); \
146 old_handler = signal(SIGPIPE, SIG_IGN);
148 #define UNMASK_SIGNAL() \
149 signal(SIGPIPE, old_handler); \
153 #ifndef __GSOCKET_STANDALONE__
154 # include "wx/unix/gsockunx.h"
155 # include "wx/gsocket.h"
157 # include "gsockunx.h"
158 # include "gsocket.h"
159 #endif /* __GSOCKET_STANDALONE__ */
161 /* debugging helpers */
162 #ifdef __GSOCKET_DEBUG__
163 # define GSocket_Debug(args) printf args
165 # define GSocket_Debug(args)
166 #endif /* __GSOCKET_DEBUG__ */
168 /* Table of GUI-related functions. We must call them indirectly because
169 * of wxBase and GUI separation: */
171 static GSocketGUIFunctionsTable
*gs_gui_functions
;
173 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
176 virtual bool OnInit();
177 virtual void OnExit();
178 virtual bool CanUseEventLoop();
179 virtual bool Init_Socket(GSocket
*socket
);
180 virtual void Destroy_Socket(GSocket
*socket
);
181 virtual void Install_Callback(GSocket
*socket
, GSocketEvent event
);
182 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
183 virtual void Enable_Events(GSocket
*socket
);
184 virtual void Disable_Events(GSocket
*socket
);
187 bool GSocketGUIFunctionsTableNull::OnInit()
189 void GSocketGUIFunctionsTableNull::OnExit()
191 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
193 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*socket
)
195 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*socket
)
197 void GSocketGUIFunctionsTableNull::Install_Callback(GSocket
*socket
, GSocketEvent event
)
199 void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
201 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*socket
)
203 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*socket
)
205 /* Global initialisers */
207 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
209 gs_gui_functions
= guifunc
;
212 int GSocket_Init(void)
214 if (!gs_gui_functions
)
216 static GSocketGUIFunctionsTableNull table
;
217 gs_gui_functions
= &table
;
219 if ( !gs_gui_functions
->OnInit() )
224 void GSocket_Cleanup(void)
226 if (gs_gui_functions
)
228 gs_gui_functions
->OnExit();
232 /* Constructors / Destructors for GSocket */
238 m_fd
= INVALID_SOCKET
;
239 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
246 m_error
= GSOCK_NOERROR
;
249 m_gui_dependent
= NULL
;
250 m_non_blocking
= false;
251 m_timeout
= 10*60*1000;
252 /* 10 minutes * 60 sec * 1000 millisec */
253 m_establishing
= false;
255 assert(gs_gui_functions
);
256 /* Per-socket GUI-specific initialization */
257 m_ok
= gs_gui_functions
->Init_Socket(this);
260 void GSocket::Close()
262 gs_gui_functions
->Disable_Events(this);
263 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
264 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
267 m_fd
= INVALID_SOCKET
;
274 /* Check that the socket is really shutdowned */
275 if (m_fd
!= INVALID_SOCKET
)
278 /* Per-socket GUI-specific cleanup */
279 gs_gui_functions
->Destroy_Socket(this);
281 /* Destroy private addresses */
283 GAddress_destroy(m_local
);
286 GAddress_destroy(m_peer
);
290 * Disallow further read/write operations on this socket, close
291 * the fd and disable all callbacks.
293 void GSocket::Shutdown()
299 /* If socket has been created, shutdown it */
300 if (m_fd
!= INVALID_SOCKET
)
306 /* Disable GUI callbacks */
307 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
308 m_cbacks
[evt
] = NULL
;
310 m_detected
= GSOCK_LOST_FLAG
;
313 /* Address handling */
319 * Set or get the local or peer address for this socket. The 'set'
320 * functions return GSOCK_NOERROR on success, an error code otherwise.
321 * The 'get' functions return a pointer to a GAddress object on success,
322 * or NULL otherwise, in which case they set the error code of the
323 * corresponding GSocket.
326 * GSOCK_INVSOCK - the socket is not valid.
327 * GSOCK_INVADDR - the address is not valid.
329 GSocketError
GSocket::SetLocal(GAddress
*address
)
333 /* the socket must be initialized, or it must be a server */
334 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
336 m_error
= GSOCK_INVSOCK
;
337 return GSOCK_INVSOCK
;
341 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
343 m_error
= GSOCK_INVADDR
;
344 return GSOCK_INVADDR
;
348 GAddress_destroy(m_local
);
350 m_local
= GAddress_copy(address
);
352 return GSOCK_NOERROR
;
355 GSocketError
GSocket::SetPeer(GAddress
*address
)
360 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
362 m_error
= GSOCK_INVADDR
;
363 return GSOCK_INVADDR
;
367 GAddress_destroy(m_peer
);
369 m_peer
= GAddress_copy(address
);
371 return GSOCK_NOERROR
;
374 GAddress
*GSocket::GetLocal()
377 struct sockaddr addr
;
378 SOCKLEN_T size
= sizeof(addr
);
383 /* try to get it from the m_local var first */
385 return GAddress_copy(m_local
);
387 /* else, if the socket is initialized, try getsockname */
388 if (m_fd
== INVALID_SOCKET
)
390 m_error
= GSOCK_INVSOCK
;
394 if (getsockname(m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
396 m_error
= GSOCK_IOERR
;
400 /* got a valid address from getsockname, create a GAddress object */
401 address
= GAddress_new();
404 m_error
= GSOCK_MEMERR
;
408 err
= _GAddress_translate_from(address
, &addr
, size
);
409 if (err
!= GSOCK_NOERROR
)
411 GAddress_destroy(address
);
419 GAddress
*GSocket::GetPeer()
423 /* try to get it from the m_peer var */
425 return GAddress_copy(m_peer
);
430 /* Server specific parts */
432 /* GSocket_SetServer:
433 * Sets up this socket as a server. The local address must have been
434 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
435 * Returns GSOCK_NOERROR on success, one of the following otherwise:
438 * GSOCK_INVSOCK - the socket is in use.
439 * GSOCK_INVADDR - the local address has not been set.
440 * GSOCK_IOERR - low-level error.
442 GSocketError
GSocket::SetServer()
448 /* must not be in use */
449 if (m_fd
!= INVALID_SOCKET
)
451 m_error
= GSOCK_INVSOCK
;
452 return GSOCK_INVSOCK
;
455 /* the local addr must have been set */
458 m_error
= GSOCK_INVADDR
;
459 return GSOCK_INVADDR
;
462 /* Initialize all fields */
466 /* Create the socket */
467 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
469 if (m_fd
== INVALID_SOCKET
)
471 m_error
= GSOCK_IOERR
;
474 #if defined(__EMX__) || defined(__VISAGECPP__)
475 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
477 ioctl(m_fd
, FIONBIO
, &arg
);
479 gs_gui_functions
->Enable_Events(this);
481 /* allow a socket to re-bind if the socket is in the TIME_WAIT
482 state after being previously closed.
485 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
487 /* Bind to the local address,
488 * retrieve the actual address bound,
489 * and listen up to 5 connections.
491 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
494 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
495 (listen(m_fd
, 5) != 0))
498 m_error
= GSOCK_IOERR
;
502 return GSOCK_NOERROR
;
505 /* GSocket_WaitConnection:
506 * Waits for an incoming client connection. Returns a pointer to
507 * a GSocket object, or NULL if there was an error, in which case
508 * the last error field will be updated for the calling GSocket.
510 * Error codes (set in the calling GSocket)
511 * GSOCK_INVSOCK - the socket is not valid or not a server.
512 * GSOCK_TIMEDOUT - timeout, no incoming connections.
513 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
514 * GSOCK_MEMERR - couldn't allocate memory.
515 * GSOCK_IOERR - low-level error.
517 GSocket
*GSocket::WaitConnection()
519 struct sockaddr from
;
520 SOCKLEN_T fromlen
= sizeof(from
);
527 /* Reenable CONNECTION events */
528 Enable(GSOCK_CONNECTION
);
530 /* If the socket has already been created, we exit immediately */
531 if (m_fd
== INVALID_SOCKET
|| !m_server
)
533 m_error
= GSOCK_INVSOCK
;
537 /* Create a GSocket object for the new connection */
538 connection
= GSocket_new();
542 m_error
= GSOCK_MEMERR
;
546 /* Wait for a connection (with timeout) */
547 if (Input_Timeout() == GSOCK_TIMEDOUT
)
550 /* m_error set by _GSocket_Input_Timeout */
554 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
556 if (connection
->m_fd
== INVALID_SOCKET
)
558 if (errno
== EWOULDBLOCK
)
559 m_error
= GSOCK_WOULDBLOCK
;
561 m_error
= GSOCK_IOERR
;
567 /* Initialize all fields */
568 connection
->m_server
= false;
569 connection
->m_stream
= true;
571 /* Setup the peer address field */
572 connection
->m_peer
= GAddress_new();
573 if (!connection
->m_peer
)
576 m_error
= GSOCK_MEMERR
;
579 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
580 if (err
!= GSOCK_NOERROR
)
582 GAddress_destroy(connection
->m_peer
);
587 #if defined(__EMX__) || defined(__VISAGECPP__)
588 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
590 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
592 gs_gui_functions
->Enable_Events(connection
);
597 bool GSocket::SetReusable()
599 /* socket must not be null, and must not be in use/already bound */
600 if (this && m_fd
== INVALID_SOCKET
) {
607 /* Client specific parts */
610 * For stream (connection oriented) sockets, GSocket_Connect() tries
611 * to establish a client connection to a server using the peer address
612 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
613 * connection has been succesfully established, or one of the error
614 * codes listed below. Note that for nonblocking sockets, a return
615 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
616 * request can be completed later; you should use GSocket_Select()
617 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
618 * corresponding asynchronous events.
620 * For datagram (non connection oriented) sockets, GSocket_Connect()
621 * just sets the peer address established with GSocket_SetPeer() as
622 * default destination.
625 * GSOCK_INVSOCK - the socket is in use or not valid.
626 * GSOCK_INVADDR - the peer address has not been established.
627 * GSOCK_TIMEDOUT - timeout, the connection failed.
628 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
629 * GSOCK_MEMERR - couldn't allocate memory.
630 * GSOCK_IOERR - low-level error.
632 GSocketError
GSocket::Connect(GSocketStream stream
)
639 /* Enable CONNECTION events (needed for nonblocking connections) */
640 Enable(GSOCK_CONNECTION
);
642 if (m_fd
!= INVALID_SOCKET
)
644 m_error
= GSOCK_INVSOCK
;
645 return GSOCK_INVSOCK
;
650 m_error
= GSOCK_INVADDR
;
651 return GSOCK_INVADDR
;
654 /* Streamed or dgram socket? */
655 m_stream
= (stream
== GSOCK_STREAMED
);
657 m_establishing
= false;
659 /* Create the socket */
660 m_fd
= socket(m_peer
->m_realfamily
,
661 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
663 if (m_fd
== INVALID_SOCKET
)
665 m_error
= GSOCK_IOERR
;
668 #if defined(__EMX__) || defined(__VISAGECPP__)
669 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
671 ioctl(m_fd
, FIONBIO
, &arg
);
673 gs_gui_functions
->Enable_Events(this);
675 /* Connect it to the peer address, with a timeout (see below) */
676 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
682 /* If connect failed with EINPROGRESS and the GSocket object
683 * is in blocking mode, we select() for the specified timeout
684 * checking for writability to see if the connection request
687 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
689 if (Output_Timeout() == GSOCK_TIMEDOUT
)
692 /* m_error is set in _GSocket_Output_Timeout */
693 return GSOCK_TIMEDOUT
;
698 SOCKLEN_T len
= sizeof(error
);
700 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
703 return GSOCK_NOERROR
;
707 /* If connect failed with EINPROGRESS and the GSocket object
708 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
709 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
710 * this way if the connection completes, a GSOCK_CONNECTION
711 * event will be generated, if enabled.
713 if ((err
== EINPROGRESS
) && (m_non_blocking
))
715 m_establishing
= true;
716 m_error
= GSOCK_WOULDBLOCK
;
717 return GSOCK_WOULDBLOCK
;
720 /* If connect failed with an error other than EINPROGRESS,
721 * then the call to GSocket_Connect has failed.
724 m_error
= GSOCK_IOERR
;
728 return GSOCK_NOERROR
;
731 /* Datagram sockets */
733 /* GSocket_SetNonOriented:
734 * Sets up this socket as a non-connection oriented (datagram) socket.
735 * Before using this function, the local address must have been set
736 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
737 * on success, or one of the following otherwise.
740 * GSOCK_INVSOCK - the socket is in use.
741 * GSOCK_INVADDR - the local address has not been set.
742 * GSOCK_IOERR - low-level error.
744 GSocketError
GSocket::SetNonOriented()
750 if (m_fd
!= INVALID_SOCKET
)
752 m_error
= GSOCK_INVSOCK
;
753 return GSOCK_INVSOCK
;
758 m_error
= GSOCK_INVADDR
;
759 return GSOCK_INVADDR
;
762 /* Initialize all fields */
766 /* Create the socket */
767 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
769 if (m_fd
== INVALID_SOCKET
)
771 m_error
= GSOCK_IOERR
;
774 #if defined(__EMX__) || defined(__VISAGECPP__)
775 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
777 ioctl(m_fd
, FIONBIO
, &arg
);
779 gs_gui_functions
->Enable_Events(this);
781 /* Bind to the local address,
782 * and retrieve the actual address bound.
784 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
787 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
790 m_error
= GSOCK_IOERR
;
794 return GSOCK_NOERROR
;
799 /* Like recv(), send(), ... */
800 int GSocket::Read(char *buffer
, int size
)
806 if (m_fd
== INVALID_SOCKET
|| m_server
)
808 m_error
= GSOCK_INVSOCK
;
812 /* Disable events during query of socket status */
813 Disable(GSOCK_INPUT
);
815 /* If the socket is blocking, wait for data (with a timeout) */
816 if (Input_Timeout() == GSOCK_TIMEDOUT
)
817 /* We no longer return here immediately, otherwise socket events would not be re-enabled! */
822 ret
= Recv_Stream(buffer
, size
);
824 ret
= Recv_Dgram(buffer
, size
);
829 if (errno
== EWOULDBLOCK
)
830 m_error
= GSOCK_WOULDBLOCK
;
832 m_error
= GSOCK_IOERR
;
835 /* Enable events again now that we are done processing */
841 int GSocket::Write(const char *buffer
, int size
)
847 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
849 if (m_fd
== INVALID_SOCKET
|| m_server
)
851 m_error
= GSOCK_INVSOCK
;
855 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
857 /* If the socket is blocking, wait for writability (with a timeout) */
858 if (Output_Timeout() == GSOCK_TIMEDOUT
)
861 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
865 ret
= Send_Stream(buffer
, size
);
867 ret
= Send_Dgram(buffer
, size
);
869 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
873 if (errno
== EWOULDBLOCK
)
875 m_error
= GSOCK_WOULDBLOCK
;
876 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
880 m_error
= GSOCK_IOERR
;
881 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
884 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
885 * in MSW). Once the first OUTPUT event is received, users can assume
886 * that the socket is writable until a read operation fails. Only then
887 * will further OUTPUT events be posted.
889 Enable(GSOCK_OUTPUT
);
893 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
899 * Polls the socket to determine its status. This function will
900 * check for the events specified in the 'flags' parameter, and
901 * it will return a mask indicating which operations can be
902 * performed. This function won't block, regardless of the
903 * mode (blocking | nonblocking) of the socket.
905 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
907 if (!gs_gui_functions
->CanUseEventLoop())
910 GSocketEventFlags result
= 0;
918 /* Do not use a static struct, Linux can garble it */
919 tv
.tv_sec
= m_timeout
/ 1000;
920 tv
.tv_usec
= (m_timeout
% 1000) / 1000;
925 FD_SET(m_fd
, &readfds
);
926 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
927 FD_SET(m_fd
, &writefds
);
928 FD_SET(m_fd
, &exceptfds
);
930 /* Check 'sticky' CONNECTION flag first */
931 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
933 /* If we have already detected a LOST event, then don't try
934 * to do any further processing.
936 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
938 m_establishing
= false;
940 return (GSOCK_LOST_FLAG
& flags
);
944 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
946 /* What to do here? */
947 return (result
& flags
);
950 /* Check for readability */
951 if (FD_ISSET(m_fd
, &readfds
))
955 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
957 result
|= GSOCK_INPUT_FLAG
;
961 if (m_server
&& m_stream
)
963 result
|= GSOCK_CONNECTION_FLAG
;
964 m_detected
|= GSOCK_CONNECTION_FLAG
;
968 m_detected
= GSOCK_LOST_FLAG
;
969 m_establishing
= false;
971 /* LOST event: Abort any further processing */
972 return (GSOCK_LOST_FLAG
& flags
);
977 /* Check for writability */
978 if (FD_ISSET(m_fd
, &writefds
))
980 if (m_establishing
&& !m_server
)
983 SOCKLEN_T len
= sizeof(error
);
985 m_establishing
= false;
987 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
991 m_detected
= GSOCK_LOST_FLAG
;
993 /* LOST event: Abort any further processing */
994 return (GSOCK_LOST_FLAG
& flags
);
998 result
|= GSOCK_CONNECTION_FLAG
;
999 m_detected
|= GSOCK_CONNECTION_FLAG
;
1004 result
|= GSOCK_OUTPUT_FLAG
;
1008 /* Check for exceptions and errors (is this useful in Unices?) */
1009 if (FD_ISSET(m_fd
, &exceptfds
))
1011 m_establishing
= false;
1012 m_detected
= GSOCK_LOST_FLAG
;
1014 /* LOST event: Abort any further processing */
1015 return (GSOCK_LOST_FLAG
& flags
);
1018 return (result
& flags
);
1025 return flags
& m_detected
;
1032 /* GSocket_SetNonBlocking:
1033 * Sets the socket to non-blocking mode. All IO calls will return
1036 void GSocket::SetNonBlocking(bool non_block
)
1040 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1042 m_non_blocking
= non_block
;
1045 /* GSocket_SetTimeout:
1046 * Sets the timeout for blocking calls. Time is expressed in
1049 void GSocket::SetTimeout(unsigned long millisec
)
1053 m_timeout
= millisec
;
1056 /* GSocket_GetError:
1057 * Returns the last error occured for this socket. Note that successful
1058 * operations do not clear this back to GSOCK_NOERROR, so use it only
1061 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1071 * There is data to be read in the input buffer. If, after a read
1072 * operation, there is still data available, the callback function will
1075 * The socket is available for writing. That is, the next write call
1076 * won't block. This event is generated only once, when the connection is
1077 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1078 * when the output buffer empties again. This means that the app should
1079 * assume that it can write since the first OUTPUT event, and no more
1080 * OUTPUT events will be generated unless an error occurs.
1082 * Connection succesfully established, for client sockets, or incoming
1083 * client connection, for server sockets. Wait for this event (also watch
1084 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1086 * The connection is lost (or a connection request failed); this could
1087 * be due to a failure, or due to the peer closing it gracefully.
1090 /* GSocket_SetCallback:
1091 * Enables the callbacks specified by 'flags'. Note that 'flags'
1092 * may be a combination of flags OR'ed toghether, so the same
1093 * callback function can be made to accept different events.
1094 * The callback function must have the following prototype:
1096 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1098 void GSocket::SetCallback(GSocketEventFlags flags
,
1099 GSocketCallback callback
, char *cdata
)
1105 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1107 if ((flags
& (1 << count
)) != 0)
1109 m_cbacks
[count
] = callback
;
1110 m_data
[count
] = cdata
;
1115 /* GSocket_UnsetCallback:
1116 * Disables all callbacks specified by 'flags', which may be a
1117 * combination of flags OR'ed toghether.
1119 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1125 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1127 if ((flags
& (1 << count
)) != 0)
1129 m_cbacks
[count
] = NULL
;
1130 m_data
[count
] = NULL
;
1135 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1136 void *optval
, int *optlen
)
1138 if (getsockopt(m_fd
, level
, optname
, optval
, (SOCKLEN_T
*)optlen
) == 0)
1140 return GSOCK_NOERROR
;
1142 return GSOCK_OPTERR
;
1145 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1146 const void *optval
, int optlen
)
1148 if (setsockopt(m_fd
, level
, optname
, optval
, optlen
) == 0)
1150 return GSOCK_NOERROR
;
1152 return GSOCK_OPTERR
;
1155 #define CALL_CALLBACK(socket, event) { \
1156 socket->Disable(event); \
1157 if (socket->m_cbacks[event]) \
1158 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1162 void GSocket::Enable(GSocketEvent event
)
1164 m_detected
&= ~(1 << event
);
1165 gs_gui_functions
->Install_Callback(this, event
);
1168 void GSocket::Disable(GSocketEvent event
)
1170 m_detected
|= (1 << event
);
1171 gs_gui_functions
->Uninstall_Callback(this, event
);
1174 /* _GSocket_Input_Timeout:
1175 * For blocking sockets, wait until data is available or
1176 * until timeout ellapses.
1178 GSocketError
GSocket::Input_Timeout()
1184 /* Linux select() will overwrite the struct on return */
1185 tv
.tv_sec
= (m_timeout
/ 1000);
1186 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1188 if (!m_non_blocking
)
1191 FD_SET(m_fd
, &readfds
);
1192 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1195 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1196 m_error
= GSOCK_TIMEDOUT
;
1197 return GSOCK_TIMEDOUT
;
1201 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1202 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1203 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1204 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1205 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1206 m_error
= GSOCK_TIMEDOUT
;
1207 return GSOCK_TIMEDOUT
;
1210 return GSOCK_NOERROR
;
1213 /* _GSocket_Output_Timeout:
1214 * For blocking sockets, wait until data can be sent without
1215 * blocking or until timeout ellapses.
1217 GSocketError
GSocket::Output_Timeout()
1223 /* Linux select() will overwrite the struct on return */
1224 tv
.tv_sec
= (m_timeout
/ 1000);
1225 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1227 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1229 if (!m_non_blocking
)
1232 FD_SET(m_fd
, &writefds
);
1233 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1236 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1237 m_error
= GSOCK_TIMEDOUT
;
1238 return GSOCK_TIMEDOUT
;
1242 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1243 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1244 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1245 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1246 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1247 m_error
= GSOCK_TIMEDOUT
;
1248 return GSOCK_TIMEDOUT
;
1250 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1251 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1254 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1259 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1262 return GSOCK_NOERROR
;
1265 int GSocket::Recv_Stream(char *buffer
, int size
)
1267 return recv(m_fd
, buffer
, size
, 0);
1270 int GSocket::Recv_Dgram(char *buffer
, int size
)
1272 struct sockaddr from
;
1273 SOCKLEN_T fromlen
= sizeof(from
);
1277 fromlen
= sizeof(from
);
1279 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1284 /* Translate a system address into a GSocket address */
1287 m_peer
= GAddress_new();
1290 m_error
= GSOCK_MEMERR
;
1294 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1295 if (err
!= GSOCK_NOERROR
)
1297 GAddress_destroy(m_peer
);
1306 int GSocket::Send_Stream(const char *buffer
, int size
)
1310 #ifndef __VISAGECPP__
1312 ret
= send(m_fd
, buffer
, size
, 0);
1315 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1321 int GSocket::Send_Dgram(const char *buffer
, int size
)
1323 struct sockaddr
*addr
;
1329 m_error
= GSOCK_INVADDR
;
1333 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1334 if (err
!= GSOCK_NOERROR
)
1340 #ifndef __VISAGECPP__
1342 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1345 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1348 /* Frees memory allocated from _GAddress_translate_to */
1354 void GSocket::Detected_Read()
1358 /* If we have already detected a LOST event, then don't try
1359 * to do any further processing.
1361 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1363 m_establishing
= false;
1365 CALL_CALLBACK(this, GSOCK_LOST
);
1370 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1372 CALL_CALLBACK(this, GSOCK_INPUT
);
1376 if (m_server
&& m_stream
)
1378 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1382 CALL_CALLBACK(this, GSOCK_LOST
);
1388 void GSocket::Detected_Write()
1390 /* If we have already detected a LOST event, then don't try
1391 * to do any further processing.
1393 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1395 m_establishing
= false;
1397 CALL_CALLBACK(this, GSOCK_LOST
);
1402 if (m_establishing
&& !m_server
)
1405 SOCKLEN_T len
= sizeof(error
);
1407 m_establishing
= false;
1409 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1413 CALL_CALLBACK(this, GSOCK_LOST
);
1418 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1419 /* We have to fire this event by hand because CONNECTION (for clients)
1420 * and OUTPUT are internally the same and we just disabled CONNECTION
1421 * events with the above macro.
1423 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1428 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1432 /* Compatibility functions for GSocket */
1433 GSocket
*GSocket_new(void)
1435 GSocket
*newsocket
= new GSocket();
1436 if(newsocket
->IsOk())
1443 * -------------------------------------------------------------------------
1445 * -------------------------------------------------------------------------
1448 /* CHECK_ADDRESS verifies that the current address family is either
1449 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1450 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1451 * an appropiate error code.
1453 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1455 #define CHECK_ADDRESS(address, family) \
1457 if (address->m_family == GSOCK_NOFAMILY) \
1458 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1459 return address->m_error; \
1460 if (address->m_family != GSOCK_##family) \
1462 address->m_error = GSOCK_INVADDR; \
1463 return GSOCK_INVADDR; \
1467 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1469 if (address->m_family == GSOCK_NOFAMILY) \
1470 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1472 if (address->m_family != GSOCK_##family) \
1474 address->m_error = GSOCK_INVADDR; \
1480 GAddress
*GAddress_new(void)
1484 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1487 address
->m_family
= GSOCK_NOFAMILY
;
1488 address
->m_addr
= NULL
;
1494 GAddress
*GAddress_copy(GAddress
*address
)
1498 assert(address
!= NULL
);
1500 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1503 memcpy(addr2
, address
, sizeof(GAddress
));
1505 if (address
->m_addr
&& address
->m_len
> 0)
1507 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1508 if (addr2
->m_addr
== NULL
)
1513 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1519 void GAddress_destroy(GAddress
*address
)
1521 assert(address
!= NULL
);
1523 if (address
->m_addr
)
1524 free(address
->m_addr
);
1529 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1531 assert(address
!= NULL
);
1533 address
->m_family
= type
;
1536 GAddressType
GAddress_GetFamily(GAddress
*address
)
1538 assert(address
!= NULL
);
1540 return address
->m_family
;
1543 GSocketError
_GAddress_translate_from(GAddress
*address
,
1544 struct sockaddr
*addr
, int len
)
1546 address
->m_realfamily
= addr
->sa_family
;
1547 switch (addr
->sa_family
)
1550 address
->m_family
= GSOCK_INET
;
1553 address
->m_family
= GSOCK_UNIX
;
1557 address
->m_family
= GSOCK_INET6
;
1562 address
->m_error
= GSOCK_INVOP
;
1567 if (address
->m_addr
)
1568 free(address
->m_addr
);
1570 address
->m_len
= len
;
1571 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1573 if (address
->m_addr
== NULL
)
1575 address
->m_error
= GSOCK_MEMERR
;
1576 return GSOCK_MEMERR
;
1578 memcpy(address
->m_addr
, addr
, len
);
1580 return GSOCK_NOERROR
;
1583 GSocketError
_GAddress_translate_to(GAddress
*address
,
1584 struct sockaddr
**addr
, int *len
)
1586 if (!address
->m_addr
)
1588 address
->m_error
= GSOCK_INVADDR
;
1589 return GSOCK_INVADDR
;
1592 *len
= address
->m_len
;
1593 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1596 address
->m_error
= GSOCK_MEMERR
;
1597 return GSOCK_MEMERR
;
1600 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1601 return GSOCK_NOERROR
;
1605 * -------------------------------------------------------------------------
1606 * Internet address family
1607 * -------------------------------------------------------------------------
1610 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1612 address
->m_len
= sizeof(struct sockaddr_in
);
1613 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1614 if (address
->m_addr
== NULL
)
1616 address
->m_error
= GSOCK_MEMERR
;
1617 return GSOCK_MEMERR
;
1620 address
->m_family
= GSOCK_INET
;
1621 address
->m_realfamily
= PF_INET
;
1622 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1623 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1625 return GSOCK_NOERROR
;
1628 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1631 struct in_addr
*addr
;
1633 assert(address
!= NULL
);
1635 CHECK_ADDRESS(address
, INET
);
1637 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1639 /* If it is a numeric host name, convert it now */
1640 #if defined(HAVE_INET_ATON)
1641 if (inet_aton(hostname
, addr
) == 0)
1643 #elif defined(HAVE_INET_ADDR)
1644 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1647 /* Use gethostbyname by default */
1649 int val
= 1; /* VA doesn't like constants in conditional expressions */
1654 struct in_addr
*array_addr
;
1656 /* It is a real name, we solve it */
1657 if ((he
= gethostbyname(hostname
)) == NULL
)
1659 /* Reset to invalid address */
1660 addr
->s_addr
= INADDR_NONE
;
1661 address
->m_error
= GSOCK_NOHOST
;
1662 return GSOCK_NOHOST
;
1664 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1665 addr
->s_addr
= array_addr
[0].s_addr
;
1667 return GSOCK_NOERROR
;
1670 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1672 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1675 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1676 unsigned long hostaddr
)
1678 struct in_addr
*addr
;
1680 assert(address
!= NULL
);
1682 CHECK_ADDRESS(address
, INET
);
1684 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1685 addr
->s_addr
= htonl(hostaddr
);
1687 return GSOCK_NOERROR
;
1690 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1691 const char *protocol
)
1694 struct sockaddr_in
*addr
;
1696 assert(address
!= NULL
);
1697 CHECK_ADDRESS(address
, INET
);
1701 address
->m_error
= GSOCK_INVPORT
;
1702 return GSOCK_INVPORT
;
1705 se
= getservbyname(port
, protocol
);
1708 /* the cast to int suppresses compiler warnings about subscript having the
1710 if (isdigit((int)port
[0]))
1714 port_int
= atoi(port
);
1715 addr
= (struct sockaddr_in
*)address
->m_addr
;
1716 addr
->sin_port
= htons(port_int
);
1717 return GSOCK_NOERROR
;
1720 address
->m_error
= GSOCK_INVPORT
;
1721 return GSOCK_INVPORT
;
1724 addr
= (struct sockaddr_in
*)address
->m_addr
;
1725 addr
->sin_port
= se
->s_port
;
1727 return GSOCK_NOERROR
;
1730 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1732 struct sockaddr_in
*addr
;
1734 assert(address
!= NULL
);
1735 CHECK_ADDRESS(address
, INET
);
1737 addr
= (struct sockaddr_in
*)address
->m_addr
;
1738 addr
->sin_port
= htons(port
);
1740 return GSOCK_NOERROR
;
1743 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1747 struct sockaddr_in
*addr
;
1749 assert(address
!= NULL
);
1750 CHECK_ADDRESS(address
, INET
);
1752 addr
= (struct sockaddr_in
*)address
->m_addr
;
1753 addr_buf
= (char *)&(addr
->sin_addr
);
1755 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1758 address
->m_error
= GSOCK_NOHOST
;
1759 return GSOCK_NOHOST
;
1762 strncpy(hostname
, he
->h_name
, sbuf
);
1764 return GSOCK_NOERROR
;
1767 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1769 struct sockaddr_in
*addr
;
1771 assert(address
!= NULL
);
1772 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1774 addr
= (struct sockaddr_in
*)address
->m_addr
;
1776 return ntohl(addr
->sin_addr
.s_addr
);
1779 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1781 struct sockaddr_in
*addr
;
1783 assert(address
!= NULL
);
1784 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1786 addr
= (struct sockaddr_in
*)address
->m_addr
;
1787 return ntohs(addr
->sin_port
);
1791 * -------------------------------------------------------------------------
1792 * Unix address family
1793 * -------------------------------------------------------------------------
1796 #ifndef __VISAGECPP__
1797 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1799 address
->m_len
= sizeof(struct sockaddr_un
);
1800 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1801 if (address
->m_addr
== NULL
)
1803 address
->m_error
= GSOCK_MEMERR
;
1804 return GSOCK_MEMERR
;
1807 address
->m_family
= GSOCK_UNIX
;
1808 address
->m_realfamily
= PF_UNIX
;
1809 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1810 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1812 return GSOCK_NOERROR
;
1815 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1817 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1819 struct sockaddr_un
*addr
;
1821 assert(address
!= NULL
);
1823 CHECK_ADDRESS(address
, UNIX
);
1825 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1826 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1827 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1829 return GSOCK_NOERROR
;
1832 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1834 struct sockaddr_un
*addr
;
1836 assert(address
!= NULL
);
1837 CHECK_ADDRESS(address
, UNIX
);
1839 addr
= (struct sockaddr_un
*)address
->m_addr
;
1841 strncpy(path
, addr
->sun_path
, sbuf
);
1843 return GSOCK_NOERROR
;
1845 #endif /* !defined(__VISAGECPP__) */
1846 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */