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.
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
;
566 /* Setup the peer address field */
567 connection
->m_peer
= GAddress_new();
568 if (!connection
->m_peer
)
571 m_error
= GSOCK_MEMERR
;
574 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
575 if (err
!= GSOCK_NOERROR
)
577 GAddress_destroy(connection
->m_peer
);
582 #if defined(__EMX__) || defined(__VISAGECPP__)
583 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
585 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
587 connection
->EventLoop_Enable_Events();
592 int GSocketBSD::SetReusable()
594 /* socket must not be null, and must not be in use/already bound */
595 if (NULL
!= this && m_fd
== INVALID_SOCKET
) {
602 /* Client specific parts */
605 * For stream (connection oriented) sockets, GSocket_Connect() tries
606 * to establish a client connection to a server using the peer address
607 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
608 * connection has been succesfully established, or one of the error
609 * codes listed below. Note that for nonblocking sockets, a return
610 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
611 * request can be completed later; you should use GSocket_Select()
612 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
613 * corresponding asynchronous events.
615 * For datagram (non connection oriented) sockets, GSocket_Connect()
616 * just sets the peer address established with GSocket_SetPeer() as
617 * default destination.
620 * GSOCK_INVSOCK - the socket is in use or not valid.
621 * GSOCK_INVADDR - the peer address has not been established.
622 * GSOCK_TIMEDOUT - timeout, the connection failed.
623 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
624 * GSOCK_MEMERR - couldn't allocate memory.
625 * GSOCK_IOERR - low-level error.
627 GSocketError
GSocketBSD::Connect(GSocketStream stream
)
634 /* Enable CONNECTION events (needed for nonblocking connections) */
635 Enable(GSOCK_CONNECTION
);
637 if (m_fd
!= INVALID_SOCKET
)
639 m_error
= GSOCK_INVSOCK
;
640 return GSOCK_INVSOCK
;
645 m_error
= GSOCK_INVADDR
;
646 return GSOCK_INVADDR
;
649 /* Streamed or dgram socket? */
650 m_stream
= (stream
== GSOCK_STREAMED
);
652 m_establishing
= FALSE
;
654 /* Create the socket */
655 m_fd
= socket(m_peer
->m_realfamily
,
656 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
658 if (m_fd
== INVALID_SOCKET
)
660 m_error
= GSOCK_IOERR
;
663 #if defined(__EMX__) || defined(__VISAGECPP__)
664 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
666 ioctl(m_fd
, FIONBIO
, &arg
);
668 EventLoop_Enable_Events();
670 /* Connect it to the peer address, with a timeout (see below) */
671 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
677 /* If connect failed with EINPROGRESS and the GSocket object
678 * is in blocking mode, we select() for the specified timeout
679 * checking for writability to see if the connection request
682 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
684 if (Output_Timeout() == GSOCK_TIMEDOUT
)
687 /* m_error is set in _GSocket_Output_Timeout */
688 return GSOCK_TIMEDOUT
;
693 SOCKLEN_T len
= sizeof(error
);
695 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
698 return GSOCK_NOERROR
;
702 /* If connect failed with EINPROGRESS and the GSocket object
703 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
704 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
705 * this way if the connection completes, a GSOCK_CONNECTION
706 * event will be generated, if enabled.
708 if ((err
== EINPROGRESS
) && (m_non_blocking
))
710 m_establishing
= TRUE
;
711 m_error
= GSOCK_WOULDBLOCK
;
712 return GSOCK_WOULDBLOCK
;
715 /* If connect failed with an error other than EINPROGRESS,
716 * then the call to GSocket_Connect has failed.
719 m_error
= GSOCK_IOERR
;
723 return GSOCK_NOERROR
;
726 /* Datagram sockets */
728 /* GSocket_SetNonOriented:
729 * Sets up this socket as a non-connection oriented (datagram) socket.
730 * Before using this function, the local address must have been set
731 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
732 * on success, or one of the following otherwise.
735 * GSOCK_INVSOCK - the socket is in use.
736 * GSOCK_INVADDR - the local address has not been set.
737 * GSOCK_IOERR - low-level error.
739 GSocketError
GSocketBSD::SetNonOriented()
745 if (m_fd
!= INVALID_SOCKET
)
747 m_error
= GSOCK_INVSOCK
;
748 return GSOCK_INVSOCK
;
753 m_error
= GSOCK_INVADDR
;
754 return GSOCK_INVADDR
;
757 /* Initialize all fields */
761 /* Create the socket */
762 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
764 if (m_fd
== INVALID_SOCKET
)
766 m_error
= GSOCK_IOERR
;
769 #if defined(__EMX__) || defined(__VISAGECPP__)
770 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
772 ioctl(m_fd
, FIONBIO
, &arg
);
774 EventLoop_Enable_Events();
776 /* Bind to the local address,
777 * and retrieve the actual address bound.
779 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
782 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
785 m_error
= GSOCK_IOERR
;
789 return GSOCK_NOERROR
;
794 /* Like recv(), send(), ... */
795 int GSocketBSD::Read(char *buffer
, int size
)
801 if (m_fd
== INVALID_SOCKET
|| m_server
)
803 m_error
= GSOCK_INVSOCK
;
807 /* Disable events during query of socket status */
808 Disable(GSOCK_INPUT
);
810 /* If the socket is blocking, wait for data (with a timeout) */
811 if (Input_Timeout() == GSOCK_TIMEDOUT
)
812 /* We no longer return here immediately, otherwise socket events would not be re-enabled! */
817 ret
= Recv_Stream(buffer
, size
);
819 ret
= Recv_Dgram(buffer
, size
);
824 if (errno
== EWOULDBLOCK
)
825 m_error
= GSOCK_WOULDBLOCK
;
827 m_error
= GSOCK_IOERR
;
830 /* Enable events again now that we are done processing */
836 int GSocketBSD::Write(const char *buffer
, int size
)
842 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
844 if (m_fd
== INVALID_SOCKET
|| m_server
)
846 m_error
= GSOCK_INVSOCK
;
850 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
852 /* If the socket is blocking, wait for writability (with a timeout) */
853 if (Output_Timeout() == GSOCK_TIMEDOUT
)
856 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
860 ret
= Send_Stream(buffer
, size
);
862 ret
= Send_Dgram(buffer
, size
);
864 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
868 if (errno
== EWOULDBLOCK
)
870 m_error
= GSOCK_WOULDBLOCK
;
871 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
875 m_error
= GSOCK_IOERR
;
876 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
879 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
880 * in MSW). Once the first OUTPUT event is received, users can assume
881 * that the socket is writable until a read operation fails. Only then
882 * will further OUTPUT events be posted.
884 Enable(GSOCK_OUTPUT
);
888 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
894 * Polls the socket to determine its status. This function will
895 * check for the events specified in the 'flags' parameter, and
896 * it will return a mask indicating which operations can be
897 * performed. This function won't block, regardless of the
898 * mode (blocking | nonblocking) of the socket.
900 GSocketEventFlags
GSocketBSD::Select(GSocketEventFlags flags
)
902 if (!GSocketBSDGUIShim::UseGUI())
905 GSocketEventFlags result
= 0;
913 /* Do not use a static struct, Linux can garble it */
914 tv
.tv_sec
= m_timeout
/ 1000;
915 tv
.tv_usec
= (m_timeout
% 1000) / 1000;
920 FD_SET(m_fd
, &readfds
);
921 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
922 FD_SET(m_fd
, &writefds
);
923 FD_SET(m_fd
, &exceptfds
);
925 /* Check 'sticky' CONNECTION flag first */
926 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
928 /* If we have already detected a LOST event, then don't try
929 * to do any further processing.
931 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
933 m_establishing
= FALSE
;
935 return (GSOCK_LOST_FLAG
& flags
);
939 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
941 /* What to do here? */
942 return (result
& flags
);
945 /* Check for readability */
946 if (FD_ISSET(m_fd
, &readfds
))
950 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
952 result
|= GSOCK_INPUT_FLAG
;
956 if (m_server
&& m_stream
)
958 result
|= GSOCK_CONNECTION_FLAG
;
959 m_detected
|= GSOCK_CONNECTION_FLAG
;
963 m_detected
= GSOCK_LOST_FLAG
;
964 m_establishing
= FALSE
;
966 /* LOST event: Abort any further processing */
967 return (GSOCK_LOST_FLAG
& flags
);
972 /* Check for writability */
973 if (FD_ISSET(m_fd
, &writefds
))
975 if (m_establishing
&& !m_server
)
978 SOCKLEN_T len
= sizeof(error
);
980 m_establishing
= FALSE
;
982 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
986 m_detected
= GSOCK_LOST_FLAG
;
988 /* LOST event: Abort any further processing */
989 return (GSOCK_LOST_FLAG
& flags
);
993 result
|= GSOCK_CONNECTION_FLAG
;
994 m_detected
|= GSOCK_CONNECTION_FLAG
;
999 result
|= GSOCK_OUTPUT_FLAG
;
1003 /* Check for exceptions and errors (is this useful in Unices?) */
1004 if (FD_ISSET(m_fd
, &exceptfds
))
1006 m_establishing
= FALSE
;
1007 m_detected
= GSOCK_LOST_FLAG
;
1009 /* LOST event: Abort any further processing */
1010 return (GSOCK_LOST_FLAG
& flags
);
1013 return (result
& flags
);
1020 return flags
& m_detected
;
1027 /* GSocket_SetNonBlocking:
1028 * Sets the socket to non-blocking mode. All IO calls will return
1031 void GSocketBSD::SetNonBlocking(int non_block
)
1035 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1037 m_non_blocking
= non_block
;
1040 /* GSocket_SetTimeout:
1041 * Sets the timeout for blocking calls. Time is expressed in
1044 void GSocketBSD::SetTimeout(unsigned long millisec
)
1048 m_timeout
= millisec
;
1051 /* GSocket_GetError:
1052 * Returns the last error occured for this socket. Note that successful
1053 * operations do not clear this back to GSOCK_NOERROR, so use it only
1056 GSocketError
GSocketBSD::GetError()
1066 * There is data to be read in the input buffer. If, after a read
1067 * operation, there is still data available, the callback function will
1070 * The socket is available for writing. That is, the next write call
1071 * won't block. This event is generated only once, when the connection is
1072 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1073 * when the output buffer empties again. This means that the app should
1074 * assume that it can write since the first OUTPUT event, and no more
1075 * OUTPUT events will be generated unless an error occurs.
1077 * Connection succesfully established, for client sockets, or incoming
1078 * client connection, for server sockets. Wait for this event (also watch
1079 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1081 * The connection is lost (or a connection request failed); this could
1082 * be due to a failure, or due to the peer closing it gracefully.
1085 /* GSocket_SetCallback:
1086 * Enables the callbacks specified by 'flags'. Note that 'flags'
1087 * may be a combination of flags OR'ed toghether, so the same
1088 * callback function can be made to accept different events.
1089 * The callback function must have the following prototype:
1091 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1093 void GSocketBSD::SetCallback(GSocketEventFlags flags
,
1094 GSocketCallback callback
, char *cdata
)
1100 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1102 if ((flags
& (1 << count
)) != 0)
1104 m_cbacks
[count
] = callback
;
1105 m_data
[count
] = cdata
;
1110 /* GSocket_UnsetCallback:
1111 * Disables all callbacks specified by 'flags', which may be a
1112 * combination of flags OR'ed toghether.
1114 void GSocketBSD::UnsetCallback(GSocketEventFlags flags
)
1120 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1122 if ((flags
& (1 << count
)) != 0)
1124 m_cbacks
[count
] = NULL
;
1125 m_data
[count
] = NULL
;
1131 GSocketError
GSocketBSD::GetSockOpt(int level
, int optname
,
1132 void *optval
, int *optlen
)
1134 if (getsockopt(m_fd
, level
, optname
, optval
, optlen
) == 0)
1136 return GSOCK_NOERROR
;
1138 return GSOCK_OPTERR
;
1141 GSocketError
GSocketBSD::SetSockOpt(int level
, int optname
,
1142 const void *optval
, int optlen
)
1144 if (setsockopt(m_fd
, level
, optname
, optval
, optlen
) == 0)
1146 return GSOCK_NOERROR
;
1148 return GSOCK_OPTERR
;
1151 #define CALL_CALLBACK(event) { \
1153 if (m_cbacks[event]) \
1154 m_cbacks[event](this, event, m_data[event]); \
1158 void GSocketBSD::Enable(GSocketEvent event
)
1160 m_detected
&= ~(1 << event
);
1161 EventLoop_Install_Callback(event
);
1164 void GSocketBSD::Disable(GSocketEvent event
)
1166 m_detected
|= (1 << event
);
1167 EventLoop_Uninstall_Callback(event
);
1170 /* _GSocket_Input_Timeout:
1171 * For blocking sockets, wait until data is available or
1172 * until timeout ellapses.
1174 GSocketError
GSocketBSD::Input_Timeout()
1180 /* Linux select() will overwrite the struct on return */
1181 tv
.tv_sec
= (m_timeout
/ 1000);
1182 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1184 if (!m_non_blocking
)
1187 FD_SET(m_fd
, &readfds
);
1188 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1191 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1192 m_error
= GSOCK_TIMEDOUT
;
1193 return GSOCK_TIMEDOUT
;
1197 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1198 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1199 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1200 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1201 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1202 m_error
= GSOCK_TIMEDOUT
;
1203 return GSOCK_TIMEDOUT
;
1206 return GSOCK_NOERROR
;
1209 /* _GSocket_Output_Timeout:
1210 * For blocking sockets, wait until data can be sent without
1211 * blocking or until timeout ellapses.
1213 GSocketError
GSocketBSD::Output_Timeout()
1219 /* Linux select() will overwrite the struct on return */
1220 tv
.tv_sec
= (m_timeout
/ 1000);
1221 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1223 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1225 if (!m_non_blocking
)
1228 FD_SET(m_fd
, &writefds
);
1229 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1232 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1233 m_error
= GSOCK_TIMEDOUT
;
1234 return GSOCK_TIMEDOUT
;
1238 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1239 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1240 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1241 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1242 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1243 m_error
= GSOCK_TIMEDOUT
;
1244 return GSOCK_TIMEDOUT
;
1246 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1247 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1250 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1255 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1258 return GSOCK_NOERROR
;
1261 int GSocketBSD::Recv_Stream(char *buffer
, int size
)
1263 return recv(m_fd
, buffer
, size
, 0);
1266 int GSocketBSD::Recv_Dgram(char *buffer
, int size
)
1268 struct sockaddr from
;
1269 SOCKLEN_T fromlen
= sizeof(from
);
1273 fromlen
= sizeof(from
);
1275 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1280 /* Translate a system address into a GSocket address */
1283 m_peer
= GAddress_new();
1286 m_error
= GSOCK_MEMERR
;
1290 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1291 if (err
!= GSOCK_NOERROR
)
1293 GAddress_destroy(m_peer
);
1302 int GSocketBSD::Send_Stream(const char *buffer
, int size
)
1306 #ifndef __VISAGECPP__
1308 ret
= send(m_fd
, buffer
, size
, 0);
1311 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1317 int GSocketBSD::Send_Dgram(const char *buffer
, int size
)
1319 struct sockaddr
*addr
;
1325 m_error
= GSOCK_INVADDR
;
1329 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1330 if (err
!= GSOCK_NOERROR
)
1336 #ifndef __VISAGECPP__
1338 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1341 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1344 /* Frees memory allocated from _GAddress_translate_to */
1350 void GSocketBSD::Detected_Read()
1354 /* If we have already detected a LOST event, then don't try
1355 * to do any further processing.
1357 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1359 m_establishing
= FALSE
;
1361 CALL_CALLBACK(GSOCK_LOST
);
1366 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1368 CALL_CALLBACK(GSOCK_INPUT
);
1372 if (m_server
&& m_stream
)
1374 CALL_CALLBACK(GSOCK_CONNECTION
);
1378 CALL_CALLBACK(GSOCK_LOST
);
1384 void GSocketBSD::Detected_Write()
1386 /* If we have already detected a LOST event, then don't try
1387 * to do any further processing.
1389 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1391 m_establishing
= FALSE
;
1393 CALL_CALLBACK(GSOCK_LOST
);
1398 if (m_establishing
&& !m_server
)
1401 SOCKLEN_T len
= sizeof(error
);
1403 m_establishing
= FALSE
;
1405 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1409 CALL_CALLBACK(GSOCK_LOST
);
1414 CALL_CALLBACK(GSOCK_CONNECTION
);
1415 /* We have to fire this event by hand because CONNECTION (for clients)
1416 * and OUTPUT are internally the same and we just disabled CONNECTION
1417 * events with the above macro.
1419 CALL_CALLBACK(GSOCK_OUTPUT
);
1424 CALL_CALLBACK(GSOCK_OUTPUT
);
1428 /* Compatibility functions for GSocket */
1429 GSocket
*GSocket_new(void)
1431 GSocket
*newsocket
= new GSocketBSDGUIShim();
1432 if(newsocket
->IsOk())
1438 void GSocket_destroy(GSocket
*socket
)
1442 /* Check that the socket is really shutdowned */
1443 if (socket
->m_fd
!= INVALID_SOCKET
)
1449 void GSocketBSD::_GSocket_Detected_Read(GSocket
*socket
)
1450 { socket
->Detected_Read(); }
1452 void GSocketBSD::_GSocket_Detected_Write(GSocket
*socket
)
1453 { socket
->Detected_Write(); }
1456 * -------------------------------------------------------------------------
1458 * -------------------------------------------------------------------------
1461 /* CHECK_ADDRESS verifies that the current address family is either
1462 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1463 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1464 * an appropiate error code.
1466 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1468 #define CHECK_ADDRESS(address, family) \
1470 if (address->m_family == GSOCK_NOFAMILY) \
1471 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1472 return address->m_error; \
1473 if (address->m_family != GSOCK_##family) \
1475 address->m_error = GSOCK_INVADDR; \
1476 return GSOCK_INVADDR; \
1480 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1482 if (address->m_family == GSOCK_NOFAMILY) \
1483 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1485 if (address->m_family != GSOCK_##family) \
1487 address->m_error = GSOCK_INVADDR; \
1493 GAddress
*GAddress_new(void)
1497 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1500 address
->m_family
= GSOCK_NOFAMILY
;
1501 address
->m_addr
= NULL
;
1507 GAddress
*GAddress_copy(GAddress
*address
)
1511 assert(address
!= NULL
);
1513 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1516 memcpy(addr2
, address
, sizeof(GAddress
));
1518 if (address
->m_addr
&& address
->m_len
> 0)
1520 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1521 if (addr2
->m_addr
== NULL
)
1526 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1532 void GAddress_destroy(GAddress
*address
)
1534 assert(address
!= NULL
);
1536 if (address
->m_addr
)
1537 free(address
->m_addr
);
1542 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1544 assert(address
!= NULL
);
1546 address
->m_family
= type
;
1549 GAddressType
GAddress_GetFamily(GAddress
*address
)
1551 assert(address
!= NULL
);
1553 return address
->m_family
;
1556 GSocketError
_GAddress_translate_from(GAddress
*address
,
1557 struct sockaddr
*addr
, int len
)
1559 address
->m_realfamily
= addr
->sa_family
;
1560 switch (addr
->sa_family
)
1563 address
->m_family
= GSOCK_INET
;
1566 address
->m_family
= GSOCK_UNIX
;
1570 address
->m_family
= GSOCK_INET6
;
1575 address
->m_error
= GSOCK_INVOP
;
1580 if (address
->m_addr
)
1581 free(address
->m_addr
);
1583 address
->m_len
= len
;
1584 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1586 if (address
->m_addr
== NULL
)
1588 address
->m_error
= GSOCK_MEMERR
;
1589 return GSOCK_MEMERR
;
1591 memcpy(address
->m_addr
, addr
, len
);
1593 return GSOCK_NOERROR
;
1596 GSocketError
_GAddress_translate_to(GAddress
*address
,
1597 struct sockaddr
**addr
, int *len
)
1599 if (!address
->m_addr
)
1601 address
->m_error
= GSOCK_INVADDR
;
1602 return GSOCK_INVADDR
;
1605 *len
= address
->m_len
;
1606 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1609 address
->m_error
= GSOCK_MEMERR
;
1610 return GSOCK_MEMERR
;
1613 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1614 return GSOCK_NOERROR
;
1618 * -------------------------------------------------------------------------
1619 * Internet address family
1620 * -------------------------------------------------------------------------
1623 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1625 address
->m_len
= sizeof(struct sockaddr_in
);
1626 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1627 if (address
->m_addr
== NULL
)
1629 address
->m_error
= GSOCK_MEMERR
;
1630 return GSOCK_MEMERR
;
1633 address
->m_family
= GSOCK_INET
;
1634 address
->m_realfamily
= PF_INET
;
1635 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1636 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1638 return GSOCK_NOERROR
;
1641 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1644 struct in_addr
*addr
;
1646 assert(address
!= NULL
);
1648 CHECK_ADDRESS(address
, INET
);
1650 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1652 /* If it is a numeric host name, convert it now */
1653 #if defined(HAVE_INET_ATON)
1654 if (inet_aton(hostname
, addr
) == 0)
1656 #elif defined(HAVE_INET_ADDR)
1657 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1660 /* Use gethostbyname by default */
1662 int val
= 1; //VA doesn't like constants in conditional expressions at all
1667 struct in_addr
*array_addr
;
1669 /* It is a real name, we solve it */
1670 if ((he
= gethostbyname(hostname
)) == NULL
)
1672 /* Reset to invalid address */
1673 addr
->s_addr
= INADDR_NONE
;
1674 address
->m_error
= GSOCK_NOHOST
;
1675 return GSOCK_NOHOST
;
1677 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1678 addr
->s_addr
= array_addr
[0].s_addr
;
1680 return GSOCK_NOERROR
;
1683 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1685 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1688 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1689 unsigned long hostaddr
)
1691 struct in_addr
*addr
;
1693 assert(address
!= NULL
);
1695 CHECK_ADDRESS(address
, INET
);
1697 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1698 addr
->s_addr
= htonl(hostaddr
);
1700 return GSOCK_NOERROR
;
1703 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1704 const char *protocol
)
1707 struct sockaddr_in
*addr
;
1709 assert(address
!= NULL
);
1710 CHECK_ADDRESS(address
, INET
);
1714 address
->m_error
= GSOCK_INVPORT
;
1715 return GSOCK_INVPORT
;
1718 se
= getservbyname(port
, protocol
);
1721 /* the cast to int suppresses compiler warnings about subscript having the
1723 if (isdigit((int)port
[0]))
1727 port_int
= atoi(port
);
1728 addr
= (struct sockaddr_in
*)address
->m_addr
;
1729 addr
->sin_port
= htons(port_int
);
1730 return GSOCK_NOERROR
;
1733 address
->m_error
= GSOCK_INVPORT
;
1734 return GSOCK_INVPORT
;
1737 addr
= (struct sockaddr_in
*)address
->m_addr
;
1738 addr
->sin_port
= se
->s_port
;
1740 return GSOCK_NOERROR
;
1743 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1745 struct sockaddr_in
*addr
;
1747 assert(address
!= NULL
);
1748 CHECK_ADDRESS(address
, INET
);
1750 addr
= (struct sockaddr_in
*)address
->m_addr
;
1751 addr
->sin_port
= htons(port
);
1753 return GSOCK_NOERROR
;
1756 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1760 struct sockaddr_in
*addr
;
1762 assert(address
!= NULL
);
1763 CHECK_ADDRESS(address
, INET
);
1765 addr
= (struct sockaddr_in
*)address
->m_addr
;
1766 addr_buf
= (char *)&(addr
->sin_addr
);
1768 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1771 address
->m_error
= GSOCK_NOHOST
;
1772 return GSOCK_NOHOST
;
1775 strncpy(hostname
, he
->h_name
, sbuf
);
1777 return GSOCK_NOERROR
;
1780 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1782 struct sockaddr_in
*addr
;
1784 assert(address
!= NULL
);
1785 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1787 addr
= (struct sockaddr_in
*)address
->m_addr
;
1789 return ntohl(addr
->sin_addr
.s_addr
);
1792 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1794 struct sockaddr_in
*addr
;
1796 assert(address
!= NULL
);
1797 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1799 addr
= (struct sockaddr_in
*)address
->m_addr
;
1800 return ntohs(addr
->sin_port
);
1804 * -------------------------------------------------------------------------
1805 * Unix address family
1806 * -------------------------------------------------------------------------
1809 #ifndef __VISAGECPP__
1810 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1812 address
->m_len
= sizeof(struct sockaddr_un
);
1813 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1814 if (address
->m_addr
== NULL
)
1816 address
->m_error
= GSOCK_MEMERR
;
1817 return GSOCK_MEMERR
;
1820 address
->m_family
= GSOCK_UNIX
;
1821 address
->m_realfamily
= PF_UNIX
;
1822 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1823 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1825 return GSOCK_NOERROR
;
1828 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1830 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1832 struct sockaddr_un
*addr
;
1834 assert(address
!= NULL
);
1836 CHECK_ADDRESS(address
, UNIX
);
1838 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1839 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1840 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1842 return GSOCK_NOERROR
;
1845 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1847 struct sockaddr_un
*addr
;
1849 assert(address
!= NULL
);
1850 CHECK_ADDRESS(address
, UNIX
);
1852 addr
= (struct sockaddr_un
*)address
->m_addr
;
1854 strncpy(path
, addr
->sun_path
, sbuf
);
1856 return GSOCK_NOERROR
;
1858 #endif /* !defined(__VISAGECPP__) */
1859 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */