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 */
461 /* Create the socket */
462 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
464 if (m_fd
== INVALID_SOCKET
)
466 m_error
= GSOCK_IOERR
;
469 #if defined(__EMX__) || defined(__VISAGECPP__)
470 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
472 ioctl(m_fd
, FIONBIO
, &arg
);
474 EventLoop_Enable_Events();
476 /* allow a socket to re-bind if the socket is in the TIME_WAIT
477 state after being previously closed.
479 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
481 /* Bind to the local address,
482 * retrieve the actual address bound,
483 * and listen up to 5 connections.
485 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
488 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
489 (listen(m_fd
, 5) != 0))
492 m_error
= GSOCK_IOERR
;
496 return GSOCK_NOERROR
;
499 /* GSocket_WaitConnection:
500 * Waits for an incoming client connection. Returns a pointer to
501 * a GSocket object, or NULL if there was an error, in which case
502 * the last error field will be updated for the calling GSocket.
504 * Error codes (set in the calling GSocket)
505 * GSOCK_INVSOCK - the socket is not valid or not a server.
506 * GSOCK_TIMEDOUT - timeout, no incoming connections.
507 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
508 * GSOCK_MEMERR - couldn't allocate memory.
509 * GSOCK_IOERR - low-level error.
511 GSocket
*GSocketBSD::WaitConnection()
513 struct sockaddr from
;
514 SOCKLEN_T fromlen
= sizeof(from
);
521 /* Reenable CONNECTION events */
522 Enable(GSOCK_CONNECTION
);
524 /* If the socket has already been created, we exit immediately */
525 if (m_fd
== INVALID_SOCKET
|| !m_server
)
527 m_error
= GSOCK_INVSOCK
;
531 /* Create a GSocket object for the new connection */
532 connection
= GSocket_new();
537 m_error
= GSOCK_MEMERR
;
541 /* Wait for a connection (with timeout) */
542 if (Input_Timeout() == GSOCK_TIMEDOUT
)
545 /* m_error set by _GSocket_Input_Timeout */
549 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
551 if (connection
->m_fd
== INVALID_SOCKET
)
553 if (errno
== EWOULDBLOCK
)
554 m_error
= GSOCK_WOULDBLOCK
;
556 m_error
= GSOCK_IOERR
;
562 /* Initialize all fields */
563 connection
->m_server
= FALSE
;
564 connection
->m_stream
= TRUE
;
565 connection
->m_oriented
= TRUE
;
567 /* Setup the peer address field */
568 connection
->m_peer
= GAddress_new();
569 if (!connection
->m_peer
)
572 m_error
= GSOCK_MEMERR
;
575 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
576 if (err
!= GSOCK_NOERROR
)
578 GAddress_destroy(connection
->m_peer
);
583 #if defined(__EMX__) || defined(__VISAGECPP__)
584 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
586 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
588 connection
->EventLoop_Enable_Events();
593 /* Client specific parts */
596 * For stream (connection oriented) sockets, GSocket_Connect() tries
597 * to establish a client connection to a server using the peer address
598 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
599 * connection has been succesfully established, or one of the error
600 * codes listed below. Note that for nonblocking sockets, a return
601 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
602 * request can be completed later; you should use GSocket_Select()
603 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
604 * corresponding asynchronous events.
606 * For datagram (non connection oriented) sockets, GSocket_Connect()
607 * just sets the peer address established with GSocket_SetPeer() as
608 * default destination.
611 * GSOCK_INVSOCK - the socket is in use or not valid.
612 * GSOCK_INVADDR - the peer address has not been established.
613 * GSOCK_TIMEDOUT - timeout, the connection failed.
614 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
615 * GSOCK_MEMERR - couldn't allocate memory.
616 * GSOCK_IOERR - low-level error.
618 GSocketError
GSocketBSD::Connect(GSocketStream stream
)
625 /* Enable CONNECTION events (needed for nonblocking connections) */
626 Enable(GSOCK_CONNECTION
);
628 if (m_fd
!= INVALID_SOCKET
)
630 m_error
= GSOCK_INVSOCK
;
631 return GSOCK_INVSOCK
;
636 m_error
= GSOCK_INVADDR
;
637 return GSOCK_INVADDR
;
640 /* Streamed or dgram socket? */
641 m_stream
= (stream
== GSOCK_STREAMED
);
644 m_establishing
= FALSE
;
646 /* Create the socket */
647 m_fd
= socket(m_peer
->m_realfamily
,
648 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
650 if (m_fd
== INVALID_SOCKET
)
652 m_error
= GSOCK_IOERR
;
655 #if defined(__EMX__) || defined(__VISAGECPP__)
656 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
658 ioctl(m_fd
, FIONBIO
, &arg
);
660 EventLoop_Enable_Events();
662 /* Connect it to the peer address, with a timeout (see below) */
663 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
669 /* If connect failed with EINPROGRESS and the GSocket object
670 * is in blocking mode, we select() for the specified timeout
671 * checking for writability to see if the connection request
674 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
676 if (Output_Timeout() == GSOCK_TIMEDOUT
)
679 /* m_error is set in _GSocket_Output_Timeout */
680 return GSOCK_TIMEDOUT
;
685 SOCKLEN_T len
= sizeof(error
);
687 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
690 return GSOCK_NOERROR
;
694 /* If connect failed with EINPROGRESS and the GSocket object
695 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
696 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
697 * this way if the connection completes, a GSOCK_CONNECTION
698 * event will be generated, if enabled.
700 if ((err
== EINPROGRESS
) && (m_non_blocking
))
702 m_establishing
= TRUE
;
703 m_error
= GSOCK_WOULDBLOCK
;
704 return GSOCK_WOULDBLOCK
;
707 /* If connect failed with an error other than EINPROGRESS,
708 * then the call to GSocket_Connect has failed.
711 m_error
= GSOCK_IOERR
;
715 return GSOCK_NOERROR
;
718 /* Datagram sockets */
720 /* GSocket_SetNonOriented:
721 * Sets up this socket as a non-connection oriented (datagram) socket.
722 * Before using this function, the local address must have been set
723 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
724 * on success, or one of the following otherwise.
727 * GSOCK_INVSOCK - the socket is in use.
728 * GSOCK_INVADDR - the local address has not been set.
729 * GSOCK_IOERR - low-level error.
731 GSocketError
GSocketBSD::SetNonOriented()
737 if (m_fd
!= INVALID_SOCKET
)
739 m_error
= GSOCK_INVSOCK
;
740 return GSOCK_INVSOCK
;
745 m_error
= GSOCK_INVADDR
;
746 return GSOCK_INVADDR
;
749 /* Initialize all fields */
754 /* Create the socket */
755 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
757 if (m_fd
== INVALID_SOCKET
)
759 m_error
= GSOCK_IOERR
;
762 #if defined(__EMX__) || defined(__VISAGECPP__)
763 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
765 ioctl(m_fd
, FIONBIO
, &arg
);
767 EventLoop_Enable_Events();
769 /* Bind to the local address,
770 * and retrieve the actual address bound.
772 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
775 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
778 m_error
= GSOCK_IOERR
;
782 return GSOCK_NOERROR
;
787 /* Like recv(), send(), ... */
788 int GSocketBSD::Read(char *buffer
, int size
)
794 /* When using CFSocket we MUST NOT reenable events until we finish reading */
796 /* Reenable INPUT events */
800 if (m_fd
== INVALID_SOCKET
|| m_server
)
802 m_error
= GSOCK_INVSOCK
;
806 /* If the socket is blocking, wait for data (with a timeout) */
807 if (Input_Timeout() == GSOCK_TIMEDOUT
)
812 ret
= Recv_Stream(buffer
, size
);
814 ret
= Recv_Dgram(buffer
, size
);
818 if (errno
== EWOULDBLOCK
)
819 m_error
= GSOCK_WOULDBLOCK
;
821 m_error
= GSOCK_IOERR
;
825 /* Reenable INPUT events */
832 int GSocketBSD::Write(const char *buffer
, int size
)
838 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
840 if (m_fd
== INVALID_SOCKET
|| m_server
)
842 m_error
= GSOCK_INVSOCK
;
846 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
848 /* If the socket is blocking, wait for writability (with a timeout) */
849 if (Output_Timeout() == GSOCK_TIMEDOUT
)
852 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
856 ret
= Send_Stream(buffer
, size
);
858 ret
= Send_Dgram(buffer
, size
);
860 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
864 if (errno
== EWOULDBLOCK
)
866 m_error
= GSOCK_WOULDBLOCK
;
867 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
871 m_error
= GSOCK_IOERR
;
872 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
875 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
876 * in MSW). Once the first OUTPUT event is received, users can assume
877 * that the socket is writable until a read operation fails. Only then
878 * will further OUTPUT events be posted.
880 Enable(GSOCK_OUTPUT
);
884 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
890 * Polls the socket to determine its status. This function will
891 * check for the events specified in the 'flags' parameter, and
892 * it will return a mask indicating which operations can be
893 * performed. This function won't block, regardless of the
894 * mode (blocking | nonblocking) of the socket.
896 GSocketEventFlags
GSocketBSD::Select(GSocketEventFlags flags
)
898 if (!GSocketBSDGUIShim::UseGUI())
901 GSocketEventFlags result
= 0;
907 /* Do not use a static struct, Linux can garble it */
908 tv
.tv_sec
= m_timeout
/ 1000;
909 tv
.tv_usec
= (m_timeout
% 1000) / 1000;
916 FD_SET(m_fd
, &readfds
);
917 if (flags
& GSOCK_OUTPUT_FLAG
)
918 FD_SET(m_fd
, &writefds
);
919 FD_SET(m_fd
, &exceptfds
);
921 /* Check 'sticky' CONNECTION flag first */
922 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
924 /* If we have already detected a LOST event, then don't try
925 * to do any further processing.
927 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
929 m_establishing
= FALSE
;
931 return (GSOCK_LOST_FLAG
& flags
);
935 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
937 /* What to do here? */
938 return (result
& flags
);
941 /* Check for readability */
942 if (FD_ISSET(m_fd
, &readfds
))
946 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
948 result
|= GSOCK_INPUT_FLAG
;
952 if (m_server
&& m_stream
)
954 result
|= GSOCK_CONNECTION_FLAG
;
955 m_detected
|= GSOCK_CONNECTION_FLAG
;
959 m_detected
= GSOCK_LOST_FLAG
;
960 m_establishing
= FALSE
;
962 /* LOST event: Abort any further processing */
963 return (GSOCK_LOST_FLAG
& flags
);
968 /* Check for writability */
969 if (FD_ISSET(m_fd
, &writefds
))
971 if (m_establishing
&& !m_server
)
974 SOCKLEN_T len
= sizeof(error
);
976 m_establishing
= FALSE
;
978 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
982 m_detected
= GSOCK_LOST_FLAG
;
984 /* LOST event: Abort any further processing */
985 return (GSOCK_LOST_FLAG
& flags
);
989 result
|= GSOCK_CONNECTION_FLAG
;
990 m_detected
|= GSOCK_CONNECTION_FLAG
;
995 result
|= GSOCK_OUTPUT_FLAG
;
999 /* Check for exceptions and errors (is this useful in Unices?) */
1000 if (FD_ISSET(m_fd
, &exceptfds
))
1002 m_establishing
= FALSE
;
1003 m_detected
= GSOCK_LOST_FLAG
;
1005 /* LOST event: Abort any further processing */
1006 return (GSOCK_LOST_FLAG
& flags
);
1009 return (result
& flags
);
1016 return flags
& m_detected
;
1023 /* GSocket_SetNonBlocking:
1024 * Sets the socket to non-blocking mode. All IO calls will return
1027 void GSocketBSD::SetNonBlocking(int non_block
)
1031 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1033 m_non_blocking
= non_block
;
1036 /* GSocket_SetTimeout:
1037 * Sets the timeout for blocking calls. Time is expressed in
1040 void GSocketBSD::SetTimeout(unsigned long millisec
)
1044 m_timeout
= millisec
;
1047 /* GSocket_GetError:
1048 * Returns the last error occured for this socket. Note that successful
1049 * operations do not clear this back to GSOCK_NOERROR, so use it only
1052 GSocketError
GSocketBSD::GetError()
1062 * There is data to be read in the input buffer. If, after a read
1063 * operation, there is still data available, the callback function will
1066 * The socket is available for writing. That is, the next write call
1067 * won't block. This event is generated only once, when the connection is
1068 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1069 * when the output buffer empties again. This means that the app should
1070 * assume that it can write since the first OUTPUT event, and no more
1071 * OUTPUT events will be generated unless an error occurs.
1073 * Connection succesfully established, for client sockets, or incoming
1074 * client connection, for server sockets. Wait for this event (also watch
1075 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1077 * The connection is lost (or a connection request failed); this could
1078 * be due to a failure, or due to the peer closing it gracefully.
1081 /* GSocket_SetCallback:
1082 * Enables the callbacks specified by 'flags'. Note that 'flags'
1083 * may be a combination of flags OR'ed toghether, so the same
1084 * callback function can be made to accept different events.
1085 * The callback function must have the following prototype:
1087 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1089 void GSocketBSD::SetCallback(GSocketEventFlags flags
,
1090 GSocketCallback callback
, char *cdata
)
1096 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1098 if ((flags
& (1 << count
)) != 0)
1100 m_cbacks
[count
] = callback
;
1101 m_data
[count
] = cdata
;
1106 /* GSocket_UnsetCallback:
1107 * Disables all callbacks specified by 'flags', which may be a
1108 * combination of flags OR'ed toghether.
1110 void GSocketBSD::UnsetCallback(GSocketEventFlags flags
)
1116 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1118 if ((flags
& (1 << count
)) != 0)
1120 m_cbacks
[count
] = NULL
;
1121 m_data
[count
] = NULL
;
1127 #define CALL_CALLBACK(event) { \
1129 if (m_cbacks[event]) \
1130 m_cbacks[event](this, event, m_data[event]); \
1134 void GSocketBSD::Enable(GSocketEvent event
)
1136 m_detected
&= ~(1 << event
);
1137 EventLoop_Install_Callback(event
);
1140 void GSocketBSD::Disable(GSocketEvent event
)
1142 m_detected
|= (1 << event
);
1143 EventLoop_Uninstall_Callback(event
);
1146 /* _GSocket_Input_Timeout:
1147 * For blocking sockets, wait until data is available or
1148 * until timeout ellapses.
1150 GSocketError
GSocketBSD::Input_Timeout()
1156 /* Linux select() will overwrite the struct on return */
1157 tv
.tv_sec
= (m_timeout
/ 1000);
1158 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1160 if (!m_non_blocking
)
1163 FD_SET(m_fd
, &readfds
);
1164 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1167 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1168 m_error
= GSOCK_TIMEDOUT
;
1169 return GSOCK_TIMEDOUT
;
1173 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1174 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1175 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1176 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1177 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1178 m_error
= GSOCK_TIMEDOUT
;
1179 return GSOCK_TIMEDOUT
;
1182 return GSOCK_NOERROR
;
1185 /* _GSocket_Output_Timeout:
1186 * For blocking sockets, wait until data can be sent without
1187 * blocking or until timeout ellapses.
1189 GSocketError
GSocketBSD::Output_Timeout()
1195 /* Linux select() will overwrite the struct on return */
1196 tv
.tv_sec
= (m_timeout
/ 1000);
1197 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1199 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1201 if (!m_non_blocking
)
1204 FD_SET(m_fd
, &writefds
);
1205 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1208 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1209 m_error
= GSOCK_TIMEDOUT
;
1210 return GSOCK_TIMEDOUT
;
1214 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1215 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1216 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1217 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1218 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1219 m_error
= GSOCK_TIMEDOUT
;
1220 return GSOCK_TIMEDOUT
;
1222 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1223 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1226 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1231 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1234 return GSOCK_NOERROR
;
1237 int GSocketBSD::Recv_Stream(char *buffer
, int size
)
1239 return recv(m_fd
, buffer
, size
, 0);
1242 int GSocketBSD::Recv_Dgram(char *buffer
, int size
)
1244 struct sockaddr from
;
1245 SOCKLEN_T fromlen
= sizeof(from
);
1249 fromlen
= sizeof(from
);
1251 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1256 /* Translate a system address into a GSocket address */
1259 m_peer
= GAddress_new();
1262 m_error
= GSOCK_MEMERR
;
1266 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1267 if (err
!= GSOCK_NOERROR
)
1269 GAddress_destroy(m_peer
);
1278 int GSocketBSD::Send_Stream(const char *buffer
, int size
)
1282 #ifndef __VISAGECPP__
1284 ret
= send(m_fd
, buffer
, size
, 0);
1287 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1293 int GSocketBSD::Send_Dgram(const char *buffer
, int size
)
1295 struct sockaddr
*addr
;
1301 m_error
= GSOCK_INVADDR
;
1305 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1306 if (err
!= GSOCK_NOERROR
)
1312 #ifndef __VISAGECPP__
1314 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1317 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1320 /* Frees memory allocated from _GAddress_translate_to */
1326 void GSocketBSD::Detected_Read()
1330 /* If we have already detected a LOST event, then don't try
1331 * to do any further processing.
1333 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1335 m_establishing
= FALSE
;
1337 CALL_CALLBACK(GSOCK_LOST
);
1342 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1344 CALL_CALLBACK(GSOCK_INPUT
);
1348 if (m_server
&& m_stream
)
1350 CALL_CALLBACK(GSOCK_CONNECTION
);
1354 CALL_CALLBACK(GSOCK_LOST
);
1360 void GSocketBSD::Detected_Write()
1362 /* If we have already detected a LOST event, then don't try
1363 * to do any further processing.
1365 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1367 m_establishing
= FALSE
;
1369 CALL_CALLBACK(GSOCK_LOST
);
1374 if (m_establishing
&& !m_server
)
1377 SOCKLEN_T len
= sizeof(error
);
1379 m_establishing
= FALSE
;
1381 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1385 CALL_CALLBACK(GSOCK_LOST
);
1390 CALL_CALLBACK(GSOCK_CONNECTION
);
1391 /* We have to fire this event by hand because CONNECTION (for clients)
1392 * and OUTPUT are internally the same and we just disabled CONNECTION
1393 * events with the above macro.
1395 CALL_CALLBACK(GSOCK_OUTPUT
);
1400 CALL_CALLBACK(GSOCK_OUTPUT
);
1404 /* Compatibility functions for GSocket */
1405 GSocket
*GSocket_new(void)
1407 GSocket
*newsocket
= new GSocketBSDGUIShim();
1408 if(newsocket
->IsOk())
1414 void GSocket_destroy(GSocket
*socket
)
1418 /* Check that the socket is really shutdowned */
1419 if (socket
->m_fd
!= INVALID_SOCKET
)
1425 void GSocketBSD::_GSocket_Detected_Read(GSocket
*socket
)
1426 { socket
->Detected_Read(); }
1428 void GSocketBSD::_GSocket_Detected_Write(GSocket
*socket
)
1429 { socket
->Detected_Write(); }
1432 * -------------------------------------------------------------------------
1434 * -------------------------------------------------------------------------
1437 /* CHECK_ADDRESS verifies that the current address family is either
1438 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1439 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1440 * an appropiate error code.
1442 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1444 #define CHECK_ADDRESS(address, family) \
1446 if (address->m_family == GSOCK_NOFAMILY) \
1447 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1448 return address->m_error; \
1449 if (address->m_family != GSOCK_##family) \
1451 address->m_error = GSOCK_INVADDR; \
1452 return GSOCK_INVADDR; \
1456 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1458 if (address->m_family == GSOCK_NOFAMILY) \
1459 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1461 if (address->m_family != GSOCK_##family) \
1463 address->m_error = GSOCK_INVADDR; \
1469 GAddress
*GAddress_new(void)
1473 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1476 address
->m_family
= GSOCK_NOFAMILY
;
1477 address
->m_addr
= NULL
;
1483 GAddress
*GAddress_copy(GAddress
*address
)
1487 assert(address
!= NULL
);
1489 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1492 memcpy(addr2
, address
, sizeof(GAddress
));
1494 if (address
->m_addr
&& address
->m_len
> 0)
1496 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1497 if (addr2
->m_addr
== NULL
)
1502 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1508 void GAddress_destroy(GAddress
*address
)
1510 assert(address
!= NULL
);
1512 if (address
->m_addr
)
1513 free(address
->m_addr
);
1518 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1520 assert(address
!= NULL
);
1522 address
->m_family
= type
;
1525 GAddressType
GAddress_GetFamily(GAddress
*address
)
1527 assert(address
!= NULL
);
1529 return address
->m_family
;
1532 GSocketError
_GAddress_translate_from(GAddress
*address
,
1533 struct sockaddr
*addr
, int len
)
1535 address
->m_realfamily
= addr
->sa_family
;
1536 switch (addr
->sa_family
)
1539 address
->m_family
= GSOCK_INET
;
1542 address
->m_family
= GSOCK_UNIX
;
1546 address
->m_family
= GSOCK_INET6
;
1551 address
->m_error
= GSOCK_INVOP
;
1556 if (address
->m_addr
)
1557 free(address
->m_addr
);
1559 address
->m_len
= len
;
1560 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1562 if (address
->m_addr
== NULL
)
1564 address
->m_error
= GSOCK_MEMERR
;
1565 return GSOCK_MEMERR
;
1567 memcpy(address
->m_addr
, addr
, len
);
1569 return GSOCK_NOERROR
;
1572 GSocketError
_GAddress_translate_to(GAddress
*address
,
1573 struct sockaddr
**addr
, int *len
)
1575 if (!address
->m_addr
)
1577 address
->m_error
= GSOCK_INVADDR
;
1578 return GSOCK_INVADDR
;
1581 *len
= address
->m_len
;
1582 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1585 address
->m_error
= GSOCK_MEMERR
;
1586 return GSOCK_MEMERR
;
1589 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1590 return GSOCK_NOERROR
;
1594 * -------------------------------------------------------------------------
1595 * Internet address family
1596 * -------------------------------------------------------------------------
1599 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1601 address
->m_len
= sizeof(struct sockaddr_in
);
1602 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1603 if (address
->m_addr
== NULL
)
1605 address
->m_error
= GSOCK_MEMERR
;
1606 return GSOCK_MEMERR
;
1609 address
->m_family
= GSOCK_INET
;
1610 address
->m_realfamily
= PF_INET
;
1611 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1612 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1614 return GSOCK_NOERROR
;
1617 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1620 struct in_addr
*addr
;
1622 assert(address
!= NULL
);
1624 CHECK_ADDRESS(address
, INET
);
1626 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1628 /* If it is a numeric host name, convert it now */
1629 #if defined(HAVE_INET_ATON)
1630 if (inet_aton(hostname
, addr
) == 0)
1632 #elif defined(HAVE_INET_ADDR)
1633 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1636 /* Use gethostbyname by default */
1637 int val
= 1; //VA doesn't like constants in conditional expressions at all
1641 struct in_addr
*array_addr
;
1643 /* It is a real name, we solve it */
1644 if ((he
= gethostbyname(hostname
)) == NULL
)
1646 /* Reset to invalid address */
1647 addr
->s_addr
= INADDR_NONE
;
1648 address
->m_error
= GSOCK_NOHOST
;
1649 return GSOCK_NOHOST
;
1651 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1652 addr
->s_addr
= array_addr
[0].s_addr
;
1654 return GSOCK_NOERROR
;
1657 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1659 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1662 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1663 unsigned long hostaddr
)
1665 struct in_addr
*addr
;
1667 assert(address
!= NULL
);
1669 CHECK_ADDRESS(address
, INET
);
1671 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1672 addr
->s_addr
= hostaddr
;
1674 return GSOCK_NOERROR
;
1677 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1678 const char *protocol
)
1681 struct sockaddr_in
*addr
;
1683 assert(address
!= NULL
);
1684 CHECK_ADDRESS(address
, INET
);
1688 address
->m_error
= GSOCK_INVPORT
;
1689 return GSOCK_INVPORT
;
1692 se
= getservbyname(port
, protocol
);
1695 /* the cast to int suppresses compiler warnings about subscript having the
1697 if (isdigit((int)port
[0]))
1701 port_int
= atoi(port
);
1702 addr
= (struct sockaddr_in
*)address
->m_addr
;
1703 addr
->sin_port
= htons(port_int
);
1704 return GSOCK_NOERROR
;
1707 address
->m_error
= GSOCK_INVPORT
;
1708 return GSOCK_INVPORT
;
1711 addr
= (struct sockaddr_in
*)address
->m_addr
;
1712 addr
->sin_port
= se
->s_port
;
1714 return GSOCK_NOERROR
;
1717 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1719 struct sockaddr_in
*addr
;
1721 assert(address
!= NULL
);
1722 CHECK_ADDRESS(address
, INET
);
1724 addr
= (struct sockaddr_in
*)address
->m_addr
;
1725 addr
->sin_port
= htons(port
);
1727 return GSOCK_NOERROR
;
1730 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1734 struct sockaddr_in
*addr
;
1736 assert(address
!= NULL
);
1737 CHECK_ADDRESS(address
, INET
);
1739 addr
= (struct sockaddr_in
*)address
->m_addr
;
1740 addr_buf
= (char *)&(addr
->sin_addr
);
1742 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1745 address
->m_error
= GSOCK_NOHOST
;
1746 return GSOCK_NOHOST
;
1749 strncpy(hostname
, he
->h_name
, sbuf
);
1751 return GSOCK_NOERROR
;
1754 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1756 struct sockaddr_in
*addr
;
1758 assert(address
!= NULL
);
1759 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1761 addr
= (struct sockaddr_in
*)address
->m_addr
;
1763 return addr
->sin_addr
.s_addr
;
1766 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1768 struct sockaddr_in
*addr
;
1770 assert(address
!= NULL
);
1771 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1773 addr
= (struct sockaddr_in
*)address
->m_addr
;
1774 return ntohs(addr
->sin_port
);
1778 * -------------------------------------------------------------------------
1779 * Unix address family
1780 * -------------------------------------------------------------------------
1783 #ifndef __VISAGECPP__
1784 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1786 address
->m_len
= sizeof(struct sockaddr_un
);
1787 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1788 if (address
->m_addr
== NULL
)
1790 address
->m_error
= GSOCK_MEMERR
;
1791 return GSOCK_MEMERR
;
1794 address
->m_family
= GSOCK_UNIX
;
1795 address
->m_realfamily
= PF_UNIX
;
1796 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1797 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1799 return GSOCK_NOERROR
;
1802 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1804 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1806 struct sockaddr_un
*addr
;
1808 assert(address
!= NULL
);
1810 CHECK_ADDRESS(address
, UNIX
);
1812 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1813 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1814 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1816 return GSOCK_NOERROR
;
1819 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1821 struct sockaddr_un
*addr
;
1823 assert(address
!= NULL
);
1824 CHECK_ADDRESS(address
, UNIX
);
1826 addr
= (struct sockaddr_un
*)address
->m_addr
;
1828 strncpy(path
, addr
->sun_path
, sbuf
);
1830 return GSOCK_NOERROR
;
1832 #endif /* !defined(__VISAGECPP__) */
1833 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */