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 ///////////////////////////////////////////////////////////////////////////
161 class GSocketBSDGUIShim
:public GSocketBSD
163 friend void GSocket_SetGUIFunctions(struct GSocketGUIFunctionsTable
*guifunc
);
165 static inline bool GUI_Init();
166 static inline void GUI_Cleanup();
167 static inline bool UseGUI();
169 virtual ~GSocketBSDGUIShim();
171 virtual void EventLoop_Enable_Events();
172 virtual void EventLoop_Disable_Events();
173 virtual void EventLoop_Install_Callback(GSocketEvent event
);
174 virtual void EventLoop_Uninstall_Callback(GSocketEvent event
);
176 /* Table of GUI-related functions. We must call them indirectly because
177 * of wxBase and GUI separation: */
179 static struct GSocketGUIFunctionsTable
*ms_gui_functions
;
182 struct GSocketGUIFunctionsTable
*GSocketBSDGUIShim::ms_gui_functions
= NULL
;
184 void GSocket_SetGUIFunctions(struct GSocketGUIFunctionsTable
*guifunc
)
186 GSocketBSDGUIShim::ms_gui_functions
= guifunc
;
189 inline bool GSocketBSDGUIShim::UseGUI()
191 return ms_gui_functions
;
194 inline bool GSocketBSDGUIShim::GUI_Init()
196 return (ms_gui_functions
)?ms_gui_functions
->GUI_Init():true;
199 inline void GSocketBSDGUIShim::GUI_Cleanup()
201 if (ms_gui_functions
) ms_gui_functions
->GUI_Cleanup();
204 GSocketBSDGUIShim::GSocketBSDGUIShim()
206 m_ok
= (ms_gui_functions
? ms_gui_functions
->GUI_Init_Socket(this) : true);
209 GSocketBSDGUIShim::~GSocketBSDGUIShim()
211 if (ms_gui_functions
) ms_gui_functions
->GUI_Destroy_Socket(this);
214 void GSocketBSDGUIShim::EventLoop_Enable_Events()
216 if (ms_gui_functions
) ms_gui_functions
->Enable_Events(this);
219 void GSocketBSDGUIShim::EventLoop_Disable_Events()
221 if (ms_gui_functions
) ms_gui_functions
->Disable_Events(this);
224 void GSocketBSDGUIShim::EventLoop_Install_Callback(GSocketEvent event
)
226 if (ms_gui_functions
) ms_gui_functions
->Install_Callback(this, event
);
229 void GSocketBSDGUIShim::EventLoop_Uninstall_Callback(GSocketEvent event
)
231 if (ms_gui_functions
) ms_gui_functions
->Uninstall_Callback(this, event
);
234 ///////////////////////////////////////////////////////////////////////////
237 static struct GSocketBaseFunctionsTable gs_base_functions
=
239 GSocketBSD::_GSocket_Detected_Read
,
240 GSocketBSD::_GSocket_Detected_Write
243 /* Global initialisers */
245 int GSocket_Init(void)
247 return GSocketBSDGUIShim::GUI_Init();
250 void GSocket_Cleanup(void)
252 GSocketBSDGUIShim::GUI_Cleanup();
255 GSocketBSD::GSocketBSD()
259 m_fd
= INVALID_SOCKET
;
260 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
267 m_error
= GSOCK_NOERROR
;
270 m_gui_dependent
= NULL
;
271 m_non_blocking
= FALSE
;
272 m_timeout
= 10*60*1000;
273 /* 10 minutes * 60 sec * 1000 millisec */
274 m_establishing
= FALSE
;
276 m_functions
= &gs_base_functions
;
281 void GSocketBSD::Close()
283 EventLoop_Disable_Events();
284 // gsockosx.c calls CFSocketInvalidate which closes the socket for us
285 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
288 m_fd
= INVALID_SOCKET
;
291 GSocketBSD::~GSocketBSD()
293 /* Destroy private addresses */
295 GAddress_destroy(m_local
);
298 GAddress_destroy(m_peer
);
302 * Disallow further read/write operations on this socket, close
303 * the fd and disable all callbacks.
305 void GSocketBSD::Shutdown()
311 /* If socket has been created, shutdown it */
312 if (m_fd
!= INVALID_SOCKET
)
318 /* Disable GUI callbacks */
319 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
320 m_cbacks
[evt
] = NULL
;
322 m_detected
= GSOCK_LOST_FLAG
;
325 /* Address handling */
331 * Set or get the local or peer address for this socket. The 'set'
332 * functions return GSOCK_NOERROR on success, an error code otherwise.
333 * The 'get' functions return a pointer to a GAddress object on success,
334 * or NULL otherwise, in which case they set the error code of the
335 * corresponding GSocket.
338 * GSOCK_INVSOCK - the socket is not valid.
339 * GSOCK_INVADDR - the address is not valid.
341 GSocketError
GSocketBSD::SetLocal(GAddress
*address
)
345 /* the socket must be initialized, or it must be a server */
346 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
348 m_error
= GSOCK_INVSOCK
;
349 return GSOCK_INVSOCK
;
353 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
355 m_error
= GSOCK_INVADDR
;
356 return GSOCK_INVADDR
;
360 GAddress_destroy(m_local
);
362 m_local
= GAddress_copy(address
);
364 return GSOCK_NOERROR
;
367 GSocketError
GSocketBSD::SetPeer(GAddress
*address
)
372 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
374 m_error
= GSOCK_INVADDR
;
375 return GSOCK_INVADDR
;
379 GAddress_destroy(m_peer
);
381 m_peer
= GAddress_copy(address
);
383 return GSOCK_NOERROR
;
386 GAddress
*GSocketBSD::GetLocal()
389 struct sockaddr addr
;
390 SOCKLEN_T size
= sizeof(addr
);
395 /* try to get it from the m_local var first */
397 return GAddress_copy(m_local
);
399 /* else, if the socket is initialized, try getsockname */
400 if (m_fd
== INVALID_SOCKET
)
402 m_error
= GSOCK_INVSOCK
;
406 if (getsockname(m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
408 m_error
= GSOCK_IOERR
;
412 /* got a valid address from getsockname, create a GAddress object */
413 address
= GAddress_new();
416 m_error
= GSOCK_MEMERR
;
420 err
= _GAddress_translate_from(address
, &addr
, size
);
421 if (err
!= GSOCK_NOERROR
)
423 GAddress_destroy(address
);
431 GAddress
*GSocketBSD::GetPeer()
435 /* try to get it from the m_peer var */
437 return GAddress_copy(m_peer
);
442 /* Server specific parts */
444 /* GSocket_SetServer:
445 * Sets up this socket as a server. The local address must have been
446 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
447 * Returns GSOCK_NOERROR on success, one of the following otherwise:
450 * GSOCK_INVSOCK - the socket is in use.
451 * GSOCK_INVADDR - the local address has not been set.
452 * GSOCK_IOERR - low-level error.
454 GSocketError
GSocketBSD::SetServer()
460 /* must not be in use */
461 if (m_fd
!= INVALID_SOCKET
)
463 m_error
= GSOCK_INVSOCK
;
464 return GSOCK_INVSOCK
;
467 /* the local addr must have been set */
470 m_error
= GSOCK_INVADDR
;
471 return GSOCK_INVADDR
;
474 /* Initialize all fields */
479 /* Create the socket */
480 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
482 if (m_fd
== INVALID_SOCKET
)
484 m_error
= GSOCK_IOERR
;
487 #if defined(__EMX__) || defined(__VISAGECPP__)
488 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
490 ioctl(m_fd
, FIONBIO
, &arg
);
492 EventLoop_Enable_Events();
494 /* allow a socket to re-bind if the socket is in the TIME_WAIT
495 state after being previously closed.
497 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
499 /* Bind to the local address,
500 * retrieve the actual address bound,
501 * and listen up to 5 connections.
503 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
506 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
507 (listen(m_fd
, 5) != 0))
510 m_error
= GSOCK_IOERR
;
514 return GSOCK_NOERROR
;
517 /* GSocket_WaitConnection:
518 * Waits for an incoming client connection. Returns a pointer to
519 * a GSocket object, or NULL if there was an error, in which case
520 * the last error field will be updated for the calling GSocket.
522 * Error codes (set in the calling GSocket)
523 * GSOCK_INVSOCK - the socket is not valid or not a server.
524 * GSOCK_TIMEDOUT - timeout, no incoming connections.
525 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
526 * GSOCK_MEMERR - couldn't allocate memory.
527 * GSOCK_IOERR - low-level error.
529 GSocket
*GSocketBSD::WaitConnection()
531 struct sockaddr from
;
532 SOCKLEN_T fromlen
= sizeof(from
);
539 /* Reenable CONNECTION events */
540 Enable(GSOCK_CONNECTION
);
542 /* If the socket has already been created, we exit immediately */
543 if (m_fd
== INVALID_SOCKET
|| !m_server
)
545 m_error
= GSOCK_INVSOCK
;
549 /* Create a GSocket object for the new connection */
550 connection
= GSocket_new();
555 m_error
= GSOCK_MEMERR
;
559 /* Wait for a connection (with timeout) */
560 if (Input_Timeout() == GSOCK_TIMEDOUT
)
563 /* m_error set by _GSocket_Input_Timeout */
567 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
569 if (connection
->m_fd
== INVALID_SOCKET
)
571 if (errno
== EWOULDBLOCK
)
572 m_error
= GSOCK_WOULDBLOCK
;
574 m_error
= GSOCK_IOERR
;
580 /* Initialize all fields */
581 connection
->m_server
= FALSE
;
582 connection
->m_stream
= TRUE
;
583 connection
->m_oriented
= TRUE
;
585 /* Setup the peer address field */
586 connection
->m_peer
= GAddress_new();
587 if (!connection
->m_peer
)
590 m_error
= GSOCK_MEMERR
;
593 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
594 if (err
!= GSOCK_NOERROR
)
596 GAddress_destroy(connection
->m_peer
);
601 #if defined(__EMX__) || defined(__VISAGECPP__)
602 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
604 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
606 connection
->EventLoop_Enable_Events();
611 /* Client specific parts */
614 * For stream (connection oriented) sockets, GSocket_Connect() tries
615 * to establish a client connection to a server using the peer address
616 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
617 * connection has been succesfully established, or one of the error
618 * codes listed below. Note that for nonblocking sockets, a return
619 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
620 * request can be completed later; you should use GSocket_Select()
621 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
622 * corresponding asynchronous events.
624 * For datagram (non connection oriented) sockets, GSocket_Connect()
625 * just sets the peer address established with GSocket_SetPeer() as
626 * default destination.
629 * GSOCK_INVSOCK - the socket is in use or not valid.
630 * GSOCK_INVADDR - the peer address has not been established.
631 * GSOCK_TIMEDOUT - timeout, the connection failed.
632 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
633 * GSOCK_MEMERR - couldn't allocate memory.
634 * GSOCK_IOERR - low-level error.
636 GSocketError
GSocketBSD::Connect(GSocketStream stream
)
643 /* Enable CONNECTION events (needed for nonblocking connections) */
644 Enable(GSOCK_CONNECTION
);
646 if (m_fd
!= INVALID_SOCKET
)
648 m_error
= GSOCK_INVSOCK
;
649 return GSOCK_INVSOCK
;
654 m_error
= GSOCK_INVADDR
;
655 return GSOCK_INVADDR
;
658 /* Streamed or dgram socket? */
659 m_stream
= (stream
== GSOCK_STREAMED
);
662 m_establishing
= FALSE
;
664 /* Create the socket */
665 m_fd
= socket(m_peer
->m_realfamily
,
666 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
668 if (m_fd
== INVALID_SOCKET
)
670 m_error
= GSOCK_IOERR
;
673 #if defined(__EMX__) || defined(__VISAGECPP__)
674 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
676 ioctl(m_fd
, FIONBIO
, &arg
);
678 EventLoop_Enable_Events();
680 /* Connect it to the peer address, with a timeout (see below) */
681 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
687 /* If connect failed with EINPROGRESS and the GSocket object
688 * is in blocking mode, we select() for the specified timeout
689 * checking for writability to see if the connection request
692 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
694 if (Output_Timeout() == GSOCK_TIMEDOUT
)
697 /* m_error is set in _GSocket_Output_Timeout */
698 return GSOCK_TIMEDOUT
;
703 SOCKLEN_T len
= sizeof(error
);
705 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
708 return GSOCK_NOERROR
;
712 /* If connect failed with EINPROGRESS and the GSocket object
713 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
714 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
715 * this way if the connection completes, a GSOCK_CONNECTION
716 * event will be generated, if enabled.
718 if ((err
== EINPROGRESS
) && (m_non_blocking
))
720 m_establishing
= TRUE
;
721 m_error
= GSOCK_WOULDBLOCK
;
722 return GSOCK_WOULDBLOCK
;
725 /* If connect failed with an error other than EINPROGRESS,
726 * then the call to GSocket_Connect has failed.
729 m_error
= GSOCK_IOERR
;
733 return GSOCK_NOERROR
;
736 /* Datagram sockets */
738 /* GSocket_SetNonOriented:
739 * Sets up this socket as a non-connection oriented (datagram) socket.
740 * Before using this function, the local address must have been set
741 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
742 * on success, or one of the following otherwise.
745 * GSOCK_INVSOCK - the socket is in use.
746 * GSOCK_INVADDR - the local address has not been set.
747 * GSOCK_IOERR - low-level error.
749 GSocketError
GSocketBSD::SetNonOriented()
755 if (m_fd
!= INVALID_SOCKET
)
757 m_error
= GSOCK_INVSOCK
;
758 return GSOCK_INVSOCK
;
763 m_error
= GSOCK_INVADDR
;
764 return GSOCK_INVADDR
;
767 /* Initialize all fields */
772 /* Create the socket */
773 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
775 if (m_fd
== INVALID_SOCKET
)
777 m_error
= GSOCK_IOERR
;
780 #if defined(__EMX__) || defined(__VISAGECPP__)
781 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
783 ioctl(m_fd
, FIONBIO
, &arg
);
785 EventLoop_Enable_Events();
787 /* Bind to the local address,
788 * and retrieve the actual address bound.
790 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
793 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
796 m_error
= GSOCK_IOERR
;
800 return GSOCK_NOERROR
;
805 /* Like recv(), send(), ... */
806 int GSocketBSD::Read(char *buffer
, int size
)
812 /* When using CFSocket we MUST NOT reenable events until we finish reading */
814 /* Reenable INPUT events */
818 if (m_fd
== INVALID_SOCKET
|| m_server
)
820 m_error
= GSOCK_INVSOCK
;
824 /* If the socket is blocking, wait for data (with a timeout) */
825 if (Input_Timeout() == GSOCK_TIMEDOUT
)
830 ret
= Recv_Stream(buffer
, size
);
832 ret
= Recv_Dgram(buffer
, size
);
836 if (errno
== EWOULDBLOCK
)
837 m_error
= GSOCK_WOULDBLOCK
;
839 m_error
= GSOCK_IOERR
;
843 /* Reenable INPUT events */
850 int GSocketBSD::Write(const char *buffer
, int size
)
856 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
858 if (m_fd
== INVALID_SOCKET
|| m_server
)
860 m_error
= GSOCK_INVSOCK
;
864 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
866 /* If the socket is blocking, wait for writability (with a timeout) */
867 if (Output_Timeout() == GSOCK_TIMEDOUT
)
870 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
874 ret
= Send_Stream(buffer
, size
);
876 ret
= Send_Dgram(buffer
, size
);
878 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
882 if (errno
== EWOULDBLOCK
)
884 m_error
= GSOCK_WOULDBLOCK
;
885 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
889 m_error
= GSOCK_IOERR
;
890 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
893 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
894 * in MSW). Once the first OUTPUT event is received, users can assume
895 * that the socket is writable until a read operation fails. Only then
896 * will further OUTPUT events be posted.
898 Enable(GSOCK_OUTPUT
);
902 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
908 * Polls the socket to determine its status. This function will
909 * check for the events specified in the 'flags' parameter, and
910 * it will return a mask indicating which operations can be
911 * performed. This function won't block, regardless of the
912 * mode (blocking | nonblocking) of the socket.
914 GSocketEventFlags
GSocketBSD::Select(GSocketEventFlags flags
)
916 if (!GSocketBSDGUIShim::UseGUI())
919 GSocketEventFlags result
= 0;
925 /* Do not use a static struct, Linux can garble it */
926 tv
.tv_sec
= m_timeout
/ 1000;
927 tv
.tv_usec
= (m_timeout
% 1000) / 1000;
934 FD_SET(m_fd
, &readfds
);
935 if (flags
& GSOCK_OUTPUT_FLAG
)
936 FD_SET(m_fd
, &writefds
);
937 FD_SET(m_fd
, &exceptfds
);
939 /* Check 'sticky' CONNECTION flag first */
940 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
942 /* If we have already detected a LOST event, then don't try
943 * to do any further processing.
945 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
947 m_establishing
= FALSE
;
949 return (GSOCK_LOST_FLAG
& flags
);
953 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
955 /* What to do here? */
956 return (result
& flags
);
959 /* Check for readability */
960 if (FD_ISSET(m_fd
, &readfds
))
964 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
966 result
|= GSOCK_INPUT_FLAG
;
970 if (m_server
&& m_stream
)
972 result
|= GSOCK_CONNECTION_FLAG
;
973 m_detected
|= GSOCK_CONNECTION_FLAG
;
977 m_detected
= GSOCK_LOST_FLAG
;
978 m_establishing
= FALSE
;
980 /* LOST event: Abort any further processing */
981 return (GSOCK_LOST_FLAG
& flags
);
986 /* Check for writability */
987 if (FD_ISSET(m_fd
, &writefds
))
989 if (m_establishing
&& !m_server
)
992 SOCKLEN_T len
= sizeof(error
);
994 m_establishing
= FALSE
;
996 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1000 m_detected
= GSOCK_LOST_FLAG
;
1002 /* LOST event: Abort any further processing */
1003 return (GSOCK_LOST_FLAG
& flags
);
1007 result
|= GSOCK_CONNECTION_FLAG
;
1008 m_detected
|= GSOCK_CONNECTION_FLAG
;
1013 result
|= GSOCK_OUTPUT_FLAG
;
1017 /* Check for exceptions and errors (is this useful in Unices?) */
1018 if (FD_ISSET(m_fd
, &exceptfds
))
1020 m_establishing
= FALSE
;
1021 m_detected
= GSOCK_LOST_FLAG
;
1023 /* LOST event: Abort any further processing */
1024 return (GSOCK_LOST_FLAG
& flags
);
1027 return (result
& flags
);
1034 return flags
& m_detected
;
1041 /* GSocket_SetNonBlocking:
1042 * Sets the socket to non-blocking mode. All IO calls will return
1045 void GSocketBSD::SetNonBlocking(int non_block
)
1049 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1051 m_non_blocking
= non_block
;
1054 /* GSocket_SetTimeout:
1055 * Sets the timeout for blocking calls. Time is expressed in
1058 void GSocketBSD::SetTimeout(unsigned long millisec
)
1062 m_timeout
= millisec
;
1065 /* GSocket_GetError:
1066 * Returns the last error occured for this socket. Note that successful
1067 * operations do not clear this back to GSOCK_NOERROR, so use it only
1070 GSocketError
GSocketBSD::GetError()
1080 * There is data to be read in the input buffer. If, after a read
1081 * operation, there is still data available, the callback function will
1084 * The socket is available for writing. That is, the next write call
1085 * won't block. This event is generated only once, when the connection is
1086 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1087 * when the output buffer empties again. This means that the app should
1088 * assume that it can write since the first OUTPUT event, and no more
1089 * OUTPUT events will be generated unless an error occurs.
1091 * Connection succesfully established, for client sockets, or incoming
1092 * client connection, for server sockets. Wait for this event (also watch
1093 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1095 * The connection is lost (or a connection request failed); this could
1096 * be due to a failure, or due to the peer closing it gracefully.
1099 /* GSocket_SetCallback:
1100 * Enables the callbacks specified by 'flags'. Note that 'flags'
1101 * may be a combination of flags OR'ed toghether, so the same
1102 * callback function can be made to accept different events.
1103 * The callback function must have the following prototype:
1105 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1107 void GSocketBSD::SetCallback(GSocketEventFlags flags
,
1108 GSocketCallback callback
, char *cdata
)
1114 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1116 if ((flags
& (1 << count
)) != 0)
1118 m_cbacks
[count
] = callback
;
1119 m_data
[count
] = cdata
;
1124 /* GSocket_UnsetCallback:
1125 * Disables all callbacks specified by 'flags', which may be a
1126 * combination of flags OR'ed toghether.
1128 void GSocketBSD::UnsetCallback(GSocketEventFlags flags
)
1134 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1136 if ((flags
& (1 << count
)) != 0)
1138 m_cbacks
[count
] = NULL
;
1139 m_data
[count
] = NULL
;
1145 #define CALL_CALLBACK(event) { \
1147 if (m_cbacks[event]) \
1148 m_cbacks[event](this, event, m_data[event]); \
1152 void GSocketBSD::Enable(GSocketEvent event
)
1154 m_detected
&= ~(1 << event
);
1155 EventLoop_Install_Callback(event
);
1158 void GSocketBSD::Disable(GSocketEvent event
)
1160 m_detected
|= (1 << event
);
1161 EventLoop_Uninstall_Callback(event
);
1164 /* _GSocket_Input_Timeout:
1165 * For blocking sockets, wait until data is available or
1166 * until timeout ellapses.
1168 GSocketError
GSocketBSD::Input_Timeout()
1174 /* Linux select() will overwrite the struct on return */
1175 tv
.tv_sec
= (m_timeout
/ 1000);
1176 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1178 if (!m_non_blocking
)
1181 FD_SET(m_fd
, &readfds
);
1182 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1185 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1186 m_error
= GSOCK_TIMEDOUT
;
1187 return GSOCK_TIMEDOUT
;
1191 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1192 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1193 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1194 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1195 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1196 m_error
= GSOCK_TIMEDOUT
;
1197 return GSOCK_TIMEDOUT
;
1200 return GSOCK_NOERROR
;
1203 /* _GSocket_Output_Timeout:
1204 * For blocking sockets, wait until data can be sent without
1205 * blocking or until timeout ellapses.
1207 GSocketError
GSocketBSD::Output_Timeout()
1213 /* Linux select() will overwrite the struct on return */
1214 tv
.tv_sec
= (m_timeout
/ 1000);
1215 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1217 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1219 if (!m_non_blocking
)
1222 FD_SET(m_fd
, &writefds
);
1223 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1226 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1227 m_error
= GSOCK_TIMEDOUT
;
1228 return GSOCK_TIMEDOUT
;
1232 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1233 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1234 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1235 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1236 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1237 m_error
= GSOCK_TIMEDOUT
;
1238 return GSOCK_TIMEDOUT
;
1240 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1241 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1244 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1249 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1252 return GSOCK_NOERROR
;
1255 int GSocketBSD::Recv_Stream(char *buffer
, int size
)
1257 return recv(m_fd
, buffer
, size
, 0);
1260 int GSocketBSD::Recv_Dgram(char *buffer
, int size
)
1262 struct sockaddr from
;
1263 SOCKLEN_T fromlen
= sizeof(from
);
1267 fromlen
= sizeof(from
);
1269 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1274 /* Translate a system address into a GSocket address */
1277 m_peer
= GAddress_new();
1280 m_error
= GSOCK_MEMERR
;
1284 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1285 if (err
!= GSOCK_NOERROR
)
1287 GAddress_destroy(m_peer
);
1296 int GSocketBSD::Send_Stream(const char *buffer
, int size
)
1300 #ifndef __VISAGECPP__
1302 ret
= send(m_fd
, buffer
, size
, 0);
1305 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1311 int GSocketBSD::Send_Dgram(const char *buffer
, int size
)
1313 struct sockaddr
*addr
;
1319 m_error
= GSOCK_INVADDR
;
1323 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1324 if (err
!= GSOCK_NOERROR
)
1330 #ifndef __VISAGECPP__
1332 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1335 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1338 /* Frees memory allocated from _GAddress_translate_to */
1344 void GSocketBSD::Detected_Read()
1348 /* If we have already detected a LOST event, then don't try
1349 * to do any further processing.
1351 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1353 m_establishing
= FALSE
;
1355 CALL_CALLBACK(GSOCK_LOST
);
1360 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1362 CALL_CALLBACK(GSOCK_INPUT
);
1366 if (m_server
&& m_stream
)
1368 CALL_CALLBACK(GSOCK_CONNECTION
);
1372 CALL_CALLBACK(GSOCK_LOST
);
1378 void GSocketBSD::Detected_Write()
1380 /* If we have already detected a LOST event, then don't try
1381 * to do any further processing.
1383 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1385 m_establishing
= FALSE
;
1387 CALL_CALLBACK(GSOCK_LOST
);
1392 if (m_establishing
&& !m_server
)
1395 SOCKLEN_T len
= sizeof(error
);
1397 m_establishing
= FALSE
;
1399 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1403 CALL_CALLBACK(GSOCK_LOST
);
1408 CALL_CALLBACK(GSOCK_CONNECTION
);
1409 /* We have to fire this event by hand because CONNECTION (for clients)
1410 * and OUTPUT are internally the same and we just disabled CONNECTION
1411 * events with the above macro.
1413 CALL_CALLBACK(GSOCK_OUTPUT
);
1418 CALL_CALLBACK(GSOCK_OUTPUT
);
1422 /* Compatibility functions for GSocket */
1423 GSocket
*GSocket_new(void)
1425 GSocket
*newsocket
= new GSocketBSDGUIShim();
1426 if(newsocket
->IsOk())
1432 void GSocket_destroy(GSocket
*socket
)
1436 /* Check that the socket is really shutdowned */
1437 if (socket
->m_fd
!= INVALID_SOCKET
)
1443 void GSocketBSD::_GSocket_Detected_Read(GSocket
*socket
)
1444 { socket
->Detected_Read(); }
1446 void GSocketBSD::_GSocket_Detected_Write(GSocket
*socket
)
1447 { socket
->Detected_Write(); }
1450 * -------------------------------------------------------------------------
1452 * -------------------------------------------------------------------------
1455 /* CHECK_ADDRESS verifies that the current address family is either
1456 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1457 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1458 * an appropiate error code.
1460 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1462 #define CHECK_ADDRESS(address, family) \
1464 if (address->m_family == GSOCK_NOFAMILY) \
1465 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1466 return address->m_error; \
1467 if (address->m_family != GSOCK_##family) \
1469 address->m_error = GSOCK_INVADDR; \
1470 return GSOCK_INVADDR; \
1474 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1476 if (address->m_family == GSOCK_NOFAMILY) \
1477 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1479 if (address->m_family != GSOCK_##family) \
1481 address->m_error = GSOCK_INVADDR; \
1487 GAddress
*GAddress_new(void)
1491 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1494 address
->m_family
= GSOCK_NOFAMILY
;
1495 address
->m_addr
= NULL
;
1501 GAddress
*GAddress_copy(GAddress
*address
)
1505 assert(address
!= NULL
);
1507 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1510 memcpy(addr2
, address
, sizeof(GAddress
));
1512 if (address
->m_addr
&& address
->m_len
> 0)
1514 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1515 if (addr2
->m_addr
== NULL
)
1520 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1526 void GAddress_destroy(GAddress
*address
)
1528 assert(address
!= NULL
);
1530 if (address
->m_addr
)
1531 free(address
->m_addr
);
1536 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1538 assert(address
!= NULL
);
1540 address
->m_family
= type
;
1543 GAddressType
GAddress_GetFamily(GAddress
*address
)
1545 assert(address
!= NULL
);
1547 return address
->m_family
;
1550 GSocketError
_GAddress_translate_from(GAddress
*address
,
1551 struct sockaddr
*addr
, int len
)
1553 address
->m_realfamily
= addr
->sa_family
;
1554 switch (addr
->sa_family
)
1557 address
->m_family
= GSOCK_INET
;
1560 address
->m_family
= GSOCK_UNIX
;
1564 address
->m_family
= GSOCK_INET6
;
1569 address
->m_error
= GSOCK_INVOP
;
1574 if (address
->m_addr
)
1575 free(address
->m_addr
);
1577 address
->m_len
= len
;
1578 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1580 if (address
->m_addr
== NULL
)
1582 address
->m_error
= GSOCK_MEMERR
;
1583 return GSOCK_MEMERR
;
1585 memcpy(address
->m_addr
, addr
, len
);
1587 return GSOCK_NOERROR
;
1590 GSocketError
_GAddress_translate_to(GAddress
*address
,
1591 struct sockaddr
**addr
, int *len
)
1593 if (!address
->m_addr
)
1595 address
->m_error
= GSOCK_INVADDR
;
1596 return GSOCK_INVADDR
;
1599 *len
= address
->m_len
;
1600 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1603 address
->m_error
= GSOCK_MEMERR
;
1604 return GSOCK_MEMERR
;
1607 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1608 return GSOCK_NOERROR
;
1612 * -------------------------------------------------------------------------
1613 * Internet address family
1614 * -------------------------------------------------------------------------
1617 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1619 address
->m_len
= sizeof(struct sockaddr_in
);
1620 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1621 if (address
->m_addr
== NULL
)
1623 address
->m_error
= GSOCK_MEMERR
;
1624 return GSOCK_MEMERR
;
1627 address
->m_family
= GSOCK_INET
;
1628 address
->m_realfamily
= PF_INET
;
1629 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1630 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1632 return GSOCK_NOERROR
;
1635 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1638 struct in_addr
*addr
;
1640 assert(address
!= NULL
);
1642 CHECK_ADDRESS(address
, INET
);
1644 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1646 /* If it is a numeric host name, convert it now */
1647 #if defined(HAVE_INET_ATON)
1648 if (inet_aton(hostname
, addr
) == 0)
1650 #elif defined(HAVE_INET_ADDR)
1651 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1654 /* Use gethostbyname by default */
1655 int val
= 1; //VA doesn't like constants in conditional expressions at all
1659 struct in_addr
*array_addr
;
1661 /* It is a real name, we solve it */
1662 if ((he
= gethostbyname(hostname
)) == NULL
)
1664 /* Reset to invalid address */
1665 addr
->s_addr
= INADDR_NONE
;
1666 address
->m_error
= GSOCK_NOHOST
;
1667 return GSOCK_NOHOST
;
1669 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1670 addr
->s_addr
= array_addr
[0].s_addr
;
1672 return GSOCK_NOERROR
;
1675 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1677 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1680 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1681 unsigned long hostaddr
)
1683 struct in_addr
*addr
;
1685 assert(address
!= NULL
);
1687 CHECK_ADDRESS(address
, INET
);
1689 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1690 addr
->s_addr
= hostaddr
;
1692 return GSOCK_NOERROR
;
1695 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1696 const char *protocol
)
1699 struct sockaddr_in
*addr
;
1701 assert(address
!= NULL
);
1702 CHECK_ADDRESS(address
, INET
);
1706 address
->m_error
= GSOCK_INVPORT
;
1707 return GSOCK_INVPORT
;
1710 se
= getservbyname(port
, protocol
);
1713 /* the cast to int suppresses compiler warnings about subscript having the
1715 if (isdigit((int)port
[0]))
1719 port_int
= atoi(port
);
1720 addr
= (struct sockaddr_in
*)address
->m_addr
;
1721 addr
->sin_port
= htons(port_int
);
1722 return GSOCK_NOERROR
;
1725 address
->m_error
= GSOCK_INVPORT
;
1726 return GSOCK_INVPORT
;
1729 addr
= (struct sockaddr_in
*)address
->m_addr
;
1730 addr
->sin_port
= se
->s_port
;
1732 return GSOCK_NOERROR
;
1735 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1737 struct sockaddr_in
*addr
;
1739 assert(address
!= NULL
);
1740 CHECK_ADDRESS(address
, INET
);
1742 addr
= (struct sockaddr_in
*)address
->m_addr
;
1743 addr
->sin_port
= htons(port
);
1745 return GSOCK_NOERROR
;
1748 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1752 struct sockaddr_in
*addr
;
1754 assert(address
!= NULL
);
1755 CHECK_ADDRESS(address
, INET
);
1757 addr
= (struct sockaddr_in
*)address
->m_addr
;
1758 addr_buf
= (char *)&(addr
->sin_addr
);
1760 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1763 address
->m_error
= GSOCK_NOHOST
;
1764 return GSOCK_NOHOST
;
1767 strncpy(hostname
, he
->h_name
, sbuf
);
1769 return GSOCK_NOERROR
;
1772 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1774 struct sockaddr_in
*addr
;
1776 assert(address
!= NULL
);
1777 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1779 addr
= (struct sockaddr_in
*)address
->m_addr
;
1781 return addr
->sin_addr
.s_addr
;
1784 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1786 struct sockaddr_in
*addr
;
1788 assert(address
!= NULL
);
1789 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1791 addr
= (struct sockaddr_in
*)address
->m_addr
;
1792 return ntohs(addr
->sin_port
);
1796 * -------------------------------------------------------------------------
1797 * Unix address family
1798 * -------------------------------------------------------------------------
1801 #ifndef __VISAGECPP__
1802 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1804 address
->m_len
= sizeof(struct sockaddr_un
);
1805 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1806 if (address
->m_addr
== NULL
)
1808 address
->m_error
= GSOCK_MEMERR
;
1809 return GSOCK_MEMERR
;
1812 address
->m_family
= GSOCK_UNIX
;
1813 address
->m_realfamily
= PF_UNIX
;
1814 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1815 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1817 return GSOCK_NOERROR
;
1820 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1822 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1824 struct sockaddr_un
*addr
;
1826 assert(address
!= NULL
);
1828 CHECK_ADDRESS(address
, UNIX
);
1830 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1831 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1832 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1834 return GSOCK_NOERROR
;
1837 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1839 struct sockaddr_un
*addr
;
1841 assert(address
!= NULL
);
1842 CHECK_ADDRESS(address
, UNIX
);
1844 addr
= (struct sockaddr_un
*)address
->m_addr
;
1846 strncpy(path
, addr
->sun_path
, sbuf
);
1848 return GSOCK_NOERROR
;
1850 #endif /* !defined(__VISAGECPP__) */
1851 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */