1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Authors: Guilhem Lavaux,
5 * Guillermo Rodriguez Garcia <guille@iies.es> (maintainer)
6 * Purpose: GSocket main Unix and OS/2 file
7 * Licence: The wxWindows licence
9 * -------------------------------------------------------------------------
12 #ifndef __GSOCKET_STANDALONE__
16 #if defined(__VISAGECPP__)
17 /* Seems to be needed by Visual Age C++, though I don't see how it manages
18 to not break on including a C++ header into a plain C source file */
20 #define BSD_SELECT /* use Berkley Sockets select */
23 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
26 #include <sys/types.h>
31 #include <netinet/in.h>
34 #include <sys/ioctl.h>
40 u_char sun_len
; /* sockaddr len including null */
41 u_char sun_family
; /* AF_UNIX */
42 char sun_path
[108]; /* path name (gag) */
45 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #include <arpa/inet.h>
59 #include <machine/endian.h>
65 #define EBADF SOCEBADF
71 #include <sys/socket.h>
72 #include <sys/ioctl.h>
73 #include <sys/select.h>
75 #define close(a) soclose(a)
76 #define select(a,b,c,d,e) bsdselect(a,b,c,d,e)
77 int _System
bsdselect(int,
82 int _System
soclose(int);
90 # include <sys/filio.h>
100 # define SOCKLEN_T unsigned int
104 # define SOCKLEN_T socklen_t
107 # define SOCKLEN_T int
111 #endif /* SOCKLEN_T */
114 * MSW defines this, Unices don't.
116 #ifndef INVALID_SOCKET
117 #define INVALID_SOCKET -1
120 /* UnixWare reportedly needs this for FIONBIO definition */
122 #include <sys/filio.h>
126 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
127 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
130 #define INADDR_NONE INADDR_BROADCAST
133 #define MASK_SIGNAL() \
135 void (*old_handler)(int); \
137 old_handler = signal(SIGPIPE, SIG_IGN);
139 #define UNMASK_SIGNAL() \
140 signal(SIGPIPE, old_handler); \
144 #ifndef __GSOCKET_STANDALONE__
145 # include "wx/unix/gsockunx.h"
146 # include "wx/gsocket.h"
148 # include "gsockunx.h"
149 # include "gsocket.h"
150 #endif /* __GSOCKET_STANDALONE__ */
152 /* debugging helpers */
153 #ifdef __GSOCKET_DEBUG__
154 # define GSocket_Debug(args) printf args
156 # define GSocket_Debug(args)
157 #endif /* __GSOCKET_DEBUG__ */
159 /* Table of GUI-related functions. We must call them indirectly because
160 * of wxBase and GUI separation: */
162 static struct GSocketGUIFunctionsTable
*gs_gui_functions
;
164 #define USE_GUI() (gs_gui_functions != NULL)
166 /* Define macros to simplify indirection: */
167 #define _GSocket_GUI_Init() \
168 if (gs_gui_functions) gs_gui_functions->GUI_Init()
169 #define _GSocket_GUI_Cleanup() \
170 if (gs_gui_functions) gs_gui_functions->GUI_Cleanup()
171 #define _GSocket_GUI_Init_Socket(socket) \
172 (gs_gui_functions ? gs_gui_functions->GUI_Init_Socket(socket) : 1)
173 #define _GSocket_GUI_Destroy_Socket(socket) \
174 if (gs_gui_functions) gs_gui_functions->GUI_Destroy_Socket(socket)
175 #define _GSocket_Enable_Events(socket) \
176 if (gs_gui_functions) gs_gui_functions->Enable_Events(socket)
177 #define _GSocket_Disable_Events(socket) \
178 if (gs_gui_functions) gs_gui_functions->Disable_Events(socket)
179 #define _GSocket_Install_Callback(socket, event) \
180 if (gs_gui_functions) gs_gui_functions->Install_Callback(socket, event)
181 #define _GSocket_Uninstall_Callback(socket, event) \
182 if (gs_gui_functions) gs_gui_functions->Uninstall_Callback(socket, event)
184 static struct GSocketBaseFunctionsTable gs_base_functions
=
186 GSocketBSD::_GSocket_Detected_Read
,
187 GSocketBSD::_GSocket_Detected_Write
190 /* Global initialisers */
192 void GSocket_SetGUIFunctions(struct GSocketGUIFunctionsTable
*guifunc
)
194 gs_gui_functions
= guifunc
;
197 int GSocket_Init(void)
199 if (gs_gui_functions
)
201 if ( !gs_gui_functions
->GUI_Init() )
207 void GSocket_Cleanup(void)
209 if (gs_gui_functions
)
211 gs_gui_functions
->GUI_Cleanup();
215 GSocketBSD::GSocketBSD()
219 m_fd
= INVALID_SOCKET
;
220 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
227 m_error
= GSOCK_NOERROR
;
230 m_gui_dependent
= NULL
;
231 m_non_blocking
= FALSE
;
232 m_timeout
= 10*60*1000;
233 /* 10 minutes * 60 sec * 1000 millisec */
234 m_establishing
= FALSE
;
236 m_functions
= &gs_base_functions
;
238 /* Per-socket GUI-specific initialization */
239 m_ok
= _GSocket_GUI_Init_Socket(this);
242 void GSocketBSD::Close()
244 _GSocket_Disable_Events(this);
245 // gsockosx.c calls CFSocketInvalidate which closes the socket for us
246 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
249 m_fd
= INVALID_SOCKET
;
252 GSocketBSD::~GSocketBSD()
256 /* Check that the socket is really shutdowned */
257 if (m_fd
!= INVALID_SOCKET
)
260 /* Per-socket GUI-specific cleanup */
261 _GSocket_GUI_Destroy_Socket(this);
263 /* Destroy private addresses */
265 GAddress_destroy(m_local
);
268 GAddress_destroy(m_peer
);
272 * Disallow further read/write operations on this socket, close
273 * the fd and disable all callbacks.
275 void GSocketBSD::Shutdown()
281 /* If socket has been created, shutdown it */
282 if (m_fd
!= INVALID_SOCKET
)
288 /* Disable GUI callbacks */
289 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
290 m_cbacks
[evt
] = NULL
;
292 m_detected
= GSOCK_LOST_FLAG
;
295 /* Address handling */
301 * Set or get the local or peer address for this socket. The 'set'
302 * functions return GSOCK_NOERROR on success, an error code otherwise.
303 * The 'get' functions return a pointer to a GAddress object on success,
304 * or NULL otherwise, in which case they set the error code of the
305 * corresponding GSocket.
308 * GSOCK_INVSOCK - the socket is not valid.
309 * GSOCK_INVADDR - the address is not valid.
311 GSocketError
GSocketBSD::SetLocal(GAddress
*address
)
315 /* the socket must be initialized, or it must be a server */
316 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
318 m_error
= GSOCK_INVSOCK
;
319 return GSOCK_INVSOCK
;
323 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
325 m_error
= GSOCK_INVADDR
;
326 return GSOCK_INVADDR
;
330 GAddress_destroy(m_local
);
332 m_local
= GAddress_copy(address
);
334 return GSOCK_NOERROR
;
337 GSocketError
GSocketBSD::SetPeer(GAddress
*address
)
342 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
344 m_error
= GSOCK_INVADDR
;
345 return GSOCK_INVADDR
;
349 GAddress_destroy(m_peer
);
351 m_peer
= GAddress_copy(address
);
353 return GSOCK_NOERROR
;
356 GAddress
*GSocketBSD::GetLocal()
359 struct sockaddr addr
;
360 SOCKLEN_T size
= sizeof(addr
);
365 /* try to get it from the m_local var first */
367 return GAddress_copy(m_local
);
369 /* else, if the socket is initialized, try getsockname */
370 if (m_fd
== INVALID_SOCKET
)
372 m_error
= GSOCK_INVSOCK
;
376 if (getsockname(m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
378 m_error
= GSOCK_IOERR
;
382 /* got a valid address from getsockname, create a GAddress object */
383 address
= GAddress_new();
386 m_error
= GSOCK_MEMERR
;
390 err
= _GAddress_translate_from(address
, &addr
, size
);
391 if (err
!= GSOCK_NOERROR
)
393 GAddress_destroy(address
);
401 GAddress
*GSocketBSD::GetPeer()
405 /* try to get it from the m_peer var */
407 return GAddress_copy(m_peer
);
412 /* Server specific parts */
414 /* GSocket_SetServer:
415 * Sets up this socket as a server. The local address must have been
416 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
417 * Returns GSOCK_NOERROR on success, one of the following otherwise:
420 * GSOCK_INVSOCK - the socket is in use.
421 * GSOCK_INVADDR - the local address has not been set.
422 * GSOCK_IOERR - low-level error.
424 GSocketError
GSocketBSD::SetServer()
430 /* must not be in use */
431 if (m_fd
!= INVALID_SOCKET
)
433 m_error
= GSOCK_INVSOCK
;
434 return GSOCK_INVSOCK
;
437 /* the local addr must have been set */
440 m_error
= GSOCK_INVADDR
;
441 return GSOCK_INVADDR
;
444 /* Initialize all fields */
449 /* Create the socket */
450 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
452 if (m_fd
== INVALID_SOCKET
)
454 m_error
= GSOCK_IOERR
;
457 #if defined(__EMX__) || defined(__VISAGECPP__)
458 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
460 ioctl(m_fd
, FIONBIO
, &arg
);
462 _GSocket_Enable_Events(this);
464 /* allow a socket to re-bind if the socket is in the TIME_WAIT
465 state after being previously closed.
467 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
469 /* Bind to the local address,
470 * retrieve the actual address bound,
471 * and listen up to 5 connections.
473 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
476 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
477 (listen(m_fd
, 5) != 0))
480 m_error
= GSOCK_IOERR
;
484 return GSOCK_NOERROR
;
487 /* GSocket_WaitConnection:
488 * Waits for an incoming client connection. Returns a pointer to
489 * a GSocket object, or NULL if there was an error, in which case
490 * the last error field will be updated for the calling GSocket.
492 * Error codes (set in the calling GSocket)
493 * GSOCK_INVSOCK - the socket is not valid or not a server.
494 * GSOCK_TIMEDOUT - timeout, no incoming connections.
495 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
496 * GSOCK_MEMERR - couldn't allocate memory.
497 * GSOCK_IOERR - low-level error.
499 GSocket
*GSocketBSD::WaitConnection()
501 struct sockaddr from
;
502 SOCKLEN_T fromlen
= sizeof(from
);
509 /* Reenable CONNECTION events */
510 Enable(GSOCK_CONNECTION
);
512 /* If the socket has already been created, we exit immediately */
513 if (m_fd
== INVALID_SOCKET
|| !m_server
)
515 m_error
= GSOCK_INVSOCK
;
519 /* Create a GSocket object for the new connection */
520 connection
= new GSocketBSD();
522 if (!connection
->IsOk())
525 m_error
= GSOCK_MEMERR
;
529 /* Wait for a connection (with timeout) */
530 if (Input_Timeout() == GSOCK_TIMEDOUT
)
533 /* m_error set by _GSocket_Input_Timeout */
537 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
539 if (connection
->m_fd
== INVALID_SOCKET
)
541 if (errno
== EWOULDBLOCK
)
542 m_error
= GSOCK_WOULDBLOCK
;
544 m_error
= GSOCK_IOERR
;
550 /* Initialize all fields */
551 connection
->m_server
= FALSE
;
552 connection
->m_stream
= TRUE
;
553 connection
->m_oriented
= TRUE
;
555 /* Setup the peer address field */
556 connection
->m_peer
= GAddress_new();
557 if (!connection
->m_peer
)
560 m_error
= GSOCK_MEMERR
;
563 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
564 if (err
!= GSOCK_NOERROR
)
566 GAddress_destroy(connection
->m_peer
);
571 #if defined(__EMX__) || defined(__VISAGECPP__)
572 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
574 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
576 _GSocket_Enable_Events(connection
);
581 /* Client specific parts */
584 * For stream (connection oriented) sockets, GSocket_Connect() tries
585 * to establish a client connection to a server using the peer address
586 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
587 * connection has been succesfully established, or one of the error
588 * codes listed below. Note that for nonblocking sockets, a return
589 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
590 * request can be completed later; you should use GSocket_Select()
591 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
592 * corresponding asynchronous events.
594 * For datagram (non connection oriented) sockets, GSocket_Connect()
595 * just sets the peer address established with GSocket_SetPeer() as
596 * default destination.
599 * GSOCK_INVSOCK - the socket is in use or not valid.
600 * GSOCK_INVADDR - the peer address has not been established.
601 * GSOCK_TIMEDOUT - timeout, the connection failed.
602 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
603 * GSOCK_MEMERR - couldn't allocate memory.
604 * GSOCK_IOERR - low-level error.
606 GSocketError
GSocketBSD::Connect(GSocketStream stream
)
613 /* Enable CONNECTION events (needed for nonblocking connections) */
614 Enable(GSOCK_CONNECTION
);
616 if (m_fd
!= INVALID_SOCKET
)
618 m_error
= GSOCK_INVSOCK
;
619 return GSOCK_INVSOCK
;
624 m_error
= GSOCK_INVADDR
;
625 return GSOCK_INVADDR
;
628 /* Streamed or dgram socket? */
629 m_stream
= (stream
== GSOCK_STREAMED
);
632 m_establishing
= FALSE
;
634 /* Create the socket */
635 m_fd
= socket(m_peer
->m_realfamily
,
636 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
638 if (m_fd
== INVALID_SOCKET
)
640 m_error
= GSOCK_IOERR
;
643 #if defined(__EMX__) || defined(__VISAGECPP__)
644 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
646 ioctl(m_fd
, FIONBIO
, &arg
);
648 _GSocket_Enable_Events(this);
650 /* Connect it to the peer address, with a timeout (see below) */
651 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
657 /* If connect failed with EINPROGRESS and the GSocket object
658 * is in blocking mode, we select() for the specified timeout
659 * checking for writability to see if the connection request
662 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
664 if (Output_Timeout() == GSOCK_TIMEDOUT
)
667 /* m_error is set in _GSocket_Output_Timeout */
668 return GSOCK_TIMEDOUT
;
673 SOCKLEN_T len
= sizeof(error
);
675 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
678 return GSOCK_NOERROR
;
682 /* If connect failed with EINPROGRESS and the GSocket object
683 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
684 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
685 * this way if the connection completes, a GSOCK_CONNECTION
686 * event will be generated, if enabled.
688 if ((err
== EINPROGRESS
) && (m_non_blocking
))
690 m_establishing
= TRUE
;
691 m_error
= GSOCK_WOULDBLOCK
;
692 return GSOCK_WOULDBLOCK
;
695 /* If connect failed with an error other than EINPROGRESS,
696 * then the call to GSocket_Connect has failed.
699 m_error
= GSOCK_IOERR
;
703 return GSOCK_NOERROR
;
706 /* Datagram sockets */
708 /* GSocket_SetNonOriented:
709 * Sets up this socket as a non-connection oriented (datagram) socket.
710 * Before using this function, the local address must have been set
711 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
712 * on success, or one of the following otherwise.
715 * GSOCK_INVSOCK - the socket is in use.
716 * GSOCK_INVADDR - the local address has not been set.
717 * GSOCK_IOERR - low-level error.
719 GSocketError
GSocketBSD::SetNonOriented()
725 if (m_fd
!= INVALID_SOCKET
)
727 m_error
= GSOCK_INVSOCK
;
728 return GSOCK_INVSOCK
;
733 m_error
= GSOCK_INVADDR
;
734 return GSOCK_INVADDR
;
737 /* Initialize all fields */
742 /* Create the socket */
743 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
745 if (m_fd
== INVALID_SOCKET
)
747 m_error
= GSOCK_IOERR
;
750 #if defined(__EMX__) || defined(__VISAGECPP__)
751 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
753 ioctl(m_fd
, FIONBIO
, &arg
);
755 _GSocket_Enable_Events(this);
757 /* Bind to the local address,
758 * and retrieve the actual address bound.
760 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
763 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
766 m_error
= GSOCK_IOERR
;
770 return GSOCK_NOERROR
;
775 /* Like recv(), send(), ... */
776 int GSocketBSD::Read(char *buffer
, int size
)
782 /* When using CFSocket we MUST NOT reenable events until we finish reading */
784 /* Reenable INPUT events */
788 if (m_fd
== INVALID_SOCKET
|| m_server
)
790 m_error
= GSOCK_INVSOCK
;
794 /* If the socket is blocking, wait for data (with a timeout) */
795 if (Input_Timeout() == GSOCK_TIMEDOUT
)
800 ret
= Recv_Stream(buffer
, size
);
802 ret
= Recv_Dgram(buffer
, size
);
806 if (errno
== EWOULDBLOCK
)
807 m_error
= GSOCK_WOULDBLOCK
;
809 m_error
= GSOCK_IOERR
;
813 /* Reenable INPUT events */
820 int GSocketBSD::Write(const char *buffer
, int size
)
826 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
828 if (m_fd
== INVALID_SOCKET
|| m_server
)
830 m_error
= GSOCK_INVSOCK
;
834 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
836 /* If the socket is blocking, wait for writability (with a timeout) */
837 if (Output_Timeout() == GSOCK_TIMEDOUT
)
840 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
844 ret
= Send_Stream(buffer
, size
);
846 ret
= Send_Dgram(buffer
, size
);
848 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
852 if (errno
== EWOULDBLOCK
)
854 m_error
= GSOCK_WOULDBLOCK
;
855 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
859 m_error
= GSOCK_IOERR
;
860 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
863 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
864 * in MSW). Once the first OUTPUT event is received, users can assume
865 * that the socket is writable until a read operation fails. Only then
866 * will further OUTPUT events be posted.
868 Enable(GSOCK_OUTPUT
);
872 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
878 * Polls the socket to determine its status. This function will
879 * check for the events specified in the 'flags' parameter, and
880 * it will return a mask indicating which operations can be
881 * performed. This function won't block, regardless of the
882 * mode (blocking | nonblocking) of the socket.
884 GSocketEventFlags
GSocketBSD::Select(GSocketEventFlags flags
)
889 GSocketEventFlags result
= 0;
895 /* Do not use a static struct, Linux can garble it */
896 tv
.tv_sec
= m_timeout
/ 1000;
897 tv
.tv_usec
= (m_timeout
% 1000) / 1000;
904 FD_SET(m_fd
, &readfds
);
905 if (flags
& GSOCK_OUTPUT_FLAG
)
906 FD_SET(m_fd
, &writefds
);
907 FD_SET(m_fd
, &exceptfds
);
909 /* Check 'sticky' CONNECTION flag first */
910 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
912 /* If we have already detected a LOST event, then don't try
913 * to do any further processing.
915 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
917 m_establishing
= FALSE
;
919 return (GSOCK_LOST_FLAG
& flags
);
923 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
925 /* What to do here? */
926 return (result
& flags
);
929 /* Check for readability */
930 if (FD_ISSET(m_fd
, &readfds
))
934 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
936 result
|= GSOCK_INPUT_FLAG
;
940 if (m_server
&& m_stream
)
942 result
|= GSOCK_CONNECTION_FLAG
;
943 m_detected
|= GSOCK_CONNECTION_FLAG
;
947 m_detected
= GSOCK_LOST_FLAG
;
948 m_establishing
= FALSE
;
950 /* LOST event: Abort any further processing */
951 return (GSOCK_LOST_FLAG
& flags
);
956 /* Check for writability */
957 if (FD_ISSET(m_fd
, &writefds
))
959 if (m_establishing
&& !m_server
)
962 SOCKLEN_T len
= sizeof(error
);
964 m_establishing
= FALSE
;
966 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
970 m_detected
= GSOCK_LOST_FLAG
;
972 /* LOST event: Abort any further processing */
973 return (GSOCK_LOST_FLAG
& flags
);
977 result
|= GSOCK_CONNECTION_FLAG
;
978 m_detected
|= GSOCK_CONNECTION_FLAG
;
983 result
|= GSOCK_OUTPUT_FLAG
;
987 /* Check for exceptions and errors (is this useful in Unices?) */
988 if (FD_ISSET(m_fd
, &exceptfds
))
990 m_establishing
= FALSE
;
991 m_detected
= GSOCK_LOST_FLAG
;
993 /* LOST event: Abort any further processing */
994 return (GSOCK_LOST_FLAG
& flags
);
997 return (result
& flags
);
1004 return flags
& m_detected
;
1011 /* GSocket_SetNonBlocking:
1012 * Sets the socket to non-blocking mode. All IO calls will return
1015 void GSocketBSD::SetNonBlocking(int non_block
)
1019 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1021 m_non_blocking
= non_block
;
1024 /* GSocket_SetTimeout:
1025 * Sets the timeout for blocking calls. Time is expressed in
1028 void GSocketBSD::SetTimeout(unsigned long millisec
)
1032 m_timeout
= millisec
;
1035 /* GSocket_GetError:
1036 * Returns the last error occured for this socket. Note that successful
1037 * operations do not clear this back to GSOCK_NOERROR, so use it only
1040 GSocketError
GSocketBSD::GetError()
1050 * There is data to be read in the input buffer. If, after a read
1051 * operation, there is still data available, the callback function will
1054 * The socket is available for writing. That is, the next write call
1055 * won't block. This event is generated only once, when the connection is
1056 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1057 * when the output buffer empties again. This means that the app should
1058 * assume that it can write since the first OUTPUT event, and no more
1059 * OUTPUT events will be generated unless an error occurs.
1061 * Connection succesfully established, for client sockets, or incoming
1062 * client connection, for server sockets. Wait for this event (also watch
1063 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1065 * The connection is lost (or a connection request failed); this could
1066 * be due to a failure, or due to the peer closing it gracefully.
1069 /* GSocket_SetCallback:
1070 * Enables the callbacks specified by 'flags'. Note that 'flags'
1071 * may be a combination of flags OR'ed toghether, so the same
1072 * callback function can be made to accept different events.
1073 * The callback function must have the following prototype:
1075 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1077 void GSocketBSD::SetCallback(GSocketEventFlags flags
,
1078 GSocketCallback callback
, char *cdata
)
1084 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1086 if ((flags
& (1 << count
)) != 0)
1088 m_cbacks
[count
] = callback
;
1089 m_data
[count
] = cdata
;
1094 /* GSocket_UnsetCallback:
1095 * Disables all callbacks specified by 'flags', which may be a
1096 * combination of flags OR'ed toghether.
1098 void GSocketBSD::UnsetCallback(GSocketEventFlags flags
)
1104 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1106 if ((flags
& (1 << count
)) != 0)
1108 m_cbacks
[count
] = NULL
;
1109 m_data
[count
] = NULL
;
1115 #define CALL_CALLBACK(event) { \
1117 if (m_cbacks[event]) \
1118 m_cbacks[event](this, event, m_data[event]); \
1122 void GSocketBSD::Enable(GSocketEvent event
)
1124 m_detected
&= ~(1 << event
);
1125 _GSocket_Install_Callback(this, event
);
1128 void GSocketBSD::Disable(GSocketEvent event
)
1130 m_detected
|= (1 << event
);
1131 _GSocket_Uninstall_Callback(this, event
);
1134 /* _GSocket_Input_Timeout:
1135 * For blocking sockets, wait until data is available or
1136 * until timeout ellapses.
1138 GSocketError
GSocketBSD::Input_Timeout()
1144 /* Linux select() will overwrite the struct on return */
1145 tv
.tv_sec
= (m_timeout
/ 1000);
1146 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1148 if (!m_non_blocking
)
1151 FD_SET(m_fd
, &readfds
);
1152 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1155 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1156 m_error
= GSOCK_TIMEDOUT
;
1157 return GSOCK_TIMEDOUT
;
1161 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1162 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1163 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1164 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1165 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1166 m_error
= GSOCK_TIMEDOUT
;
1167 return GSOCK_TIMEDOUT
;
1170 return GSOCK_NOERROR
;
1173 /* _GSocket_Output_Timeout:
1174 * For blocking sockets, wait until data can be sent without
1175 * blocking or until timeout ellapses.
1177 GSocketError
GSocketBSD::Output_Timeout()
1183 /* Linux select() will overwrite the struct on return */
1184 tv
.tv_sec
= (m_timeout
/ 1000);
1185 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1187 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1189 if (!m_non_blocking
)
1192 FD_SET(m_fd
, &writefds
);
1193 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1196 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1197 m_error
= GSOCK_TIMEDOUT
;
1198 return GSOCK_TIMEDOUT
;
1202 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1203 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1204 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1205 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1206 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1207 m_error
= GSOCK_TIMEDOUT
;
1208 return GSOCK_TIMEDOUT
;
1210 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1211 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1214 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1219 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1222 return GSOCK_NOERROR
;
1225 int GSocketBSD::Recv_Stream(char *buffer
, int size
)
1227 return recv(m_fd
, buffer
, size
, 0);
1230 int GSocketBSD::Recv_Dgram(char *buffer
, int size
)
1232 struct sockaddr from
;
1233 SOCKLEN_T fromlen
= sizeof(from
);
1237 fromlen
= sizeof(from
);
1239 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1244 /* Translate a system address into a GSocket address */
1247 m_peer
= GAddress_new();
1250 m_error
= GSOCK_MEMERR
;
1254 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1255 if (err
!= GSOCK_NOERROR
)
1257 GAddress_destroy(m_peer
);
1266 int GSocketBSD::Send_Stream(const char *buffer
, int size
)
1270 #ifndef __VISAGECPP__
1272 ret
= send(m_fd
, buffer
, size
, 0);
1275 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1281 int GSocketBSD::Send_Dgram(const char *buffer
, int size
)
1283 struct sockaddr
*addr
;
1289 m_error
= GSOCK_INVADDR
;
1293 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1294 if (err
!= GSOCK_NOERROR
)
1300 #ifndef __VISAGECPP__
1302 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1305 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1308 /* Frees memory allocated from _GAddress_translate_to */
1314 void GSocketBSD::Detected_Read()
1318 /* If we have already detected a LOST event, then don't try
1319 * to do any further processing.
1321 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1323 m_establishing
= FALSE
;
1325 CALL_CALLBACK(GSOCK_LOST
);
1330 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1332 CALL_CALLBACK(GSOCK_INPUT
);
1336 if (m_server
&& m_stream
)
1338 CALL_CALLBACK(GSOCK_CONNECTION
);
1342 CALL_CALLBACK(GSOCK_LOST
);
1348 void GSocketBSD::Detected_Write()
1350 /* If we have already detected a LOST event, then don't try
1351 * to do any further processing.
1353 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1355 m_establishing
= FALSE
;
1357 CALL_CALLBACK(GSOCK_LOST
);
1362 if (m_establishing
&& !m_server
)
1365 SOCKLEN_T len
= sizeof(error
);
1367 m_establishing
= FALSE
;
1369 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1373 CALL_CALLBACK(GSOCK_LOST
);
1378 CALL_CALLBACK(GSOCK_CONNECTION
);
1379 /* We have to fire this event by hand because CONNECTION (for clients)
1380 * and OUTPUT are internally the same and we just disabled CONNECTION
1381 * events with the above macro.
1383 CALL_CALLBACK(GSOCK_OUTPUT
);
1388 CALL_CALLBACK(GSOCK_OUTPUT
);
1392 /* Compatibility functions for GSocket */
1393 GSocket
*GSocket_new(void)
1395 GSocket
*newsocket
= new GSocketBSD();
1396 if(newsocket
->IsOk())
1402 void GSocket_destroy(GSocket
*socket
)
1407 void GSocketBSD::_GSocket_Detected_Read(GSocket
*socket
)
1408 { socket
->Detected_Read(); }
1410 void GSocketBSD::_GSocket_Detected_Write(GSocket
*socket
)
1411 { socket
->Detected_Write(); }
1414 * -------------------------------------------------------------------------
1416 * -------------------------------------------------------------------------
1419 /* CHECK_ADDRESS verifies that the current address family is either
1420 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1421 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1422 * an appropiate error code.
1424 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1426 #define CHECK_ADDRESS(address, family) \
1428 if (address->m_family == GSOCK_NOFAMILY) \
1429 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1430 return address->m_error; \
1431 if (address->m_family != GSOCK_##family) \
1433 address->m_error = GSOCK_INVADDR; \
1434 return GSOCK_INVADDR; \
1438 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1440 if (address->m_family == GSOCK_NOFAMILY) \
1441 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1443 if (address->m_family != GSOCK_##family) \
1445 address->m_error = GSOCK_INVADDR; \
1451 GAddress
*GAddress_new(void)
1455 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1458 address
->m_family
= GSOCK_NOFAMILY
;
1459 address
->m_addr
= NULL
;
1465 GAddress
*GAddress_copy(GAddress
*address
)
1469 assert(address
!= NULL
);
1471 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1474 memcpy(addr2
, address
, sizeof(GAddress
));
1476 if (address
->m_addr
&& address
->m_len
> 0)
1478 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1479 if (addr2
->m_addr
== NULL
)
1484 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1490 void GAddress_destroy(GAddress
*address
)
1492 assert(address
!= NULL
);
1494 if (address
->m_addr
)
1495 free(address
->m_addr
);
1500 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1502 assert(address
!= NULL
);
1504 address
->m_family
= type
;
1507 GAddressType
GAddress_GetFamily(GAddress
*address
)
1509 assert(address
!= NULL
);
1511 return address
->m_family
;
1514 GSocketError
_GAddress_translate_from(GAddress
*address
,
1515 struct sockaddr
*addr
, int len
)
1517 address
->m_realfamily
= addr
->sa_family
;
1518 switch (addr
->sa_family
)
1521 address
->m_family
= GSOCK_INET
;
1524 address
->m_family
= GSOCK_UNIX
;
1528 address
->m_family
= GSOCK_INET6
;
1533 address
->m_error
= GSOCK_INVOP
;
1538 if (address
->m_addr
)
1539 free(address
->m_addr
);
1541 address
->m_len
= len
;
1542 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1544 if (address
->m_addr
== NULL
)
1546 address
->m_error
= GSOCK_MEMERR
;
1547 return GSOCK_MEMERR
;
1549 memcpy(address
->m_addr
, addr
, len
);
1551 return GSOCK_NOERROR
;
1554 GSocketError
_GAddress_translate_to(GAddress
*address
,
1555 struct sockaddr
**addr
, int *len
)
1557 if (!address
->m_addr
)
1559 address
->m_error
= GSOCK_INVADDR
;
1560 return GSOCK_INVADDR
;
1563 *len
= address
->m_len
;
1564 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1567 address
->m_error
= GSOCK_MEMERR
;
1568 return GSOCK_MEMERR
;
1571 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1572 return GSOCK_NOERROR
;
1576 * -------------------------------------------------------------------------
1577 * Internet address family
1578 * -------------------------------------------------------------------------
1581 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1583 address
->m_len
= sizeof(struct sockaddr_in
);
1584 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1585 if (address
->m_addr
== NULL
)
1587 address
->m_error
= GSOCK_MEMERR
;
1588 return GSOCK_MEMERR
;
1591 address
->m_family
= GSOCK_INET
;
1592 address
->m_realfamily
= PF_INET
;
1593 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1594 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1596 return GSOCK_NOERROR
;
1599 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1602 struct in_addr
*addr
;
1604 assert(address
!= NULL
);
1606 CHECK_ADDRESS(address
, INET
);
1608 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1610 /* If it is a numeric host name, convert it now */
1611 #if defined(HAVE_INET_ATON)
1612 if (inet_aton(hostname
, addr
) == 0)
1614 #elif defined(HAVE_INET_ADDR)
1615 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1618 /* Use gethostbyname by default */
1619 int val
= 1; //VA doesn't like constants in conditional expressions at all
1623 struct in_addr
*array_addr
;
1625 /* It is a real name, we solve it */
1626 if ((he
= gethostbyname(hostname
)) == NULL
)
1628 /* Reset to invalid address */
1629 addr
->s_addr
= INADDR_NONE
;
1630 address
->m_error
= GSOCK_NOHOST
;
1631 return GSOCK_NOHOST
;
1633 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1634 addr
->s_addr
= array_addr
[0].s_addr
;
1636 return GSOCK_NOERROR
;
1639 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1641 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1644 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1645 unsigned long hostaddr
)
1647 struct in_addr
*addr
;
1649 assert(address
!= NULL
);
1651 CHECK_ADDRESS(address
, INET
);
1653 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1654 addr
->s_addr
= hostaddr
;
1656 return GSOCK_NOERROR
;
1659 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1660 const char *protocol
)
1663 struct sockaddr_in
*addr
;
1665 assert(address
!= NULL
);
1666 CHECK_ADDRESS(address
, INET
);
1670 address
->m_error
= GSOCK_INVPORT
;
1671 return GSOCK_INVPORT
;
1674 se
= getservbyname(port
, protocol
);
1677 /* the cast to int suppresses compiler warnings about subscript having the
1679 if (isdigit((int)port
[0]))
1683 port_int
= atoi(port
);
1684 addr
= (struct sockaddr_in
*)address
->m_addr
;
1685 addr
->sin_port
= htons(port_int
);
1686 return GSOCK_NOERROR
;
1689 address
->m_error
= GSOCK_INVPORT
;
1690 return GSOCK_INVPORT
;
1693 addr
= (struct sockaddr_in
*)address
->m_addr
;
1694 addr
->sin_port
= se
->s_port
;
1696 return GSOCK_NOERROR
;
1699 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1701 struct sockaddr_in
*addr
;
1703 assert(address
!= NULL
);
1704 CHECK_ADDRESS(address
, INET
);
1706 addr
= (struct sockaddr_in
*)address
->m_addr
;
1707 addr
->sin_port
= htons(port
);
1709 return GSOCK_NOERROR
;
1712 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1716 struct sockaddr_in
*addr
;
1718 assert(address
!= NULL
);
1719 CHECK_ADDRESS(address
, INET
);
1721 addr
= (struct sockaddr_in
*)address
->m_addr
;
1722 addr_buf
= (char *)&(addr
->sin_addr
);
1724 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1727 address
->m_error
= GSOCK_NOHOST
;
1728 return GSOCK_NOHOST
;
1731 strncpy(hostname
, he
->h_name
, sbuf
);
1733 return GSOCK_NOERROR
;
1736 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1738 struct sockaddr_in
*addr
;
1740 assert(address
!= NULL
);
1741 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1743 addr
= (struct sockaddr_in
*)address
->m_addr
;
1745 return addr
->sin_addr
.s_addr
;
1748 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1750 struct sockaddr_in
*addr
;
1752 assert(address
!= NULL
);
1753 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1755 addr
= (struct sockaddr_in
*)address
->m_addr
;
1756 return ntohs(addr
->sin_port
);
1760 * -------------------------------------------------------------------------
1761 * Unix address family
1762 * -------------------------------------------------------------------------
1765 #ifndef __VISAGECPP__
1766 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1768 address
->m_len
= sizeof(struct sockaddr_un
);
1769 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1770 if (address
->m_addr
== NULL
)
1772 address
->m_error
= GSOCK_MEMERR
;
1773 return GSOCK_MEMERR
;
1776 address
->m_family
= GSOCK_UNIX
;
1777 address
->m_realfamily
= PF_UNIX
;
1778 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1779 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1781 return GSOCK_NOERROR
;
1784 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1786 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1788 struct sockaddr_un
*addr
;
1790 assert(address
!= NULL
);
1792 CHECK_ADDRESS(address
, UNIX
);
1794 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1795 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1796 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1798 return GSOCK_NOERROR
;
1801 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1803 struct sockaddr_un
*addr
;
1805 assert(address
!= NULL
);
1806 CHECK_ADDRESS(address
, UNIX
);
1808 addr
= (struct sockaddr_un
*)address
->m_addr
;
1810 strncpy(path
, addr
->sun_path
, sbuf
);
1812 return GSOCK_NOERROR
;
1814 #endif /* !defined(__VISAGECPP__) */
1815 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */