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 * -------------------------------------------------------------------------
14 * PLEASE don't put C++ comments here - this is a C source file.
17 #ifndef __GSOCKET_STANDALONE__
21 #if defined(__VISAGECPP__)
22 /* Seems to be needed by Visual Age C++, though I don't see how it manages
23 to not break on including a C++ header into a plain C source file */
25 #define BSD_SELECT /* use Berkley Sockets select */
28 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
31 #include <sys/types.h>
36 #include <netinet/in.h>
39 #include <sys/ioctl.h>
45 u_char sun_len
; /* sockaddr len including null */
46 u_char sun_family
; /* AF_UNIX */
47 char sun_path
[108]; /* path name (gag) */
50 #include <sys/socket.h>
56 #include <netinet/in.h>
57 #include <arpa/inet.h>
64 #include <machine/endian.h>
70 #define EBADF SOCEBADF
76 #include <sys/socket.h>
77 #include <sys/ioctl.h>
78 #include <sys/select.h>
80 #define close(a) soclose(a)
81 #define select(a,b,c,d,e) bsdselect(a,b,c,d,e)
82 int _System
bsdselect(int,
87 int _System
soclose(int);
91 #include <sys/select.h>
99 # include <sys/filio.h>
102 # include <bstring.h>
109 # define SOCKLEN_T unsigned int
113 # define SOCKLEN_T socklen_t
116 # define SOCKLEN_T int
121 /* undefine for OSX - its really an int */
124 # define SOCKLEN_T int
126 #endif /* SOCKLEN_T */
129 * MSW defines this, Unices don't.
131 #ifndef INVALID_SOCKET
132 #define INVALID_SOCKET -1
135 /* UnixWare reportedly needs this for FIONBIO definition */
137 #include <sys/filio.h>
141 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
142 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
145 #define INADDR_NONE INADDR_BROADCAST
148 #define MASK_SIGNAL() \
150 void (*old_handler)(int); \
152 old_handler = signal(SIGPIPE, SIG_IGN);
154 #define UNMASK_SIGNAL() \
155 signal(SIGPIPE, old_handler); \
159 #ifndef __GSOCKET_STANDALONE__
160 # include "wx/unix/gsockunx.h"
161 # include "wx/gsocket.h"
163 # include "gsockunx.h"
164 # include "gsocket.h"
165 #endif /* __GSOCKET_STANDALONE__ */
167 /* debugging helpers */
168 #ifdef __GSOCKET_DEBUG__
169 # define GSocket_Debug(args) printf args
171 # define GSocket_Debug(args)
172 #endif /* __GSOCKET_DEBUG__ */
174 /* Table of GUI-related functions. We must call them indirectly because
175 * of wxBase and GUI separation: */
177 static GSocketGUIFunctionsTable
*gs_gui_functions
;
179 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
182 virtual bool OnInit();
183 virtual void OnExit();
184 virtual bool CanUseEventLoop();
185 virtual bool Init_Socket(GSocket
*socket
);
186 virtual void Destroy_Socket(GSocket
*socket
);
187 virtual void Install_Callback(GSocket
*socket
, GSocketEvent event
);
188 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
189 virtual void Enable_Events(GSocket
*socket
);
190 virtual void Disable_Events(GSocket
*socket
);
193 bool GSocketGUIFunctionsTableNull::OnInit()
195 void GSocketGUIFunctionsTableNull::OnExit()
197 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
199 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*socket
)
201 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*socket
)
203 void GSocketGUIFunctionsTableNull::Install_Callback(GSocket
*socket
, GSocketEvent event
)
205 void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
207 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*socket
)
209 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*socket
)
211 /* Global initialisers */
213 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
215 gs_gui_functions
= guifunc
;
218 int GSocket_Init(void)
220 if (!gs_gui_functions
)
222 static GSocketGUIFunctionsTableNull table
;
223 gs_gui_functions
= &table
;
225 if ( !gs_gui_functions
->OnInit() )
230 void GSocket_Cleanup(void)
232 if (gs_gui_functions
)
234 gs_gui_functions
->OnExit();
238 /* Constructors / Destructors for GSocket */
244 m_fd
= INVALID_SOCKET
;
245 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
252 m_error
= GSOCK_NOERROR
;
255 m_gui_dependent
= NULL
;
256 m_non_blocking
= false;
258 m_timeout
= 10*60*1000;
259 /* 10 minutes * 60 sec * 1000 millisec */
260 m_establishing
= false;
262 assert(gs_gui_functions
);
263 /* Per-socket GUI-specific initialization */
264 m_ok
= gs_gui_functions
->Init_Socket(this);
267 void GSocket::Close()
269 gs_gui_functions
->Disable_Events(this);
270 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
271 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
274 m_fd
= INVALID_SOCKET
;
281 /* Check that the socket is really shutdowned */
282 if (m_fd
!= INVALID_SOCKET
)
285 /* Per-socket GUI-specific cleanup */
286 gs_gui_functions
->Destroy_Socket(this);
288 /* Destroy private addresses */
290 GAddress_destroy(m_local
);
293 GAddress_destroy(m_peer
);
297 * Disallow further read/write operations on this socket, close
298 * the fd and disable all callbacks.
300 void GSocket::Shutdown()
306 /* If socket has been created, shutdown it */
307 if (m_fd
!= INVALID_SOCKET
)
313 /* Disable GUI callbacks */
314 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
315 m_cbacks
[evt
] = NULL
;
317 m_detected
= GSOCK_LOST_FLAG
;
320 /* Address handling */
326 * Set or get the local or peer address for this socket. The 'set'
327 * functions return GSOCK_NOERROR on success, an error code otherwise.
328 * The 'get' functions return a pointer to a GAddress object on success,
329 * or NULL otherwise, in which case they set the error code of the
330 * corresponding GSocket.
333 * GSOCK_INVSOCK - the socket is not valid.
334 * GSOCK_INVADDR - the address is not valid.
336 GSocketError
GSocket::SetLocal(GAddress
*address
)
340 /* the socket must be initialized, or it must be a server */
341 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
343 m_error
= GSOCK_INVSOCK
;
344 return GSOCK_INVSOCK
;
348 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
350 m_error
= GSOCK_INVADDR
;
351 return GSOCK_INVADDR
;
355 GAddress_destroy(m_local
);
357 m_local
= GAddress_copy(address
);
359 return GSOCK_NOERROR
;
362 GSocketError
GSocket::SetPeer(GAddress
*address
)
367 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
369 m_error
= GSOCK_INVADDR
;
370 return GSOCK_INVADDR
;
374 GAddress_destroy(m_peer
);
376 m_peer
= GAddress_copy(address
);
378 return GSOCK_NOERROR
;
381 GAddress
*GSocket::GetLocal()
384 struct sockaddr addr
;
385 SOCKLEN_T size
= sizeof(addr
);
390 /* try to get it from the m_local var first */
392 return GAddress_copy(m_local
);
394 /* else, if the socket is initialized, try getsockname */
395 if (m_fd
== INVALID_SOCKET
)
397 m_error
= GSOCK_INVSOCK
;
401 if (getsockname(m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
403 m_error
= GSOCK_IOERR
;
407 /* got a valid address from getsockname, create a GAddress object */
408 address
= GAddress_new();
411 m_error
= GSOCK_MEMERR
;
415 err
= _GAddress_translate_from(address
, &addr
, size
);
416 if (err
!= GSOCK_NOERROR
)
418 GAddress_destroy(address
);
426 GAddress
*GSocket::GetPeer()
430 /* try to get it from the m_peer var */
432 return GAddress_copy(m_peer
);
437 /* Server specific parts */
439 /* GSocket_SetServer:
440 * Sets up this socket as a server. The local address must have been
441 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
442 * Returns GSOCK_NOERROR on success, one of the following otherwise:
445 * GSOCK_INVSOCK - the socket is in use.
446 * GSOCK_INVADDR - the local address has not been set.
447 * GSOCK_IOERR - low-level error.
449 GSocketError
GSocket::SetServer()
455 /* must not be in use */
456 if (m_fd
!= INVALID_SOCKET
)
458 m_error
= GSOCK_INVSOCK
;
459 return GSOCK_INVSOCK
;
462 /* the local addr must have been set */
465 m_error
= GSOCK_INVADDR
;
466 return GSOCK_INVADDR
;
469 /* Initialize all fields */
473 /* Create the socket */
474 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
476 if (m_fd
== INVALID_SOCKET
)
478 m_error
= GSOCK_IOERR
;
481 ioctl(m_fd
, FIONBIO
, &arg
);
482 gs_gui_functions
->Enable_Events(this);
484 /* allow a socket to re-bind if the socket is in the TIME_WAIT
485 state after being previously closed.
488 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
490 /* Bind to the local address,
491 * retrieve the actual address bound,
492 * and listen up to 5 connections.
494 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
497 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
498 (listen(m_fd
, 5) != 0))
501 m_error
= GSOCK_IOERR
;
505 return GSOCK_NOERROR
;
508 /* GSocket_WaitConnection:
509 * Waits for an incoming client connection. Returns a pointer to
510 * a GSocket object, or NULL if there was an error, in which case
511 * the last error field will be updated for the calling GSocket.
513 * Error codes (set in the calling GSocket)
514 * GSOCK_INVSOCK - the socket is not valid or not a server.
515 * GSOCK_TIMEDOUT - timeout, no incoming connections.
516 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
517 * GSOCK_MEMERR - couldn't allocate memory.
518 * GSOCK_IOERR - low-level error.
520 GSocket
*GSocket::WaitConnection()
522 struct sockaddr from
;
523 SOCKLEN_T fromlen
= sizeof(from
);
530 /* Reenable CONNECTION events */
531 Enable(GSOCK_CONNECTION
);
533 /* If the socket has already been created, we exit immediately */
534 if (m_fd
== INVALID_SOCKET
|| !m_server
)
536 m_error
= GSOCK_INVSOCK
;
540 /* Create a GSocket object for the new connection */
541 connection
= GSocket_new();
545 m_error
= GSOCK_MEMERR
;
549 /* Wait for a connection (with timeout) */
550 if (Input_Timeout() == GSOCK_TIMEDOUT
)
553 /* m_error set by _GSocket_Input_Timeout */
557 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
559 if (connection
->m_fd
== INVALID_SOCKET
)
561 if (errno
== EWOULDBLOCK
)
562 m_error
= GSOCK_WOULDBLOCK
;
564 m_error
= GSOCK_IOERR
;
570 /* Initialize all fields */
571 connection
->m_server
= false;
572 connection
->m_stream
= true;
574 /* Setup the peer address field */
575 connection
->m_peer
= GAddress_new();
576 if (!connection
->m_peer
)
579 m_error
= GSOCK_MEMERR
;
582 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
583 if (err
!= GSOCK_NOERROR
)
585 GAddress_destroy(connection
->m_peer
);
590 #if defined(__EMX__) || defined(__VISAGECPP__)
591 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
593 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
595 gs_gui_functions
->Enable_Events(connection
);
600 bool GSocket::SetReusable()
602 /* socket must not be null, and must not be in use/already bound */
603 if (this && m_fd
== INVALID_SOCKET
) {
610 /* Client specific parts */
613 * For stream (connection oriented) sockets, GSocket_Connect() tries
614 * to establish a client connection to a server using the peer address
615 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
616 * connection has been succesfully established, or one of the error
617 * codes listed below. Note that for nonblocking sockets, a return
618 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
619 * request can be completed later; you should use GSocket_Select()
620 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
621 * corresponding asynchronous events.
623 * For datagram (non connection oriented) sockets, GSocket_Connect()
624 * just sets the peer address established with GSocket_SetPeer() as
625 * default destination.
628 * GSOCK_INVSOCK - the socket is in use or not valid.
629 * GSOCK_INVADDR - the peer address has not been established.
630 * GSOCK_TIMEDOUT - timeout, the connection failed.
631 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
632 * GSOCK_MEMERR - couldn't allocate memory.
633 * GSOCK_IOERR - low-level error.
635 GSocketError
GSocket::Connect(GSocketStream stream
)
642 /* Enable CONNECTION events (needed for nonblocking connections) */
643 Enable(GSOCK_CONNECTION
);
645 if (m_fd
!= INVALID_SOCKET
)
647 m_error
= GSOCK_INVSOCK
;
648 return GSOCK_INVSOCK
;
653 m_error
= GSOCK_INVADDR
;
654 return GSOCK_INVADDR
;
657 /* Streamed or dgram socket? */
658 m_stream
= (stream
== GSOCK_STREAMED
);
660 m_establishing
= false;
662 /* Create the socket */
663 m_fd
= socket(m_peer
->m_realfamily
,
664 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
666 if (m_fd
== INVALID_SOCKET
)
668 m_error
= GSOCK_IOERR
;
671 #if defined(__EMX__) || defined(__VISAGECPP__)
672 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
674 ioctl(m_fd
, FIONBIO
, &arg
);
676 gs_gui_functions
->Enable_Events(this);
678 /* Connect it to the peer address, with a timeout (see below) */
679 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
685 /* If connect failed with EINPROGRESS and the GSocket object
686 * is in blocking mode, we select() for the specified timeout
687 * checking for writability to see if the connection request
690 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
692 if (Output_Timeout() == GSOCK_TIMEDOUT
)
695 /* m_error is set in _GSocket_Output_Timeout */
696 return GSOCK_TIMEDOUT
;
701 SOCKLEN_T len
= sizeof(error
);
703 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
706 return GSOCK_NOERROR
;
710 /* If connect failed with EINPROGRESS and the GSocket object
711 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
712 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
713 * this way if the connection completes, a GSOCK_CONNECTION
714 * event will be generated, if enabled.
716 if ((err
== EINPROGRESS
) && (m_non_blocking
))
718 m_establishing
= true;
719 m_error
= GSOCK_WOULDBLOCK
;
720 return GSOCK_WOULDBLOCK
;
723 /* If connect failed with an error other than EINPROGRESS,
724 * then the call to GSocket_Connect has failed.
727 m_error
= GSOCK_IOERR
;
731 return GSOCK_NOERROR
;
734 /* Datagram sockets */
736 /* GSocket_SetNonOriented:
737 * Sets up this socket as a non-connection oriented (datagram) socket.
738 * Before using this function, the local address must have been set
739 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
740 * on success, or one of the following otherwise.
743 * GSOCK_INVSOCK - the socket is in use.
744 * GSOCK_INVADDR - the local address has not been set.
745 * GSOCK_IOERR - low-level error.
747 GSocketError
GSocket::SetNonOriented()
753 if (m_fd
!= INVALID_SOCKET
)
755 m_error
= GSOCK_INVSOCK
;
756 return GSOCK_INVSOCK
;
761 m_error
= GSOCK_INVADDR
;
762 return GSOCK_INVADDR
;
765 /* Initialize all fields */
769 /* Create the socket */
770 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
772 if (m_fd
== INVALID_SOCKET
)
774 m_error
= GSOCK_IOERR
;
777 #if defined(__EMX__) || defined(__VISAGECPP__)
778 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
780 ioctl(m_fd
, FIONBIO
, &arg
);
782 gs_gui_functions
->Enable_Events(this);
784 /* Bind to the local address,
785 * and retrieve the actual address bound.
787 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
790 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
793 m_error
= GSOCK_IOERR
;
797 return GSOCK_NOERROR
;
802 /* Like recv(), send(), ... */
803 int GSocket::Read(char *buffer
, int size
)
809 if (m_fd
== INVALID_SOCKET
|| m_server
)
811 m_error
= GSOCK_INVSOCK
;
815 /* Disable events during query of socket status */
816 Disable(GSOCK_INPUT
);
818 /* If the socket is blocking, wait for data (with a timeout) */
819 if (Input_Timeout() == GSOCK_TIMEDOUT
)
820 /* We no longer return here immediately, otherwise socket events would not be re-enabled! */
825 ret
= Recv_Stream(buffer
, size
);
827 ret
= Recv_Dgram(buffer
, size
);
832 if (errno
== EWOULDBLOCK
)
833 m_error
= GSOCK_WOULDBLOCK
;
835 m_error
= GSOCK_IOERR
;
838 /* Enable events again now that we are done processing */
844 int GSocket::Write(const char *buffer
, int size
)
850 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
852 if (m_fd
== INVALID_SOCKET
|| m_server
)
854 m_error
= GSOCK_INVSOCK
;
858 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
860 /* If the socket is blocking, wait for writability (with a timeout) */
861 if (Output_Timeout() == GSOCK_TIMEDOUT
)
864 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
868 ret
= Send_Stream(buffer
, size
);
870 ret
= Send_Dgram(buffer
, size
);
872 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
876 if (errno
== EWOULDBLOCK
)
878 m_error
= GSOCK_WOULDBLOCK
;
879 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
883 m_error
= GSOCK_IOERR
;
884 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
887 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
888 * in MSW). Once the first OUTPUT event is received, users can assume
889 * that the socket is writable until a read operation fails. Only then
890 * will further OUTPUT events be posted.
892 Enable(GSOCK_OUTPUT
);
896 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
902 * Polls the socket to determine its status. This function will
903 * check for the events specified in the 'flags' parameter, and
904 * it will return a mask indicating which operations can be
905 * performed. This function won't block, regardless of the
906 * mode (blocking | nonblocking) of the socket.
908 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
910 if (!gs_gui_functions
->CanUseEventLoop())
913 GSocketEventFlags result
= 0;
921 /* Do not use a static struct, Linux can garble it */
922 tv
.tv_sec
= m_timeout
/ 1000;
923 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
928 FD_SET(m_fd
, &readfds
);
929 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
930 FD_SET(m_fd
, &writefds
);
931 FD_SET(m_fd
, &exceptfds
);
933 /* Check 'sticky' CONNECTION flag first */
934 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
936 /* If we have already detected a LOST event, then don't try
937 * to do any further processing.
939 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
941 m_establishing
= false;
943 return (GSOCK_LOST_FLAG
& flags
);
947 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
949 /* What to do here? */
950 return (result
& flags
);
953 /* Check for readability */
954 if (FD_ISSET(m_fd
, &readfds
))
958 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
960 result
|= GSOCK_INPUT_FLAG
;
964 if (m_server
&& m_stream
)
966 result
|= GSOCK_CONNECTION_FLAG
;
967 m_detected
|= GSOCK_CONNECTION_FLAG
;
971 m_detected
= GSOCK_LOST_FLAG
;
972 m_establishing
= false;
974 /* LOST event: Abort any further processing */
975 return (GSOCK_LOST_FLAG
& flags
);
980 /* Check for writability */
981 if (FD_ISSET(m_fd
, &writefds
))
983 if (m_establishing
&& !m_server
)
986 SOCKLEN_T len
= sizeof(error
);
988 m_establishing
= false;
990 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
994 m_detected
= GSOCK_LOST_FLAG
;
996 /* LOST event: Abort any further processing */
997 return (GSOCK_LOST_FLAG
& flags
);
1001 result
|= GSOCK_CONNECTION_FLAG
;
1002 m_detected
|= GSOCK_CONNECTION_FLAG
;
1007 result
|= GSOCK_OUTPUT_FLAG
;
1011 /* Check for exceptions and errors (is this useful in Unices?) */
1012 if (FD_ISSET(m_fd
, &exceptfds
))
1014 m_establishing
= false;
1015 m_detected
= GSOCK_LOST_FLAG
;
1017 /* LOST event: Abort any further processing */
1018 return (GSOCK_LOST_FLAG
& flags
);
1021 return (result
& flags
);
1028 return flags
& m_detected
;
1035 /* GSocket_SetNonBlocking:
1036 * Sets the socket to non-blocking mode. All IO calls will return
1039 void GSocket::SetNonBlocking(bool non_block
)
1043 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1045 m_non_blocking
= non_block
;
1048 /* GSocket_SetTimeout:
1049 * Sets the timeout for blocking calls. Time is expressed in
1052 void GSocket::SetTimeout(unsigned long millisec
)
1056 m_timeout
= millisec
;
1059 /* GSocket_GetError:
1060 * Returns the last error occured for this socket. Note that successful
1061 * operations do not clear this back to GSOCK_NOERROR, so use it only
1064 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1074 * There is data to be read in the input buffer. If, after a read
1075 * operation, there is still data available, the callback function will
1078 * The socket is available for writing. That is, the next write call
1079 * won't block. This event is generated only once, when the connection is
1080 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1081 * when the output buffer empties again. This means that the app should
1082 * assume that it can write since the first OUTPUT event, and no more
1083 * OUTPUT events will be generated unless an error occurs.
1085 * Connection succesfully established, for client sockets, or incoming
1086 * client connection, for server sockets. Wait for this event (also watch
1087 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1089 * The connection is lost (or a connection request failed); this could
1090 * be due to a failure, or due to the peer closing it gracefully.
1093 /* GSocket_SetCallback:
1094 * Enables the callbacks specified by 'flags'. Note that 'flags'
1095 * may be a combination of flags OR'ed toghether, so the same
1096 * callback function can be made to accept different events.
1097 * The callback function must have the following prototype:
1099 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1101 void GSocket::SetCallback(GSocketEventFlags flags
,
1102 GSocketCallback callback
, char *cdata
)
1108 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1110 if ((flags
& (1 << count
)) != 0)
1112 m_cbacks
[count
] = callback
;
1113 m_data
[count
] = cdata
;
1118 /* GSocket_UnsetCallback:
1119 * Disables all callbacks specified by 'flags', which may be a
1120 * combination of flags OR'ed toghether.
1122 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1128 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1130 if ((flags
& (1 << count
)) != 0)
1132 m_cbacks
[count
] = NULL
;
1133 m_data
[count
] = NULL
;
1138 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1139 void *optval
, int *optlen
)
1141 if (getsockopt(m_fd
, level
, optname
, optval
, (SOCKLEN_T
*)optlen
) == 0)
1143 return GSOCK_NOERROR
;
1145 return GSOCK_OPTERR
;
1148 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1149 const void *optval
, int optlen
)
1151 if (setsockopt(m_fd
, level
, optname
, optval
, optlen
) == 0)
1153 return GSOCK_NOERROR
;
1155 return GSOCK_OPTERR
;
1158 #define CALL_CALLBACK(socket, event) { \
1159 socket->Disable(event); \
1160 if (socket->m_cbacks[event]) \
1161 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1165 void GSocket::Enable(GSocketEvent event
)
1167 m_detected
&= ~(1 << event
);
1168 gs_gui_functions
->Install_Callback(this, event
);
1171 void GSocket::Disable(GSocketEvent event
)
1173 m_detected
|= (1 << event
);
1174 gs_gui_functions
->Uninstall_Callback(this, event
);
1177 /* _GSocket_Input_Timeout:
1178 * For blocking sockets, wait until data is available or
1179 * until timeout ellapses.
1181 GSocketError
GSocket::Input_Timeout()
1187 /* Linux select() will overwrite the struct on return */
1188 tv
.tv_sec
= (m_timeout
/ 1000);
1189 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1191 if (!m_non_blocking
)
1194 FD_SET(m_fd
, &readfds
);
1195 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1198 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1199 m_error
= GSOCK_TIMEDOUT
;
1200 return GSOCK_TIMEDOUT
;
1204 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1205 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1206 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1207 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1208 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1209 m_error
= GSOCK_TIMEDOUT
;
1210 return GSOCK_TIMEDOUT
;
1213 return GSOCK_NOERROR
;
1216 /* _GSocket_Output_Timeout:
1217 * For blocking sockets, wait until data can be sent without
1218 * blocking or until timeout ellapses.
1220 GSocketError
GSocket::Output_Timeout()
1226 /* Linux select() will overwrite the struct on return */
1227 tv
.tv_sec
= (m_timeout
/ 1000);
1228 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1230 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1232 if (!m_non_blocking
)
1235 FD_SET(m_fd
, &writefds
);
1236 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1239 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1240 m_error
= GSOCK_TIMEDOUT
;
1241 return GSOCK_TIMEDOUT
;
1245 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1246 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1247 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1248 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1249 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1250 m_error
= GSOCK_TIMEDOUT
;
1251 return GSOCK_TIMEDOUT
;
1253 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1254 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1257 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1262 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1265 return GSOCK_NOERROR
;
1268 int GSocket::Recv_Stream(char *buffer
, int size
)
1270 return recv(m_fd
, buffer
, size
, 0);
1273 int GSocket::Recv_Dgram(char *buffer
, int size
)
1275 struct sockaddr from
;
1276 SOCKLEN_T fromlen
= sizeof(from
);
1280 fromlen
= sizeof(from
);
1282 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1287 /* Translate a system address into a GSocket address */
1290 m_peer
= GAddress_new();
1293 m_error
= GSOCK_MEMERR
;
1297 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1298 if (err
!= GSOCK_NOERROR
)
1300 GAddress_destroy(m_peer
);
1309 int GSocket::Send_Stream(const char *buffer
, int size
)
1313 #ifndef __VISAGECPP__
1315 ret
= send(m_fd
, buffer
, size
, 0);
1318 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1324 int GSocket::Send_Dgram(const char *buffer
, int size
)
1326 struct sockaddr
*addr
;
1332 m_error
= GSOCK_INVADDR
;
1336 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1337 if (err
!= GSOCK_NOERROR
)
1343 #ifndef __VISAGECPP__
1345 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1348 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1351 /* Frees memory allocated from _GAddress_translate_to */
1357 void GSocket::Detected_Read()
1361 /* If we have already detected a LOST event, then don't try
1362 * to do any further processing.
1364 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1366 m_establishing
= false;
1368 CALL_CALLBACK(this, GSOCK_LOST
);
1373 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1375 CALL_CALLBACK(this, GSOCK_INPUT
);
1379 if (m_server
&& m_stream
)
1381 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1385 CALL_CALLBACK(this, GSOCK_LOST
);
1391 void GSocket::Detected_Write()
1393 /* If we have already detected a LOST event, then don't try
1394 * to do any further processing.
1396 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1398 m_establishing
= false;
1400 CALL_CALLBACK(this, GSOCK_LOST
);
1405 if (m_establishing
&& !m_server
)
1408 SOCKLEN_T len
= sizeof(error
);
1410 m_establishing
= false;
1412 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1416 CALL_CALLBACK(this, GSOCK_LOST
);
1421 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1422 /* We have to fire this event by hand because CONNECTION (for clients)
1423 * and OUTPUT are internally the same and we just disabled CONNECTION
1424 * events with the above macro.
1426 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1431 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1435 /* Compatibility functions for GSocket */
1436 GSocket
*GSocket_new(void)
1438 GSocket
*newsocket
= new GSocket();
1439 if(newsocket
->IsOk())
1446 * -------------------------------------------------------------------------
1448 * -------------------------------------------------------------------------
1451 /* CHECK_ADDRESS verifies that the current address family is either
1452 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1453 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1454 * an appropiate error code.
1456 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1458 #define CHECK_ADDRESS(address, family) \
1460 if (address->m_family == GSOCK_NOFAMILY) \
1461 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1462 return address->m_error; \
1463 if (address->m_family != GSOCK_##family) \
1465 address->m_error = GSOCK_INVADDR; \
1466 return GSOCK_INVADDR; \
1470 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1472 if (address->m_family == GSOCK_NOFAMILY) \
1473 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1475 if (address->m_family != GSOCK_##family) \
1477 address->m_error = GSOCK_INVADDR; \
1483 GAddress
*GAddress_new(void)
1487 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1490 address
->m_family
= GSOCK_NOFAMILY
;
1491 address
->m_addr
= NULL
;
1497 GAddress
*GAddress_copy(GAddress
*address
)
1501 assert(address
!= NULL
);
1503 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1506 memcpy(addr2
, address
, sizeof(GAddress
));
1508 if (address
->m_addr
&& address
->m_len
> 0)
1510 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1511 if (addr2
->m_addr
== NULL
)
1516 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1522 void GAddress_destroy(GAddress
*address
)
1524 assert(address
!= NULL
);
1526 if (address
->m_addr
)
1527 free(address
->m_addr
);
1532 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1534 assert(address
!= NULL
);
1536 address
->m_family
= type
;
1539 GAddressType
GAddress_GetFamily(GAddress
*address
)
1541 assert(address
!= NULL
);
1543 return address
->m_family
;
1546 GSocketError
_GAddress_translate_from(GAddress
*address
,
1547 struct sockaddr
*addr
, int len
)
1549 address
->m_realfamily
= addr
->sa_family
;
1550 switch (addr
->sa_family
)
1553 address
->m_family
= GSOCK_INET
;
1556 address
->m_family
= GSOCK_UNIX
;
1560 address
->m_family
= GSOCK_INET6
;
1565 address
->m_error
= GSOCK_INVOP
;
1570 if (address
->m_addr
)
1571 free(address
->m_addr
);
1573 address
->m_len
= len
;
1574 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1576 if (address
->m_addr
== NULL
)
1578 address
->m_error
= GSOCK_MEMERR
;
1579 return GSOCK_MEMERR
;
1581 memcpy(address
->m_addr
, addr
, len
);
1583 return GSOCK_NOERROR
;
1586 GSocketError
_GAddress_translate_to(GAddress
*address
,
1587 struct sockaddr
**addr
, int *len
)
1589 if (!address
->m_addr
)
1591 address
->m_error
= GSOCK_INVADDR
;
1592 return GSOCK_INVADDR
;
1595 *len
= address
->m_len
;
1596 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1599 address
->m_error
= GSOCK_MEMERR
;
1600 return GSOCK_MEMERR
;
1603 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1604 return GSOCK_NOERROR
;
1608 * -------------------------------------------------------------------------
1609 * Internet address family
1610 * -------------------------------------------------------------------------
1613 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1615 address
->m_len
= sizeof(struct sockaddr_in
);
1616 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1617 if (address
->m_addr
== NULL
)
1619 address
->m_error
= GSOCK_MEMERR
;
1620 return GSOCK_MEMERR
;
1623 address
->m_family
= GSOCK_INET
;
1624 address
->m_realfamily
= PF_INET
;
1625 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1626 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1628 return GSOCK_NOERROR
;
1631 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1634 struct in_addr
*addr
;
1636 assert(address
!= NULL
);
1638 CHECK_ADDRESS(address
, INET
);
1640 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1642 /* If it is a numeric host name, convert it now */
1643 #if defined(HAVE_INET_ATON)
1644 if (inet_aton(hostname
, addr
) == 0)
1646 #elif defined(HAVE_INET_ADDR)
1647 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1650 /* Use gethostbyname by default */
1652 int val
= 1; /* VA doesn't like constants in conditional expressions */
1657 struct in_addr
*array_addr
;
1659 /* It is a real name, we solve it */
1660 if ((he
= gethostbyname(hostname
)) == NULL
)
1662 /* Reset to invalid address */
1663 addr
->s_addr
= INADDR_NONE
;
1664 address
->m_error
= GSOCK_NOHOST
;
1665 return GSOCK_NOHOST
;
1667 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1668 addr
->s_addr
= array_addr
[0].s_addr
;
1670 return GSOCK_NOERROR
;
1673 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1675 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1678 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1679 unsigned long hostaddr
)
1681 struct in_addr
*addr
;
1683 assert(address
!= NULL
);
1685 CHECK_ADDRESS(address
, INET
);
1687 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1688 addr
->s_addr
= htonl(hostaddr
);
1690 return GSOCK_NOERROR
;
1693 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1694 const char *protocol
)
1697 struct sockaddr_in
*addr
;
1699 assert(address
!= NULL
);
1700 CHECK_ADDRESS(address
, INET
);
1704 address
->m_error
= GSOCK_INVPORT
;
1705 return GSOCK_INVPORT
;
1708 #if defined(__WXPM__) && defined(__EMX__)
1709 se
= getservbyname(port
, (char*)protocol
);
1711 se
= getservbyname(port
, protocol
);
1715 /* the cast to int suppresses compiler warnings about subscript having the
1717 if (isdigit((int)port
[0]))
1721 port_int
= atoi(port
);
1722 addr
= (struct sockaddr_in
*)address
->m_addr
;
1723 addr
->sin_port
= htons(port_int
);
1724 return GSOCK_NOERROR
;
1727 address
->m_error
= GSOCK_INVPORT
;
1728 return GSOCK_INVPORT
;
1731 addr
= (struct sockaddr_in
*)address
->m_addr
;
1732 addr
->sin_port
= se
->s_port
;
1734 return GSOCK_NOERROR
;
1737 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1739 struct sockaddr_in
*addr
;
1741 assert(address
!= NULL
);
1742 CHECK_ADDRESS(address
, INET
);
1744 addr
= (struct sockaddr_in
*)address
->m_addr
;
1745 addr
->sin_port
= htons(port
);
1747 return GSOCK_NOERROR
;
1750 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1754 struct sockaddr_in
*addr
;
1756 assert(address
!= NULL
);
1757 CHECK_ADDRESS(address
, INET
);
1759 addr
= (struct sockaddr_in
*)address
->m_addr
;
1760 addr_buf
= (char *)&(addr
->sin_addr
);
1762 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1765 address
->m_error
= GSOCK_NOHOST
;
1766 return GSOCK_NOHOST
;
1769 strncpy(hostname
, he
->h_name
, sbuf
);
1771 return GSOCK_NOERROR
;
1774 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1776 struct sockaddr_in
*addr
;
1778 assert(address
!= NULL
);
1779 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1781 addr
= (struct sockaddr_in
*)address
->m_addr
;
1783 return ntohl(addr
->sin_addr
.s_addr
);
1786 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1788 struct sockaddr_in
*addr
;
1790 assert(address
!= NULL
);
1791 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1793 addr
= (struct sockaddr_in
*)address
->m_addr
;
1794 return ntohs(addr
->sin_port
);
1798 * -------------------------------------------------------------------------
1799 * Unix address family
1800 * -------------------------------------------------------------------------
1803 #ifndef __VISAGECPP__
1804 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1806 address
->m_len
= sizeof(struct sockaddr_un
);
1807 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1808 if (address
->m_addr
== NULL
)
1810 address
->m_error
= GSOCK_MEMERR
;
1811 return GSOCK_MEMERR
;
1814 address
->m_family
= GSOCK_UNIX
;
1815 address
->m_realfamily
= PF_UNIX
;
1816 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1817 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1819 return GSOCK_NOERROR
;
1822 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1824 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1826 struct sockaddr_un
*addr
;
1828 assert(address
!= NULL
);
1830 CHECK_ADDRESS(address
, UNIX
);
1832 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1833 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1834 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1836 return GSOCK_NOERROR
;
1839 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1841 struct sockaddr_un
*addr
;
1843 assert(address
!= NULL
);
1844 CHECK_ADDRESS(address
, UNIX
);
1846 addr
= (struct sockaddr_un
*)address
->m_addr
;
1848 strncpy(path
, addr
->sun_path
, sbuf
);
1850 return GSOCK_NOERROR
;
1852 #endif /* !defined(__VISAGECPP__) */
1853 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */