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 wxWidgets 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);
95 # include <sys/filio.h>
105 # define SOCKLEN_T unsigned int
109 # define SOCKLEN_T socklen_t
112 # define SOCKLEN_T int
116 #endif /* SOCKLEN_T */
119 * MSW defines this, Unices don't.
121 #ifndef INVALID_SOCKET
122 #define INVALID_SOCKET -1
125 /* UnixWare reportedly needs this for FIONBIO definition */
127 #include <sys/filio.h>
131 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
132 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
135 #define INADDR_NONE INADDR_BROADCAST
138 #define MASK_SIGNAL() \
140 void (*old_handler)(int); \
142 old_handler = signal(SIGPIPE, SIG_IGN);
144 #define UNMASK_SIGNAL() \
145 signal(SIGPIPE, old_handler); \
149 #ifndef __GSOCKET_STANDALONE__
150 # include "wx/unix/gsockunx.h"
151 # include "wx/gsocket.h"
153 # include "gsockunx.h"
154 # include "gsocket.h"
155 #endif /* __GSOCKET_STANDALONE__ */
157 /* debugging helpers */
158 #ifdef __GSOCKET_DEBUG__
159 # define GSocket_Debug(args) printf args
161 # define GSocket_Debug(args)
162 #endif /* __GSOCKET_DEBUG__ */
164 /* Table of GUI-related functions. We must call them indirectly because
165 * of wxBase and GUI separation: */
167 static struct GSocketGUIFunctionsTable
*gs_gui_functions
;
169 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
172 virtual bool OnInit();
173 virtual void OnExit();
174 virtual bool CanUseEventLoop();
175 virtual bool Init_Socket(GSocket
*socket
);
176 virtual void Destroy_Socket(GSocket
*socket
);
177 virtual void Install_Callback(GSocket
*socket
, GSocketEvent event
);
179 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
180 virtual void Enable_Events(GSocket
*socket
);
181 virtual void Disable_Events(GSocket
*socket
);
184 bool GSocketGUIFunctionsTableNull::OnInit()
186 void GSocketGUIFunctionsTableNull::OnExit()
188 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
190 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*socket
)
192 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*socket
)
194 void GSocketGUIFunctionsTableNull::Install_Callback(GSocket
*socket
, GSocketEvent event
)
196 void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
198 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*socket
)
200 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*socket
)
202 /* Global initialisers */
204 void GSocket_SetGUIFunctions(struct GSocketGUIFunctionsTable
*guifunc
)
206 gs_gui_functions
= guifunc
;
209 int GSocket_Init(void)
211 if (!gs_gui_functions
)
213 static class GSocketGUIFunctionsTableNull table
;
214 gs_gui_functions
= &table
;
216 if ( !gs_gui_functions
->OnInit() )
221 void GSocket_Cleanup(void)
223 if (gs_gui_functions
)
225 gs_gui_functions
->OnExit();
229 /* Constructors / Destructors for GSocket */
235 m_fd
= INVALID_SOCKET
;
236 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
243 m_error
= GSOCK_NOERROR
;
246 m_gui_dependent
= NULL
;
247 m_non_blocking
= FALSE
;
248 m_timeout
= 10*60*1000;
249 /* 10 minutes * 60 sec * 1000 millisec */
250 m_establishing
= FALSE
;
252 assert(gs_gui_functions
);
253 /* Per-socket GUI-specific initialization */
254 m_ok
= gs_gui_functions
->Init_Socket(this);
257 void GSocket::Close()
259 gs_gui_functions
->Disable_Events(this);
260 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
261 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
264 m_fd
= INVALID_SOCKET
;
271 /* Check that the socket is really shutdowned */
272 if (m_fd
!= INVALID_SOCKET
)
275 /* Per-socket GUI-specific cleanup */
276 gs_gui_functions
->Destroy_Socket(this);
278 /* Destroy private addresses */
280 GAddress_destroy(m_local
);
283 GAddress_destroy(m_peer
);
287 * Disallow further read/write operations on this socket, close
288 * the fd and disable all callbacks.
290 void GSocket::Shutdown()
296 /* If socket has been created, shutdown it */
297 if (m_fd
!= INVALID_SOCKET
)
303 /* Disable GUI callbacks */
304 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
305 m_cbacks
[evt
] = NULL
;
307 m_detected
= GSOCK_LOST_FLAG
;
310 /* Address handling */
316 * Set or get the local or peer address for this socket. The 'set'
317 * functions return GSOCK_NOERROR on success, an error code otherwise.
318 * The 'get' functions return a pointer to a GAddress object on success,
319 * or NULL otherwise, in which case they set the error code of the
320 * corresponding GSocket.
323 * GSOCK_INVSOCK - the socket is not valid.
324 * GSOCK_INVADDR - the address is not valid.
326 GSocketError
GSocket::SetLocal(GAddress
*address
)
330 /* the socket must be initialized, or it must be a server */
331 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
333 m_error
= GSOCK_INVSOCK
;
334 return GSOCK_INVSOCK
;
338 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
340 m_error
= GSOCK_INVADDR
;
341 return GSOCK_INVADDR
;
345 GAddress_destroy(m_local
);
347 m_local
= GAddress_copy(address
);
349 return GSOCK_NOERROR
;
352 GSocketError
GSocket::SetPeer(GAddress
*address
)
357 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
359 m_error
= GSOCK_INVADDR
;
360 return GSOCK_INVADDR
;
364 GAddress_destroy(m_peer
);
366 m_peer
= GAddress_copy(address
);
368 return GSOCK_NOERROR
;
371 GAddress
*GSocket::GetLocal()
374 struct sockaddr addr
;
375 SOCKLEN_T size
= sizeof(addr
);
380 /* try to get it from the m_local var first */
382 return GAddress_copy(m_local
);
384 /* else, if the socket is initialized, try getsockname */
385 if (m_fd
== INVALID_SOCKET
)
387 m_error
= GSOCK_INVSOCK
;
391 if (getsockname(m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
393 m_error
= GSOCK_IOERR
;
397 /* got a valid address from getsockname, create a GAddress object */
398 address
= GAddress_new();
401 m_error
= GSOCK_MEMERR
;
405 err
= _GAddress_translate_from(address
, &addr
, size
);
406 if (err
!= GSOCK_NOERROR
)
408 GAddress_destroy(address
);
416 GAddress
*GSocket::GetPeer()
420 /* try to get it from the m_peer var */
422 return GAddress_copy(m_peer
);
427 /* Server specific parts */
429 /* GSocket_SetServer:
430 * Sets up this socket as a server. The local address must have been
431 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
432 * Returns GSOCK_NOERROR on success, one of the following otherwise:
435 * GSOCK_INVSOCK - the socket is in use.
436 * GSOCK_INVADDR - the local address has not been set.
437 * GSOCK_IOERR - low-level error.
439 GSocketError
GSocket::SetServer()
445 /* must not be in use */
446 if (m_fd
!= INVALID_SOCKET
)
448 m_error
= GSOCK_INVSOCK
;
449 return GSOCK_INVSOCK
;
452 /* the local addr must have been set */
455 m_error
= GSOCK_INVADDR
;
456 return GSOCK_INVADDR
;
459 /* Initialize all fields */
463 /* Create the socket */
464 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
466 if (m_fd
== INVALID_SOCKET
)
468 m_error
= GSOCK_IOERR
;
471 #if defined(__EMX__) || defined(__VISAGECPP__)
472 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
474 ioctl(m_fd
, FIONBIO
, &arg
);
476 gs_gui_functions
->Enable_Events(this);
478 /* allow a socket to re-bind if the socket is in the TIME_WAIT
479 state after being previously closed.
482 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
484 /* Bind to the local address,
485 * retrieve the actual address bound,
486 * and listen up to 5 connections.
488 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
491 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
492 (listen(m_fd
, 5) != 0))
495 m_error
= GSOCK_IOERR
;
499 return GSOCK_NOERROR
;
502 /* GSocket_WaitConnection:
503 * Waits for an incoming client connection. Returns a pointer to
504 * a GSocket object, or NULL if there was an error, in which case
505 * the last error field will be updated for the calling GSocket.
507 * Error codes (set in the calling GSocket)
508 * GSOCK_INVSOCK - the socket is not valid or not a server.
509 * GSOCK_TIMEDOUT - timeout, no incoming connections.
510 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
511 * GSOCK_MEMERR - couldn't allocate memory.
512 * GSOCK_IOERR - low-level error.
514 GSocket
*GSocket::WaitConnection()
516 struct sockaddr from
;
517 SOCKLEN_T fromlen
= sizeof(from
);
524 /* Reenable CONNECTION events */
525 Enable(GSOCK_CONNECTION
);
527 /* If the socket has already been created, we exit immediately */
528 if (m_fd
== INVALID_SOCKET
|| !m_server
)
530 m_error
= GSOCK_INVSOCK
;
534 /* Create a GSocket object for the new connection */
535 connection
= GSocket_new();
539 m_error
= GSOCK_MEMERR
;
543 /* Wait for a connection (with timeout) */
544 if (Input_Timeout() == GSOCK_TIMEDOUT
)
546 GSocket_destroy(connection
);
547 /* m_error set by _GSocket_Input_Timeout */
551 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
553 if (connection
->m_fd
== INVALID_SOCKET
)
555 if (errno
== EWOULDBLOCK
)
556 m_error
= GSOCK_WOULDBLOCK
;
558 m_error
= GSOCK_IOERR
;
560 GSocket_destroy(connection
);
564 /* Initialize all fields */
565 connection
->m_server
= FALSE
;
566 connection
->m_stream
= TRUE
;
568 /* Setup the peer address field */
569 connection
->m_peer
= GAddress_new();
570 if (!connection
->m_peer
)
572 GSocket_destroy(connection
);
573 m_error
= GSOCK_MEMERR
;
576 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
577 if (err
!= GSOCK_NOERROR
)
579 GAddress_destroy(connection
->m_peer
);
580 GSocket_destroy(connection
);
584 #if defined(__EMX__) || defined(__VISAGECPP__)
585 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
587 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
589 gs_gui_functions
->Enable_Events(connection
);
594 int GSocket::SetReusable()
596 /* socket must not be null, and must not be in use/already bound */
597 if (this && m_fd
== INVALID_SOCKET
) {
604 /* Client specific parts */
607 * For stream (connection oriented) sockets, GSocket_Connect() tries
608 * to establish a client connection to a server using the peer address
609 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
610 * connection has been succesfully established, or one of the error
611 * codes listed below. Note that for nonblocking sockets, a return
612 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
613 * request can be completed later; you should use GSocket_Select()
614 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
615 * corresponding asynchronous events.
617 * For datagram (non connection oriented) sockets, GSocket_Connect()
618 * just sets the peer address established with GSocket_SetPeer() as
619 * default destination.
622 * GSOCK_INVSOCK - the socket is in use or not valid.
623 * GSOCK_INVADDR - the peer address has not been established.
624 * GSOCK_TIMEDOUT - timeout, the connection failed.
625 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
626 * GSOCK_MEMERR - couldn't allocate memory.
627 * GSOCK_IOERR - low-level error.
629 GSocketError
GSocket::Connect(GSocketStream stream
)
636 /* Enable CONNECTION events (needed for nonblocking connections) */
637 Enable(GSOCK_CONNECTION
);
639 if (m_fd
!= INVALID_SOCKET
)
641 m_error
= GSOCK_INVSOCK
;
642 return GSOCK_INVSOCK
;
647 m_error
= GSOCK_INVADDR
;
648 return GSOCK_INVADDR
;
651 /* Streamed or dgram socket? */
652 m_stream
= (stream
== GSOCK_STREAMED
);
654 m_establishing
= FALSE
;
656 /* Create the socket */
657 m_fd
= socket(m_peer
->m_realfamily
,
658 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
660 if (m_fd
== INVALID_SOCKET
)
662 m_error
= GSOCK_IOERR
;
665 #if defined(__EMX__) || defined(__VISAGECPP__)
666 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
668 ioctl(m_fd
, FIONBIO
, &arg
);
670 gs_gui_functions
->Enable_Events(this);
672 /* Connect it to the peer address, with a timeout (see below) */
673 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
679 /* If connect failed with EINPROGRESS and the GSocket object
680 * is in blocking mode, we select() for the specified timeout
681 * checking for writability to see if the connection request
684 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
686 if (Output_Timeout() == GSOCK_TIMEDOUT
)
689 /* m_error is set in _GSocket_Output_Timeout */
690 return GSOCK_TIMEDOUT
;
695 SOCKLEN_T len
= sizeof(error
);
697 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
700 return GSOCK_NOERROR
;
704 /* If connect failed with EINPROGRESS and the GSocket object
705 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
706 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
707 * this way if the connection completes, a GSOCK_CONNECTION
708 * event will be generated, if enabled.
710 if ((err
== EINPROGRESS
) && (m_non_blocking
))
712 m_establishing
= TRUE
;
713 m_error
= GSOCK_WOULDBLOCK
;
714 return GSOCK_WOULDBLOCK
;
717 /* If connect failed with an error other than EINPROGRESS,
718 * then the call to GSocket_Connect has failed.
721 m_error
= GSOCK_IOERR
;
725 return GSOCK_NOERROR
;
728 /* Datagram sockets */
730 /* GSocket_SetNonOriented:
731 * Sets up this socket as a non-connection oriented (datagram) socket.
732 * Before using this function, the local address must have been set
733 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
734 * on success, or one of the following otherwise.
737 * GSOCK_INVSOCK - the socket is in use.
738 * GSOCK_INVADDR - the local address has not been set.
739 * GSOCK_IOERR - low-level error.
741 GSocketError
GSocket::SetNonOriented()
747 if (m_fd
!= INVALID_SOCKET
)
749 m_error
= GSOCK_INVSOCK
;
750 return GSOCK_INVSOCK
;
755 m_error
= GSOCK_INVADDR
;
756 return GSOCK_INVADDR
;
759 /* Initialize all fields */
763 /* Create the socket */
764 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
766 if (m_fd
== INVALID_SOCKET
)
768 m_error
= GSOCK_IOERR
;
771 #if defined(__EMX__) || defined(__VISAGECPP__)
772 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
774 ioctl(m_fd
, FIONBIO
, &arg
);
776 gs_gui_functions
->Enable_Events(this);
778 /* Bind to the local address,
779 * and retrieve the actual address bound.
781 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
784 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
787 m_error
= GSOCK_IOERR
;
791 return GSOCK_NOERROR
;
796 /* Like recv(), send(), ... */
797 int GSocket::Read(char *buffer
, int size
)
803 if (m_fd
== INVALID_SOCKET
|| m_server
)
805 m_error
= GSOCK_INVSOCK
;
809 /* Disable events during query of socket status */
810 Disable(GSOCK_INPUT
);
812 /* If the socket is blocking, wait for data (with a timeout) */
813 if (Input_Timeout() == GSOCK_TIMEDOUT
)
814 /* We no longer return here immediately, otherwise socket events would not be re-enabled! */
819 ret
= Recv_Stream(buffer
, size
);
821 ret
= Recv_Dgram(buffer
, size
);
826 if (errno
== EWOULDBLOCK
)
827 m_error
= GSOCK_WOULDBLOCK
;
829 m_error
= GSOCK_IOERR
;
832 /* Enable events again now that we are done processing */
838 int GSocket::Write(const char *buffer
, int size
)
844 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
846 if (m_fd
== INVALID_SOCKET
|| m_server
)
848 m_error
= GSOCK_INVSOCK
;
852 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
854 /* If the socket is blocking, wait for writability (with a timeout) */
855 if (Output_Timeout() == GSOCK_TIMEDOUT
)
858 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
862 ret
= Send_Stream(buffer
, size
);
864 ret
= Send_Dgram(buffer
, size
);
866 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
870 if (errno
== EWOULDBLOCK
)
872 m_error
= GSOCK_WOULDBLOCK
;
873 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
877 m_error
= GSOCK_IOERR
;
878 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
881 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
882 * in MSW). Once the first OUTPUT event is received, users can assume
883 * that the socket is writable until a read operation fails. Only then
884 * will further OUTPUT events be posted.
886 Enable(GSOCK_OUTPUT
);
890 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
896 * Polls the socket to determine its status. This function will
897 * check for the events specified in the 'flags' parameter, and
898 * it will return a mask indicating which operations can be
899 * performed. This function won't block, regardless of the
900 * mode (blocking | nonblocking) of the socket.
902 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
904 if (!gs_gui_functions
->CanUseEventLoop())
907 GSocketEventFlags result
= 0;
915 /* Do not use a static struct, Linux can garble it */
916 tv
.tv_sec
= m_timeout
/ 1000;
917 tv
.tv_usec
= (m_timeout
% 1000) / 1000;
922 FD_SET(m_fd
, &readfds
);
923 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
924 FD_SET(m_fd
, &writefds
);
925 FD_SET(m_fd
, &exceptfds
);
927 /* Check 'sticky' CONNECTION flag first */
928 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
930 /* If we have already detected a LOST event, then don't try
931 * to do any further processing.
933 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
935 m_establishing
= FALSE
;
937 return (GSOCK_LOST_FLAG
& flags
);
941 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
943 /* What to do here? */
944 return (result
& flags
);
947 /* Check for readability */
948 if (FD_ISSET(m_fd
, &readfds
))
952 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
954 result
|= GSOCK_INPUT_FLAG
;
958 if (m_server
&& m_stream
)
960 result
|= GSOCK_CONNECTION_FLAG
;
961 m_detected
|= GSOCK_CONNECTION_FLAG
;
965 m_detected
= GSOCK_LOST_FLAG
;
966 m_establishing
= FALSE
;
968 /* LOST event: Abort any further processing */
969 return (GSOCK_LOST_FLAG
& flags
);
974 /* Check for writability */
975 if (FD_ISSET(m_fd
, &writefds
))
977 if (m_establishing
&& !m_server
)
980 SOCKLEN_T len
= sizeof(error
);
982 m_establishing
= FALSE
;
984 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
988 m_detected
= GSOCK_LOST_FLAG
;
990 /* LOST event: Abort any further processing */
991 return (GSOCK_LOST_FLAG
& flags
);
995 result
|= GSOCK_CONNECTION_FLAG
;
996 m_detected
|= GSOCK_CONNECTION_FLAG
;
1001 result
|= GSOCK_OUTPUT_FLAG
;
1005 /* Check for exceptions and errors (is this useful in Unices?) */
1006 if (FD_ISSET(m_fd
, &exceptfds
))
1008 m_establishing
= FALSE
;
1009 m_detected
= GSOCK_LOST_FLAG
;
1011 /* LOST event: Abort any further processing */
1012 return (GSOCK_LOST_FLAG
& flags
);
1015 return (result
& flags
);
1022 return flags
& m_detected
;
1029 /* GSocket_SetNonBlocking:
1030 * Sets the socket to non-blocking mode. All IO calls will return
1033 void GSocket::SetNonBlocking(int non_block
)
1037 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1039 m_non_blocking
= non_block
;
1042 /* GSocket_SetTimeout:
1043 * Sets the timeout for blocking calls. Time is expressed in
1046 void GSocket::SetTimeout(unsigned long millisec
)
1050 m_timeout
= millisec
;
1053 /* GSocket_GetError:
1054 * Returns the last error occured for this socket. Note that successful
1055 * operations do not clear this back to GSOCK_NOERROR, so use it only
1058 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1068 * There is data to be read in the input buffer. If, after a read
1069 * operation, there is still data available, the callback function will
1072 * The socket is available for writing. That is, the next write call
1073 * won't block. This event is generated only once, when the connection is
1074 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1075 * when the output buffer empties again. This means that the app should
1076 * assume that it can write since the first OUTPUT event, and no more
1077 * OUTPUT events will be generated unless an error occurs.
1079 * Connection succesfully established, for client sockets, or incoming
1080 * client connection, for server sockets. Wait for this event (also watch
1081 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1083 * The connection is lost (or a connection request failed); this could
1084 * be due to a failure, or due to the peer closing it gracefully.
1087 /* GSocket_SetCallback:
1088 * Enables the callbacks specified by 'flags'. Note that 'flags'
1089 * may be a combination of flags OR'ed toghether, so the same
1090 * callback function can be made to accept different events.
1091 * The callback function must have the following prototype:
1093 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1095 void GSocket::SetCallback(GSocketEventFlags flags
,
1096 GSocketCallback callback
, char *cdata
)
1102 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1104 if ((flags
& (1 << count
)) != 0)
1106 m_cbacks
[count
] = callback
;
1107 m_data
[count
] = cdata
;
1112 /* GSocket_UnsetCallback:
1113 * Disables all callbacks specified by 'flags', which may be a
1114 * combination of flags OR'ed toghether.
1116 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1122 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1124 if ((flags
& (1 << count
)) != 0)
1126 m_cbacks
[count
] = NULL
;
1127 m_data
[count
] = NULL
;
1132 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1133 void *optval
, int *optlen
)
1135 if (getsockopt(m_fd
, level
, optname
, optval
, optlen
) == 0)
1137 return GSOCK_NOERROR
;
1139 return GSOCK_OPTERR
;
1142 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1143 const void *optval
, int optlen
)
1145 if (setsockopt(m_fd
, level
, optname
, optval
, optlen
) == 0)
1147 return GSOCK_NOERROR
;
1149 return GSOCK_OPTERR
;
1152 #define CALL_CALLBACK(socket, event) { \
1153 socket->Disable(event); \
1154 if (socket->m_cbacks[event]) \
1155 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1159 void GSocket::Enable(GSocketEvent event
)
1161 m_detected
&= ~(1 << event
);
1162 gs_gui_functions
->Install_Callback(this, event
);
1165 void GSocket::Disable(GSocketEvent event
)
1167 m_detected
|= (1 << event
);
1168 gs_gui_functions
->Uninstall_Callback(this, event
);
1171 /* _GSocket_Input_Timeout:
1172 * For blocking sockets, wait until data is available or
1173 * until timeout ellapses.
1175 GSocketError
GSocket::Input_Timeout()
1181 /* Linux select() will overwrite the struct on return */
1182 tv
.tv_sec
= (m_timeout
/ 1000);
1183 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1185 if (!m_non_blocking
)
1188 FD_SET(m_fd
, &readfds
);
1189 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1192 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1193 m_error
= GSOCK_TIMEDOUT
;
1194 return GSOCK_TIMEDOUT
;
1198 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1199 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1200 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1201 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1202 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1203 m_error
= GSOCK_TIMEDOUT
;
1204 return GSOCK_TIMEDOUT
;
1207 return GSOCK_NOERROR
;
1210 /* _GSocket_Output_Timeout:
1211 * For blocking sockets, wait until data can be sent without
1212 * blocking or until timeout ellapses.
1214 GSocketError
GSocket::Output_Timeout()
1220 /* Linux select() will overwrite the struct on return */
1221 tv
.tv_sec
= (m_timeout
/ 1000);
1222 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1224 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1226 if (!m_non_blocking
)
1229 FD_SET(m_fd
, &writefds
);
1230 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1233 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1234 m_error
= GSOCK_TIMEDOUT
;
1235 return GSOCK_TIMEDOUT
;
1239 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1240 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1241 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1242 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1243 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1244 m_error
= GSOCK_TIMEDOUT
;
1245 return GSOCK_TIMEDOUT
;
1247 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1248 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1251 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1256 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1259 return GSOCK_NOERROR
;
1262 int GSocket::Recv_Stream(char *buffer
, int size
)
1264 return recv(m_fd
, buffer
, size
, 0);
1267 int GSocket::Recv_Dgram(char *buffer
, int size
)
1269 struct sockaddr from
;
1270 SOCKLEN_T fromlen
= sizeof(from
);
1274 fromlen
= sizeof(from
);
1276 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1281 /* Translate a system address into a GSocket address */
1284 m_peer
= GAddress_new();
1287 m_error
= GSOCK_MEMERR
;
1291 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1292 if (err
!= GSOCK_NOERROR
)
1294 GAddress_destroy(m_peer
);
1303 int GSocket::Send_Stream(const char *buffer
, int size
)
1307 #ifndef __VISAGECPP__
1309 ret
= send(m_fd
, buffer
, size
, 0);
1312 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1318 int GSocket::Send_Dgram(const char *buffer
, int size
)
1320 struct sockaddr
*addr
;
1326 m_error
= GSOCK_INVADDR
;
1330 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1331 if (err
!= GSOCK_NOERROR
)
1337 #ifndef __VISAGECPP__
1339 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1342 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1345 /* Frees memory allocated from _GAddress_translate_to */
1351 void GSocket::Detected_Read()
1355 /* If we have already detected a LOST event, then don't try
1356 * to do any further processing.
1358 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1360 m_establishing
= FALSE
;
1362 CALL_CALLBACK(this, GSOCK_LOST
);
1367 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1369 CALL_CALLBACK(this, GSOCK_INPUT
);
1373 if (m_server
&& m_stream
)
1375 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1379 CALL_CALLBACK(this, GSOCK_LOST
);
1385 void GSocket::Detected_Write()
1387 /* If we have already detected a LOST event, then don't try
1388 * to do any further processing.
1390 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1392 m_establishing
= FALSE
;
1394 CALL_CALLBACK(this, GSOCK_LOST
);
1399 if (m_establishing
&& !m_server
)
1402 SOCKLEN_T len
= sizeof(error
);
1404 m_establishing
= FALSE
;
1406 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1410 CALL_CALLBACK(this, GSOCK_LOST
);
1415 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1416 /* We have to fire this event by hand because CONNECTION (for clients)
1417 * and OUTPUT are internally the same and we just disabled CONNECTION
1418 * events with the above macro.
1420 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1425 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1429 /* Compatibility functions for GSocket */
1430 GSocket
*GSocket_new(void)
1432 GSocket
*newsocket
= new GSocket();
1433 if(newsocket
->IsOk())
1440 * -------------------------------------------------------------------------
1442 * -------------------------------------------------------------------------
1445 /* CHECK_ADDRESS verifies that the current address family is either
1446 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1447 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1448 * an appropiate error code.
1450 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1452 #define CHECK_ADDRESS(address, family) \
1454 if (address->m_family == GSOCK_NOFAMILY) \
1455 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1456 return address->m_error; \
1457 if (address->m_family != GSOCK_##family) \
1459 address->m_error = GSOCK_INVADDR; \
1460 return GSOCK_INVADDR; \
1464 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1466 if (address->m_family == GSOCK_NOFAMILY) \
1467 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1469 if (address->m_family != GSOCK_##family) \
1471 address->m_error = GSOCK_INVADDR; \
1477 GAddress
*GAddress_new(void)
1481 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1484 address
->m_family
= GSOCK_NOFAMILY
;
1485 address
->m_addr
= NULL
;
1491 GAddress
*GAddress_copy(GAddress
*address
)
1495 assert(address
!= NULL
);
1497 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1500 memcpy(addr2
, address
, sizeof(GAddress
));
1502 if (address
->m_addr
&& address
->m_len
> 0)
1504 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1505 if (addr2
->m_addr
== NULL
)
1510 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1516 void GAddress_destroy(GAddress
*address
)
1518 assert(address
!= NULL
);
1520 if (address
->m_addr
)
1521 free(address
->m_addr
);
1526 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1528 assert(address
!= NULL
);
1530 address
->m_family
= type
;
1533 GAddressType
GAddress_GetFamily(GAddress
*address
)
1535 assert(address
!= NULL
);
1537 return address
->m_family
;
1540 GSocketError
_GAddress_translate_from(GAddress
*address
,
1541 struct sockaddr
*addr
, int len
)
1543 address
->m_realfamily
= addr
->sa_family
;
1544 switch (addr
->sa_family
)
1547 address
->m_family
= GSOCK_INET
;
1550 address
->m_family
= GSOCK_UNIX
;
1554 address
->m_family
= GSOCK_INET6
;
1559 address
->m_error
= GSOCK_INVOP
;
1564 if (address
->m_addr
)
1565 free(address
->m_addr
);
1567 address
->m_len
= len
;
1568 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1570 if (address
->m_addr
== NULL
)
1572 address
->m_error
= GSOCK_MEMERR
;
1573 return GSOCK_MEMERR
;
1575 memcpy(address
->m_addr
, addr
, len
);
1577 return GSOCK_NOERROR
;
1580 GSocketError
_GAddress_translate_to(GAddress
*address
,
1581 struct sockaddr
**addr
, int *len
)
1583 if (!address
->m_addr
)
1585 address
->m_error
= GSOCK_INVADDR
;
1586 return GSOCK_INVADDR
;
1589 *len
= address
->m_len
;
1590 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1593 address
->m_error
= GSOCK_MEMERR
;
1594 return GSOCK_MEMERR
;
1597 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1598 return GSOCK_NOERROR
;
1602 * -------------------------------------------------------------------------
1603 * Internet address family
1604 * -------------------------------------------------------------------------
1607 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1609 address
->m_len
= sizeof(struct sockaddr_in
);
1610 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1611 if (address
->m_addr
== NULL
)
1613 address
->m_error
= GSOCK_MEMERR
;
1614 return GSOCK_MEMERR
;
1617 address
->m_family
= GSOCK_INET
;
1618 address
->m_realfamily
= PF_INET
;
1619 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1620 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1622 return GSOCK_NOERROR
;
1625 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1628 struct in_addr
*addr
;
1630 assert(address
!= NULL
);
1632 CHECK_ADDRESS(address
, INET
);
1634 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1636 /* If it is a numeric host name, convert it now */
1637 #if defined(HAVE_INET_ATON)
1638 if (inet_aton(hostname
, addr
) == 0)
1640 #elif defined(HAVE_INET_ADDR)
1641 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1644 /* Use gethostbyname by default */
1646 int val
= 1; /* VA doesn't like constants in conditional expressions */
1651 struct in_addr
*array_addr
;
1653 /* It is a real name, we solve it */
1654 if ((he
= gethostbyname(hostname
)) == NULL
)
1656 /* Reset to invalid address */
1657 addr
->s_addr
= INADDR_NONE
;
1658 address
->m_error
= GSOCK_NOHOST
;
1659 return GSOCK_NOHOST
;
1661 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1662 addr
->s_addr
= array_addr
[0].s_addr
;
1664 return GSOCK_NOERROR
;
1667 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1669 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1672 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1673 unsigned long hostaddr
)
1675 struct in_addr
*addr
;
1677 assert(address
!= NULL
);
1679 CHECK_ADDRESS(address
, INET
);
1681 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1682 addr
->s_addr
= htonl(hostaddr
);
1684 return GSOCK_NOERROR
;
1687 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1688 const char *protocol
)
1691 struct sockaddr_in
*addr
;
1693 assert(address
!= NULL
);
1694 CHECK_ADDRESS(address
, INET
);
1698 address
->m_error
= GSOCK_INVPORT
;
1699 return GSOCK_INVPORT
;
1702 se
= getservbyname(port
, protocol
);
1705 /* the cast to int suppresses compiler warnings about subscript having the
1707 if (isdigit((int)port
[0]))
1711 port_int
= atoi(port
);
1712 addr
= (struct sockaddr_in
*)address
->m_addr
;
1713 addr
->sin_port
= htons(port_int
);
1714 return GSOCK_NOERROR
;
1717 address
->m_error
= GSOCK_INVPORT
;
1718 return GSOCK_INVPORT
;
1721 addr
= (struct sockaddr_in
*)address
->m_addr
;
1722 addr
->sin_port
= se
->s_port
;
1724 return GSOCK_NOERROR
;
1727 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1729 struct sockaddr_in
*addr
;
1731 assert(address
!= NULL
);
1732 CHECK_ADDRESS(address
, INET
);
1734 addr
= (struct sockaddr_in
*)address
->m_addr
;
1735 addr
->sin_port
= htons(port
);
1737 return GSOCK_NOERROR
;
1740 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1744 struct sockaddr_in
*addr
;
1746 assert(address
!= NULL
);
1747 CHECK_ADDRESS(address
, INET
);
1749 addr
= (struct sockaddr_in
*)address
->m_addr
;
1750 addr_buf
= (char *)&(addr
->sin_addr
);
1752 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1755 address
->m_error
= GSOCK_NOHOST
;
1756 return GSOCK_NOHOST
;
1759 strncpy(hostname
, he
->h_name
, sbuf
);
1761 return GSOCK_NOERROR
;
1764 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1766 struct sockaddr_in
*addr
;
1768 assert(address
!= NULL
);
1769 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1771 addr
= (struct sockaddr_in
*)address
->m_addr
;
1773 return ntohl(addr
->sin_addr
.s_addr
);
1776 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1778 struct sockaddr_in
*addr
;
1780 assert(address
!= NULL
);
1781 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1783 addr
= (struct sockaddr_in
*)address
->m_addr
;
1784 return ntohs(addr
->sin_port
);
1788 * -------------------------------------------------------------------------
1789 * Unix address family
1790 * -------------------------------------------------------------------------
1793 #ifndef __VISAGECPP__
1794 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1796 address
->m_len
= sizeof(struct sockaddr_un
);
1797 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1798 if (address
->m_addr
== NULL
)
1800 address
->m_error
= GSOCK_MEMERR
;
1801 return GSOCK_MEMERR
;
1804 address
->m_family
= GSOCK_UNIX
;
1805 address
->m_realfamily
= PF_UNIX
;
1806 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1807 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1809 return GSOCK_NOERROR
;
1812 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1814 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1816 struct sockaddr_un
*addr
;
1818 assert(address
!= NULL
);
1820 CHECK_ADDRESS(address
, UNIX
);
1822 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1823 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1824 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1826 return GSOCK_NOERROR
;
1829 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1831 struct sockaddr_un
*addr
;
1833 assert(address
!= NULL
);
1834 CHECK_ADDRESS(address
, UNIX
);
1836 addr
= (struct sockaddr_un
*)address
->m_addr
;
1838 strncpy(path
, addr
->sun_path
, sbuf
);
1840 return GSOCK_NOERROR
;
1842 #endif /* !defined(__VISAGECPP__) */
1843 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */