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 * -------------------------------------------------------------------------
13 #include "wx/wxprec.h"
16 #include "wx/apptrait.h"
17 #endif //ndef WX_PRECOMP
19 #if defined(__VISAGECPP__)
20 /* Seems to be needed by Visual Age C++, though I don't see how it manages
21 to not break on including a C++ header into a plain C source file */
23 #define BSD_SELECT /* use Berkley Sockets select */
26 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
29 #include <sys/types.h>
34 #include <netinet/in.h>
37 #include <sys/ioctl.h>
43 u_char sun_len
; /* sockaddr len including null */
44 u_char sun_family
; /* AF_UNIX */
45 char sun_path
[108]; /* path name (gag) */
48 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
62 #include <machine/endian.h>
68 #define EBADF SOCEBADF
74 #include <sys/socket.h>
75 #include <sys/ioctl.h>
76 #include <sys/select.h>
78 #define close(a) soclose(a)
79 #define select(a,b,c,d,e) bsdselect(a,b,c,d,e)
80 int _System
bsdselect(int,
85 int _System
soclose(int);
93 # include <sys/filio.h>
103 # define SOCKLEN_T unsigned int
107 # define SOCKLEN_T socklen_t
110 # define SOCKLEN_T int
114 #endif /* SOCKLEN_T */
117 * MSW defines this, Unices don't.
119 #ifndef INVALID_SOCKET
120 #define INVALID_SOCKET -1
123 /* UnixWare reportedly needs this for FIONBIO definition */
125 #include <sys/filio.h>
129 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
130 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
133 #define INADDR_NONE INADDR_BROADCAST
136 #define MASK_SIGNAL() \
138 void (*old_handler)(int); \
140 old_handler = signal(SIGPIPE, SIG_IGN);
142 #define UNMASK_SIGNAL() \
143 signal(SIGPIPE, old_handler); \
147 #ifndef __GSOCKET_STANDALONE__
148 # include "wx/unix/gsockunx.h"
149 # include "wx/gsocket.h"
151 # include "gsockunx.h"
152 # include "gsocket.h"
153 #endif /* __GSOCKET_STANDALONE__ */
155 /* debugging helpers */
156 #ifdef __GSOCKET_DEBUG__
157 # define GSocket_Debug(args) printf args
159 # define GSocket_Debug(args)
160 #endif /* __GSOCKET_DEBUG__ */
162 ///////////////////////////////////////////////////////////////////////////
164 struct GSocketGUIFunctionsTable
*GSocketBSDGUIShim::ms_gui_functions
= NULL
;
166 void GSocket_SetGUIFunctions(struct GSocketGUIFunctionsTable
*guifunc
)
168 GSocketBSDGUIShim::ms_gui_functions
= guifunc
;
171 inline bool GSocketBSDGUIShim::UseGUI()
173 return ms_gui_functions
;
176 inline bool GSocketBSDGUIShim::GUI_Init()
178 return (ms_gui_functions
)?ms_gui_functions
->GUI_Init():true;
181 inline void GSocketBSDGUIShim::GUI_Cleanup()
183 if (ms_gui_functions
) ms_gui_functions
->GUI_Cleanup();
186 GSocketBSDGUIShim::GSocketBSDGUIShim()
188 m_ok
= (ms_gui_functions
? ms_gui_functions
->GUI_Init_Socket(this) : true);
191 GSocketBSDGUIShim::~GSocketBSDGUIShim()
193 if (ms_gui_functions
) ms_gui_functions
->GUI_Destroy_Socket(this);
196 void GSocketBSDGUIShim::EventLoop_Enable_Events()
198 if (ms_gui_functions
) ms_gui_functions
->Enable_Events(this);
201 void GSocketBSDGUIShim::EventLoop_Disable_Events()
203 if (ms_gui_functions
) ms_gui_functions
->Disable_Events(this);
206 void GSocketBSDGUIShim::EventLoop_Install_Callback(GSocketEvent event
)
208 if (ms_gui_functions
) ms_gui_functions
->Install_Callback(this, event
);
211 void GSocketBSDGUIShim::EventLoop_Uninstall_Callback(GSocketEvent event
)
213 if (ms_gui_functions
) ms_gui_functions
->Uninstall_Callback(this, event
);
216 ///////////////////////////////////////////////////////////////////////////
219 static struct GSocketBaseFunctionsTable gs_base_functions
=
221 GSocketBSD::_GSocket_Detected_Read
,
222 GSocketBSD::_GSocket_Detected_Write
225 /* Global initialisers */
227 int GSocket_Init(void)
229 return GSocketBSDGUIShim::GUI_Init();
232 void GSocket_Cleanup(void)
234 GSocketBSDGUIShim::GUI_Cleanup();
237 GSocketBSD::GSocketBSD()
241 m_fd
= INVALID_SOCKET
;
242 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
249 m_error
= GSOCK_NOERROR
;
252 m_gui_dependent
= NULL
;
253 m_non_blocking
= FALSE
;
254 m_timeout
= 10*60*1000;
255 /* 10 minutes * 60 sec * 1000 millisec */
256 m_establishing
= FALSE
;
258 m_functions
= &gs_base_functions
;
263 void GSocketBSD::Close()
265 EventLoop_Disable_Events();
266 // gsockosx.c calls CFSocketInvalidate which closes the socket for us
267 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
270 m_fd
= INVALID_SOCKET
;
273 GSocketBSD::~GSocketBSD()
275 /* Destroy private addresses */
277 GAddress_destroy(m_local
);
280 GAddress_destroy(m_peer
);
284 * Disallow further read/write operations on this socket, close
285 * the fd and disable all callbacks.
287 void GSocketBSD::Shutdown()
293 /* If socket has been created, shutdown it */
294 if (m_fd
!= INVALID_SOCKET
)
300 /* Disable GUI callbacks */
301 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
302 m_cbacks
[evt
] = NULL
;
304 m_detected
= GSOCK_LOST_FLAG
;
307 /* Address handling */
313 * Set or get the local or peer address for this socket. The 'set'
314 * functions return GSOCK_NOERROR on success, an error code otherwise.
315 * The 'get' functions return a pointer to a GAddress object on success,
316 * or NULL otherwise, in which case they set the error code of the
317 * corresponding GSocket.
320 * GSOCK_INVSOCK - the socket is not valid.
321 * GSOCK_INVADDR - the address is not valid.
323 GSocketError
GSocketBSD::SetLocal(GAddress
*address
)
327 /* the socket must be initialized, or it must be a server */
328 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
330 m_error
= GSOCK_INVSOCK
;
331 return GSOCK_INVSOCK
;
335 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
337 m_error
= GSOCK_INVADDR
;
338 return GSOCK_INVADDR
;
342 GAddress_destroy(m_local
);
344 m_local
= GAddress_copy(address
);
346 return GSOCK_NOERROR
;
349 GSocketError
GSocketBSD::SetPeer(GAddress
*address
)
354 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
356 m_error
= GSOCK_INVADDR
;
357 return GSOCK_INVADDR
;
361 GAddress_destroy(m_peer
);
363 m_peer
= GAddress_copy(address
);
365 return GSOCK_NOERROR
;
368 GAddress
*GSocketBSD::GetLocal()
371 struct sockaddr addr
;
372 SOCKLEN_T size
= sizeof(addr
);
377 /* try to get it from the m_local var first */
379 return GAddress_copy(m_local
);
381 /* else, if the socket is initialized, try getsockname */
382 if (m_fd
== INVALID_SOCKET
)
384 m_error
= GSOCK_INVSOCK
;
388 if (getsockname(m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
390 m_error
= GSOCK_IOERR
;
394 /* got a valid address from getsockname, create a GAddress object */
395 address
= GAddress_new();
398 m_error
= GSOCK_MEMERR
;
402 err
= _GAddress_translate_from(address
, &addr
, size
);
403 if (err
!= GSOCK_NOERROR
)
405 GAddress_destroy(address
);
413 GAddress
*GSocketBSD::GetPeer()
417 /* try to get it from the m_peer var */
419 return GAddress_copy(m_peer
);
424 /* Server specific parts */
426 /* GSocket_SetServer:
427 * Sets up this socket as a server. The local address must have been
428 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
429 * Returns GSOCK_NOERROR on success, one of the following otherwise:
432 * GSOCK_INVSOCK - the socket is in use.
433 * GSOCK_INVADDR - the local address has not been set.
434 * GSOCK_IOERR - low-level error.
436 GSocketError
GSocketBSD::SetServer()
442 /* must not be in use */
443 if (m_fd
!= INVALID_SOCKET
)
445 m_error
= GSOCK_INVSOCK
;
446 return GSOCK_INVSOCK
;
449 /* the local addr must have been set */
452 m_error
= GSOCK_INVADDR
;
453 return GSOCK_INVADDR
;
456 /* Initialize all fields */
460 /* Create the socket */
461 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
463 if (m_fd
== INVALID_SOCKET
)
465 m_error
= GSOCK_IOERR
;
468 #if defined(__EMX__) || defined(__VISAGECPP__)
469 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
471 ioctl(m_fd
, FIONBIO
, &arg
);
473 EventLoop_Enable_Events();
475 /* allow a socket to re-bind if the socket is in the TIME_WAIT
476 state after being previously closed.
478 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
480 /* Bind to the local address,
481 * retrieve the actual address bound,
482 * and listen up to 5 connections.
484 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
487 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
488 (listen(m_fd
, 5) != 0))
491 m_error
= GSOCK_IOERR
;
495 return GSOCK_NOERROR
;
498 /* GSocket_WaitConnection:
499 * Waits for an incoming client connection. Returns a pointer to
500 * a GSocket object, or NULL if there was an error, in which case
501 * the last error field will be updated for the calling GSocket.
503 * Error codes (set in the calling GSocket)
504 * GSOCK_INVSOCK - the socket is not valid or not a server.
505 * GSOCK_TIMEDOUT - timeout, no incoming connections.
506 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
507 * GSOCK_MEMERR - couldn't allocate memory.
508 * GSOCK_IOERR - low-level error.
510 GSocket
*GSocketBSD::WaitConnection()
512 struct sockaddr from
;
513 SOCKLEN_T fromlen
= sizeof(from
);
520 /* Reenable CONNECTION events */
521 Enable(GSOCK_CONNECTION
);
523 /* If the socket has already been created, we exit immediately */
524 if (m_fd
== INVALID_SOCKET
|| !m_server
)
526 m_error
= GSOCK_INVSOCK
;
530 /* Create a GSocket object for the new connection */
531 connection
= GSocket_new();
536 m_error
= GSOCK_MEMERR
;
540 /* Wait for a connection (with timeout) */
541 if (Input_Timeout() == GSOCK_TIMEDOUT
)
544 /* m_error set by _GSocket_Input_Timeout */
548 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
550 if (connection
->m_fd
== INVALID_SOCKET
)
552 if (errno
== EWOULDBLOCK
)
553 m_error
= GSOCK_WOULDBLOCK
;
555 m_error
= GSOCK_IOERR
;
561 /* Initialize all fields */
562 connection
->m_server
= FALSE
;
563 connection
->m_stream
= TRUE
;
565 /* Setup the peer address field */
566 connection
->m_peer
= GAddress_new();
567 if (!connection
->m_peer
)
570 m_error
= GSOCK_MEMERR
;
573 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
574 if (err
!= GSOCK_NOERROR
)
576 GAddress_destroy(connection
->m_peer
);
581 #if defined(__EMX__) || defined(__VISAGECPP__)
582 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
584 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
586 connection
->EventLoop_Enable_Events();
591 /* Client specific parts */
594 * For stream (connection oriented) sockets, GSocket_Connect() tries
595 * to establish a client connection to a server using the peer address
596 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
597 * connection has been succesfully established, or one of the error
598 * codes listed below. Note that for nonblocking sockets, a return
599 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
600 * request can be completed later; you should use GSocket_Select()
601 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
602 * corresponding asynchronous events.
604 * For datagram (non connection oriented) sockets, GSocket_Connect()
605 * just sets the peer address established with GSocket_SetPeer() as
606 * default destination.
609 * GSOCK_INVSOCK - the socket is in use or not valid.
610 * GSOCK_INVADDR - the peer address has not been established.
611 * GSOCK_TIMEDOUT - timeout, the connection failed.
612 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
613 * GSOCK_MEMERR - couldn't allocate memory.
614 * GSOCK_IOERR - low-level error.
616 GSocketError
GSocketBSD::Connect(GSocketStream stream
)
623 /* Enable CONNECTION events (needed for nonblocking connections) */
624 Enable(GSOCK_CONNECTION
);
626 if (m_fd
!= INVALID_SOCKET
)
628 m_error
= GSOCK_INVSOCK
;
629 return GSOCK_INVSOCK
;
634 m_error
= GSOCK_INVADDR
;
635 return GSOCK_INVADDR
;
638 /* Streamed or dgram socket? */
639 m_stream
= (stream
== GSOCK_STREAMED
);
641 m_establishing
= FALSE
;
643 /* Create the socket */
644 m_fd
= socket(m_peer
->m_realfamily
,
645 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
647 if (m_fd
== INVALID_SOCKET
)
649 m_error
= GSOCK_IOERR
;
652 #if defined(__EMX__) || defined(__VISAGECPP__)
653 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
655 ioctl(m_fd
, FIONBIO
, &arg
);
657 EventLoop_Enable_Events();
659 /* Connect it to the peer address, with a timeout (see below) */
660 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
666 /* If connect failed with EINPROGRESS and the GSocket object
667 * is in blocking mode, we select() for the specified timeout
668 * checking for writability to see if the connection request
671 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
673 if (Output_Timeout() == GSOCK_TIMEDOUT
)
676 /* m_error is set in _GSocket_Output_Timeout */
677 return GSOCK_TIMEDOUT
;
682 SOCKLEN_T len
= sizeof(error
);
684 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
687 return GSOCK_NOERROR
;
691 /* If connect failed with EINPROGRESS and the GSocket object
692 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
693 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
694 * this way if the connection completes, a GSOCK_CONNECTION
695 * event will be generated, if enabled.
697 if ((err
== EINPROGRESS
) && (m_non_blocking
))
699 m_establishing
= TRUE
;
700 m_error
= GSOCK_WOULDBLOCK
;
701 return GSOCK_WOULDBLOCK
;
704 /* If connect failed with an error other than EINPROGRESS,
705 * then the call to GSocket_Connect has failed.
708 m_error
= GSOCK_IOERR
;
712 return GSOCK_NOERROR
;
715 /* Datagram sockets */
717 /* GSocket_SetNonOriented:
718 * Sets up this socket as a non-connection oriented (datagram) socket.
719 * Before using this function, the local address must have been set
720 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
721 * on success, or one of the following otherwise.
724 * GSOCK_INVSOCK - the socket is in use.
725 * GSOCK_INVADDR - the local address has not been set.
726 * GSOCK_IOERR - low-level error.
728 GSocketError
GSocketBSD::SetNonOriented()
734 if (m_fd
!= INVALID_SOCKET
)
736 m_error
= GSOCK_INVSOCK
;
737 return GSOCK_INVSOCK
;
742 m_error
= GSOCK_INVADDR
;
743 return GSOCK_INVADDR
;
746 /* Initialize all fields */
750 /* Create the socket */
751 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
753 if (m_fd
== INVALID_SOCKET
)
755 m_error
= GSOCK_IOERR
;
758 #if defined(__EMX__) || defined(__VISAGECPP__)
759 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
761 ioctl(m_fd
, FIONBIO
, &arg
);
763 EventLoop_Enable_Events();
765 /* Bind to the local address,
766 * and retrieve the actual address bound.
768 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
771 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
774 m_error
= GSOCK_IOERR
;
778 return GSOCK_NOERROR
;
783 /* Like recv(), send(), ... */
784 int GSocketBSD::Read(char *buffer
, int size
)
790 if (m_fd
== INVALID_SOCKET
|| m_server
)
792 m_error
= GSOCK_INVSOCK
;
796 /* Disable events during query of socket status */
797 Disable(GSOCK_INPUT
);
799 /* If the socket is blocking, wait for data (with a timeout) */
800 if (Input_Timeout() == GSOCK_TIMEDOUT
)
801 /* We no longer return here immediately, otherwise socket events would not be re-enabled! */
806 ret
= Recv_Stream(buffer
, size
);
808 ret
= Recv_Dgram(buffer
, size
);
813 if (errno
== EWOULDBLOCK
)
814 m_error
= GSOCK_WOULDBLOCK
;
816 m_error
= GSOCK_IOERR
;
819 /* Enable events again now that we are done processing */
825 int GSocketBSD::Write(const char *buffer
, int size
)
831 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
833 if (m_fd
== INVALID_SOCKET
|| m_server
)
835 m_error
= GSOCK_INVSOCK
;
839 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
841 /* If the socket is blocking, wait for writability (with a timeout) */
842 if (Output_Timeout() == GSOCK_TIMEDOUT
)
845 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
849 ret
= Send_Stream(buffer
, size
);
851 ret
= Send_Dgram(buffer
, size
);
853 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
857 if (errno
== EWOULDBLOCK
)
859 m_error
= GSOCK_WOULDBLOCK
;
860 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
864 m_error
= GSOCK_IOERR
;
865 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
868 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
869 * in MSW). Once the first OUTPUT event is received, users can assume
870 * that the socket is writable until a read operation fails. Only then
871 * will further OUTPUT events be posted.
873 Enable(GSOCK_OUTPUT
);
877 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
883 * Polls the socket to determine its status. This function will
884 * check for the events specified in the 'flags' parameter, and
885 * it will return a mask indicating which operations can be
886 * performed. This function won't block, regardless of the
887 * mode (blocking | nonblocking) of the socket.
889 GSocketEventFlags
GSocketBSD::Select(GSocketEventFlags flags
)
891 if (!GSocketBSDGUIShim::UseGUI())
894 GSocketEventFlags result
= 0;
902 /* Do not use a static struct, Linux can garble it */
903 tv
.tv_sec
= m_timeout
/ 1000;
904 tv
.tv_usec
= (m_timeout
% 1000) / 1000;
909 FD_SET(m_fd
, &readfds
);
910 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
911 FD_SET(m_fd
, &writefds
);
912 FD_SET(m_fd
, &exceptfds
);
914 /* Check 'sticky' CONNECTION flag first */
915 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
917 /* If we have already detected a LOST event, then don't try
918 * to do any further processing.
920 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
922 m_establishing
= FALSE
;
924 return (GSOCK_LOST_FLAG
& flags
);
928 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
930 /* What to do here? */
931 return (result
& flags
);
934 /* Check for readability */
935 if (FD_ISSET(m_fd
, &readfds
))
939 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
941 result
|= GSOCK_INPUT_FLAG
;
945 if (m_server
&& m_stream
)
947 result
|= GSOCK_CONNECTION_FLAG
;
948 m_detected
|= GSOCK_CONNECTION_FLAG
;
952 m_detected
= GSOCK_LOST_FLAG
;
953 m_establishing
= FALSE
;
955 /* LOST event: Abort any further processing */
956 return (GSOCK_LOST_FLAG
& flags
);
961 /* Check for writability */
962 if (FD_ISSET(m_fd
, &writefds
))
964 if (m_establishing
&& !m_server
)
967 SOCKLEN_T len
= sizeof(error
);
969 m_establishing
= FALSE
;
971 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
975 m_detected
= GSOCK_LOST_FLAG
;
977 /* LOST event: Abort any further processing */
978 return (GSOCK_LOST_FLAG
& flags
);
982 result
|= GSOCK_CONNECTION_FLAG
;
983 m_detected
|= GSOCK_CONNECTION_FLAG
;
988 result
|= GSOCK_OUTPUT_FLAG
;
992 /* Check for exceptions and errors (is this useful in Unices?) */
993 if (FD_ISSET(m_fd
, &exceptfds
))
995 m_establishing
= FALSE
;
996 m_detected
= GSOCK_LOST_FLAG
;
998 /* LOST event: Abort any further processing */
999 return (GSOCK_LOST_FLAG
& flags
);
1002 return (result
& flags
);
1009 return flags
& m_detected
;
1016 /* GSocket_SetNonBlocking:
1017 * Sets the socket to non-blocking mode. All IO calls will return
1020 void GSocketBSD::SetNonBlocking(int non_block
)
1024 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1026 m_non_blocking
= non_block
;
1029 /* GSocket_SetTimeout:
1030 * Sets the timeout for blocking calls. Time is expressed in
1033 void GSocketBSD::SetTimeout(unsigned long millisec
)
1037 m_timeout
= millisec
;
1040 /* GSocket_GetError:
1041 * Returns the last error occured for this socket. Note that successful
1042 * operations do not clear this back to GSOCK_NOERROR, so use it only
1045 GSocketError
GSocketBSD::GetError()
1055 * There is data to be read in the input buffer. If, after a read
1056 * operation, there is still data available, the callback function will
1059 * The socket is available for writing. That is, the next write call
1060 * won't block. This event is generated only once, when the connection is
1061 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1062 * when the output buffer empties again. This means that the app should
1063 * assume that it can write since the first OUTPUT event, and no more
1064 * OUTPUT events will be generated unless an error occurs.
1066 * Connection succesfully established, for client sockets, or incoming
1067 * client connection, for server sockets. Wait for this event (also watch
1068 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1070 * The connection is lost (or a connection request failed); this could
1071 * be due to a failure, or due to the peer closing it gracefully.
1074 /* GSocket_SetCallback:
1075 * Enables the callbacks specified by 'flags'. Note that 'flags'
1076 * may be a combination of flags OR'ed toghether, so the same
1077 * callback function can be made to accept different events.
1078 * The callback function must have the following prototype:
1080 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1082 void GSocketBSD::SetCallback(GSocketEventFlags flags
,
1083 GSocketCallback callback
, char *cdata
)
1089 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1091 if ((flags
& (1 << count
)) != 0)
1093 m_cbacks
[count
] = callback
;
1094 m_data
[count
] = cdata
;
1099 /* GSocket_UnsetCallback:
1100 * Disables all callbacks specified by 'flags', which may be a
1101 * combination of flags OR'ed toghether.
1103 void GSocketBSD::UnsetCallback(GSocketEventFlags flags
)
1109 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1111 if ((flags
& (1 << count
)) != 0)
1113 m_cbacks
[count
] = NULL
;
1114 m_data
[count
] = NULL
;
1120 #define CALL_CALLBACK(event) { \
1122 if (m_cbacks[event]) \
1123 m_cbacks[event](this, event, m_data[event]); \
1127 void GSocketBSD::Enable(GSocketEvent event
)
1129 m_detected
&= ~(1 << event
);
1130 EventLoop_Install_Callback(event
);
1133 void GSocketBSD::Disable(GSocketEvent event
)
1135 m_detected
|= (1 << event
);
1136 EventLoop_Uninstall_Callback(event
);
1139 /* _GSocket_Input_Timeout:
1140 * For blocking sockets, wait until data is available or
1141 * until timeout ellapses.
1143 GSocketError
GSocketBSD::Input_Timeout()
1149 /* Linux select() will overwrite the struct on return */
1150 tv
.tv_sec
= (m_timeout
/ 1000);
1151 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1153 if (!m_non_blocking
)
1156 FD_SET(m_fd
, &readfds
);
1157 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1160 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1161 m_error
= GSOCK_TIMEDOUT
;
1162 return GSOCK_TIMEDOUT
;
1166 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1167 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1168 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1169 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1170 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1171 m_error
= GSOCK_TIMEDOUT
;
1172 return GSOCK_TIMEDOUT
;
1175 return GSOCK_NOERROR
;
1178 /* _GSocket_Output_Timeout:
1179 * For blocking sockets, wait until data can be sent without
1180 * blocking or until timeout ellapses.
1182 GSocketError
GSocketBSD::Output_Timeout()
1188 /* Linux select() will overwrite the struct on return */
1189 tv
.tv_sec
= (m_timeout
/ 1000);
1190 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1192 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1194 if (!m_non_blocking
)
1197 FD_SET(m_fd
, &writefds
);
1198 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1201 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1202 m_error
= GSOCK_TIMEDOUT
;
1203 return GSOCK_TIMEDOUT
;
1207 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1208 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1209 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1210 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1211 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1212 m_error
= GSOCK_TIMEDOUT
;
1213 return GSOCK_TIMEDOUT
;
1215 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1216 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1219 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1224 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1227 return GSOCK_NOERROR
;
1230 int GSocketBSD::Recv_Stream(char *buffer
, int size
)
1232 return recv(m_fd
, buffer
, size
, 0);
1235 int GSocketBSD::Recv_Dgram(char *buffer
, int size
)
1237 struct sockaddr from
;
1238 SOCKLEN_T fromlen
= sizeof(from
);
1242 fromlen
= sizeof(from
);
1244 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1249 /* Translate a system address into a GSocket address */
1252 m_peer
= GAddress_new();
1255 m_error
= GSOCK_MEMERR
;
1259 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1260 if (err
!= GSOCK_NOERROR
)
1262 GAddress_destroy(m_peer
);
1271 int GSocketBSD::Send_Stream(const char *buffer
, int size
)
1275 #ifndef __VISAGECPP__
1277 ret
= send(m_fd
, buffer
, size
, 0);
1280 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1286 int GSocketBSD::Send_Dgram(const char *buffer
, int size
)
1288 struct sockaddr
*addr
;
1294 m_error
= GSOCK_INVADDR
;
1298 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1299 if (err
!= GSOCK_NOERROR
)
1305 #ifndef __VISAGECPP__
1307 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1310 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1313 /* Frees memory allocated from _GAddress_translate_to */
1319 void GSocketBSD::Detected_Read()
1323 /* If we have already detected a LOST event, then don't try
1324 * to do any further processing.
1326 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1328 m_establishing
= FALSE
;
1330 CALL_CALLBACK(GSOCK_LOST
);
1335 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1337 CALL_CALLBACK(GSOCK_INPUT
);
1341 if (m_server
&& m_stream
)
1343 CALL_CALLBACK(GSOCK_CONNECTION
);
1347 CALL_CALLBACK(GSOCK_LOST
);
1353 void GSocketBSD::Detected_Write()
1355 /* If we have already detected a LOST event, then don't try
1356 * to do any further processing.
1358 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1360 m_establishing
= FALSE
;
1362 CALL_CALLBACK(GSOCK_LOST
);
1367 if (m_establishing
&& !m_server
)
1370 SOCKLEN_T len
= sizeof(error
);
1372 m_establishing
= FALSE
;
1374 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1378 CALL_CALLBACK(GSOCK_LOST
);
1383 CALL_CALLBACK(GSOCK_CONNECTION
);
1384 /* We have to fire this event by hand because CONNECTION (for clients)
1385 * and OUTPUT are internally the same and we just disabled CONNECTION
1386 * events with the above macro.
1388 CALL_CALLBACK(GSOCK_OUTPUT
);
1393 CALL_CALLBACK(GSOCK_OUTPUT
);
1397 /* Compatibility functions for GSocket */
1398 GSocket
*GSocket_new(void)
1400 GSocket
*newsocket
= new GSocketBSDGUIShim();
1401 if(newsocket
->IsOk())
1407 void GSocket_destroy(GSocket
*socket
)
1411 /* Check that the socket is really shutdowned */
1412 if (socket
->m_fd
!= INVALID_SOCKET
)
1418 void GSocketBSD::_GSocket_Detected_Read(GSocket
*socket
)
1419 { socket
->Detected_Read(); }
1421 void GSocketBSD::_GSocket_Detected_Write(GSocket
*socket
)
1422 { socket
->Detected_Write(); }
1425 * -------------------------------------------------------------------------
1427 * -------------------------------------------------------------------------
1430 /* CHECK_ADDRESS verifies that the current address family is either
1431 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1432 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1433 * an appropiate error code.
1435 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1437 #define CHECK_ADDRESS(address, family) \
1439 if (address->m_family == GSOCK_NOFAMILY) \
1440 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1441 return address->m_error; \
1442 if (address->m_family != GSOCK_##family) \
1444 address->m_error = GSOCK_INVADDR; \
1445 return GSOCK_INVADDR; \
1449 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1451 if (address->m_family == GSOCK_NOFAMILY) \
1452 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1454 if (address->m_family != GSOCK_##family) \
1456 address->m_error = GSOCK_INVADDR; \
1462 GAddress
*GAddress_new(void)
1466 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1469 address
->m_family
= GSOCK_NOFAMILY
;
1470 address
->m_addr
= NULL
;
1476 GAddress
*GAddress_copy(GAddress
*address
)
1480 assert(address
!= NULL
);
1482 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1485 memcpy(addr2
, address
, sizeof(GAddress
));
1487 if (address
->m_addr
&& address
->m_len
> 0)
1489 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1490 if (addr2
->m_addr
== NULL
)
1495 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1501 void GAddress_destroy(GAddress
*address
)
1503 assert(address
!= NULL
);
1505 if (address
->m_addr
)
1506 free(address
->m_addr
);
1511 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1513 assert(address
!= NULL
);
1515 address
->m_family
= type
;
1518 GAddressType
GAddress_GetFamily(GAddress
*address
)
1520 assert(address
!= NULL
);
1522 return address
->m_family
;
1525 GSocketError
_GAddress_translate_from(GAddress
*address
,
1526 struct sockaddr
*addr
, int len
)
1528 address
->m_realfamily
= addr
->sa_family
;
1529 switch (addr
->sa_family
)
1532 address
->m_family
= GSOCK_INET
;
1535 address
->m_family
= GSOCK_UNIX
;
1539 address
->m_family
= GSOCK_INET6
;
1544 address
->m_error
= GSOCK_INVOP
;
1549 if (address
->m_addr
)
1550 free(address
->m_addr
);
1552 address
->m_len
= len
;
1553 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1555 if (address
->m_addr
== NULL
)
1557 address
->m_error
= GSOCK_MEMERR
;
1558 return GSOCK_MEMERR
;
1560 memcpy(address
->m_addr
, addr
, len
);
1562 return GSOCK_NOERROR
;
1565 GSocketError
_GAddress_translate_to(GAddress
*address
,
1566 struct sockaddr
**addr
, int *len
)
1568 if (!address
->m_addr
)
1570 address
->m_error
= GSOCK_INVADDR
;
1571 return GSOCK_INVADDR
;
1574 *len
= address
->m_len
;
1575 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1578 address
->m_error
= GSOCK_MEMERR
;
1579 return GSOCK_MEMERR
;
1582 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1583 return GSOCK_NOERROR
;
1587 * -------------------------------------------------------------------------
1588 * Internet address family
1589 * -------------------------------------------------------------------------
1592 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1594 address
->m_len
= sizeof(struct sockaddr_in
);
1595 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1596 if (address
->m_addr
== NULL
)
1598 address
->m_error
= GSOCK_MEMERR
;
1599 return GSOCK_MEMERR
;
1602 address
->m_family
= GSOCK_INET
;
1603 address
->m_realfamily
= PF_INET
;
1604 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1605 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1607 return GSOCK_NOERROR
;
1610 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1613 struct in_addr
*addr
;
1615 assert(address
!= NULL
);
1617 CHECK_ADDRESS(address
, INET
);
1619 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1621 /* If it is a numeric host name, convert it now */
1622 #if defined(HAVE_INET_ATON)
1623 if (inet_aton(hostname
, addr
) == 0)
1625 #elif defined(HAVE_INET_ADDR)
1626 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1629 /* Use gethostbyname by default */
1631 int val
= 1; //VA doesn't like constants in conditional expressions at all
1636 struct in_addr
*array_addr
;
1638 /* It is a real name, we solve it */
1639 if ((he
= gethostbyname(hostname
)) == NULL
)
1641 /* Reset to invalid address */
1642 addr
->s_addr
= INADDR_NONE
;
1643 address
->m_error
= GSOCK_NOHOST
;
1644 return GSOCK_NOHOST
;
1646 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1647 addr
->s_addr
= array_addr
[0].s_addr
;
1649 return GSOCK_NOERROR
;
1652 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1654 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1657 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1658 unsigned long hostaddr
)
1660 struct in_addr
*addr
;
1662 assert(address
!= NULL
);
1664 CHECK_ADDRESS(address
, INET
);
1666 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1667 addr
->s_addr
= htonl(hostaddr
);
1669 return GSOCK_NOERROR
;
1672 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1673 const char *protocol
)
1676 struct sockaddr_in
*addr
;
1678 assert(address
!= NULL
);
1679 CHECK_ADDRESS(address
, INET
);
1683 address
->m_error
= GSOCK_INVPORT
;
1684 return GSOCK_INVPORT
;
1687 se
= getservbyname(port
, protocol
);
1690 /* the cast to int suppresses compiler warnings about subscript having the
1692 if (isdigit((int)port
[0]))
1696 port_int
= atoi(port
);
1697 addr
= (struct sockaddr_in
*)address
->m_addr
;
1698 addr
->sin_port
= htons(port_int
);
1699 return GSOCK_NOERROR
;
1702 address
->m_error
= GSOCK_INVPORT
;
1703 return GSOCK_INVPORT
;
1706 addr
= (struct sockaddr_in
*)address
->m_addr
;
1707 addr
->sin_port
= se
->s_port
;
1709 return GSOCK_NOERROR
;
1712 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1714 struct sockaddr_in
*addr
;
1716 assert(address
!= NULL
);
1717 CHECK_ADDRESS(address
, INET
);
1719 addr
= (struct sockaddr_in
*)address
->m_addr
;
1720 addr
->sin_port
= htons(port
);
1722 return GSOCK_NOERROR
;
1725 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1729 struct sockaddr_in
*addr
;
1731 assert(address
!= NULL
);
1732 CHECK_ADDRESS(address
, INET
);
1734 addr
= (struct sockaddr_in
*)address
->m_addr
;
1735 addr_buf
= (char *)&(addr
->sin_addr
);
1737 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1740 address
->m_error
= GSOCK_NOHOST
;
1741 return GSOCK_NOHOST
;
1744 strncpy(hostname
, he
->h_name
, sbuf
);
1746 return GSOCK_NOERROR
;
1749 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1751 struct sockaddr_in
*addr
;
1753 assert(address
!= NULL
);
1754 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1756 addr
= (struct sockaddr_in
*)address
->m_addr
;
1758 return ntohl(addr
->sin_addr
.s_addr
);
1761 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1763 struct sockaddr_in
*addr
;
1765 assert(address
!= NULL
);
1766 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1768 addr
= (struct sockaddr_in
*)address
->m_addr
;
1769 return ntohs(addr
->sin_port
);
1773 * -------------------------------------------------------------------------
1774 * Unix address family
1775 * -------------------------------------------------------------------------
1778 #ifndef __VISAGECPP__
1779 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1781 address
->m_len
= sizeof(struct sockaddr_un
);
1782 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1783 if (address
->m_addr
== NULL
)
1785 address
->m_error
= GSOCK_MEMERR
;
1786 return GSOCK_MEMERR
;
1789 address
->m_family
= GSOCK_UNIX
;
1790 address
->m_realfamily
= PF_UNIX
;
1791 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1792 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1794 return GSOCK_NOERROR
;
1797 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1799 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1801 struct sockaddr_un
*addr
;
1803 assert(address
!= NULL
);
1805 CHECK_ADDRESS(address
, UNIX
);
1807 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1808 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1809 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1811 return GSOCK_NOERROR
;
1814 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1816 struct sockaddr_un
*addr
;
1818 assert(address
!= NULL
);
1819 CHECK_ADDRESS(address
, UNIX
);
1821 addr
= (struct sockaddr_un
*)address
->m_addr
;
1823 strncpy(path
, addr
->sun_path
, sbuf
);
1825 return GSOCK_NOERROR
;
1827 #endif /* !defined(__VISAGECPP__) */
1828 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */