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);
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
);
178 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
179 virtual void Enable_Events(GSocket
*socket
);
180 virtual void Disable_Events(GSocket
*socket
);
183 bool GSocketGUIFunctionsTableNull::OnInit()
185 void GSocketGUIFunctionsTableNull::OnExit()
187 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
189 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*socket
)
191 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*socket
)
193 void GSocketGUIFunctionsTableNull::Install_Callback(GSocket
*socket
, GSocketEvent event
)
195 void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket
*socket
, GSocketEvent event
)
197 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*socket
)
199 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*socket
)
201 /* Global initialisers */
203 void GSocket_SetGUIFunctions(struct GSocketGUIFunctionsTable
*guifunc
)
205 gs_gui_functions
= guifunc
;
208 int GSocket_Init(void)
210 if (!gs_gui_functions
)
212 static class GSocketGUIFunctionsTableNull table
;
213 gs_gui_functions
= &table
;
215 if ( !gs_gui_functions
->OnInit() )
220 void GSocket_Cleanup(void)
222 if (gs_gui_functions
)
224 gs_gui_functions
->OnExit();
228 /* Constructors / Destructors for GSocket */
234 m_fd
= INVALID_SOCKET
;
235 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
242 m_error
= GSOCK_NOERROR
;
245 m_gui_dependent
= NULL
;
246 m_non_blocking
= FALSE
;
247 m_timeout
= 10*60*1000;
248 /* 10 minutes * 60 sec * 1000 millisec */
249 m_establishing
= FALSE
;
251 assert(gs_gui_functions
);
252 /* Per-socket GUI-specific initialization */
253 m_ok
= gs_gui_functions
->Init_Socket(this);
256 void GSocket::Close()
258 gs_gui_functions
->Disable_Events(this);
259 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
260 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
263 m_fd
= INVALID_SOCKET
;
270 /* Check that the socket is really shutdowned */
271 if (m_fd
!= INVALID_SOCKET
)
274 /* Per-socket GUI-specific cleanup */
275 gs_gui_functions
->Destroy_Socket(this);
277 /* Destroy private addresses */
279 GAddress_destroy(m_local
);
282 GAddress_destroy(m_peer
);
286 * Disallow further read/write operations on this socket, close
287 * the fd and disable all callbacks.
289 void GSocket::Shutdown()
295 /* If socket has been created, shutdown it */
296 if (m_fd
!= INVALID_SOCKET
)
302 /* Disable GUI callbacks */
303 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
304 m_cbacks
[evt
] = NULL
;
306 m_detected
= GSOCK_LOST_FLAG
;
309 /* Address handling */
315 * Set or get the local or peer address for this socket. The 'set'
316 * functions return GSOCK_NOERROR on success, an error code otherwise.
317 * The 'get' functions return a pointer to a GAddress object on success,
318 * or NULL otherwise, in which case they set the error code of the
319 * corresponding GSocket.
322 * GSOCK_INVSOCK - the socket is not valid.
323 * GSOCK_INVADDR - the address is not valid.
325 GSocketError
GSocket::SetLocal(GAddress
*address
)
329 /* the socket must be initialized, or it must be a server */
330 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
332 m_error
= GSOCK_INVSOCK
;
333 return GSOCK_INVSOCK
;
337 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
339 m_error
= GSOCK_INVADDR
;
340 return GSOCK_INVADDR
;
344 GAddress_destroy(m_local
);
346 m_local
= GAddress_copy(address
);
348 return GSOCK_NOERROR
;
351 GSocketError
GSocket::SetPeer(GAddress
*address
)
356 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
358 m_error
= GSOCK_INVADDR
;
359 return GSOCK_INVADDR
;
363 GAddress_destroy(m_peer
);
365 m_peer
= GAddress_copy(address
);
367 return GSOCK_NOERROR
;
370 GAddress
*GSocket::GetLocal()
373 struct sockaddr addr
;
374 SOCKLEN_T size
= sizeof(addr
);
379 /* try to get it from the m_local var first */
381 return GAddress_copy(m_local
);
383 /* else, if the socket is initialized, try getsockname */
384 if (m_fd
== INVALID_SOCKET
)
386 m_error
= GSOCK_INVSOCK
;
390 if (getsockname(m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
392 m_error
= GSOCK_IOERR
;
396 /* got a valid address from getsockname, create a GAddress object */
397 address
= GAddress_new();
400 m_error
= GSOCK_MEMERR
;
404 err
= _GAddress_translate_from(address
, &addr
, size
);
405 if (err
!= GSOCK_NOERROR
)
407 GAddress_destroy(address
);
415 GAddress
*GSocket::GetPeer()
419 /* try to get it from the m_peer var */
421 return GAddress_copy(m_peer
);
426 /* Server specific parts */
428 /* GSocket_SetServer:
429 * Sets up this socket as a server. The local address must have been
430 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
431 * Returns GSOCK_NOERROR on success, one of the following otherwise:
434 * GSOCK_INVSOCK - the socket is in use.
435 * GSOCK_INVADDR - the local address has not been set.
436 * GSOCK_IOERR - low-level error.
438 GSocketError
GSocket::SetServer()
444 /* must not be in use */
445 if (m_fd
!= INVALID_SOCKET
)
447 m_error
= GSOCK_INVSOCK
;
448 return GSOCK_INVSOCK
;
451 /* the local addr must have been set */
454 m_error
= GSOCK_INVADDR
;
455 return GSOCK_INVADDR
;
458 /* Initialize all fields */
462 /* Create the socket */
463 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
465 if (m_fd
== INVALID_SOCKET
)
467 m_error
= GSOCK_IOERR
;
470 #if defined(__EMX__) || defined(__VISAGECPP__)
471 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
473 ioctl(m_fd
, FIONBIO
, &arg
);
475 gs_gui_functions
->Enable_Events(this);
477 /* allow a socket to re-bind if the socket is in the TIME_WAIT
478 state after being previously closed.
481 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
483 /* Bind to the local address,
484 * retrieve the actual address bound,
485 * and listen up to 5 connections.
487 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
490 (SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
491 (listen(m_fd
, 5) != 0))
494 m_error
= GSOCK_IOERR
;
498 return GSOCK_NOERROR
;
501 /* GSocket_WaitConnection:
502 * Waits for an incoming client connection. Returns a pointer to
503 * a GSocket object, or NULL if there was an error, in which case
504 * the last error field will be updated for the calling GSocket.
506 * Error codes (set in the calling GSocket)
507 * GSOCK_INVSOCK - the socket is not valid or not a server.
508 * GSOCK_TIMEDOUT - timeout, no incoming connections.
509 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
510 * GSOCK_MEMERR - couldn't allocate memory.
511 * GSOCK_IOERR - low-level error.
513 GSocket
*GSocket::WaitConnection()
515 struct sockaddr from
;
516 SOCKLEN_T fromlen
= sizeof(from
);
523 /* Reenable CONNECTION events */
524 Enable(GSOCK_CONNECTION
);
526 /* If the socket has already been created, we exit immediately */
527 if (m_fd
== INVALID_SOCKET
|| !m_server
)
529 m_error
= GSOCK_INVSOCK
;
533 /* Create a GSocket object for the new connection */
534 connection
= GSocket_new();
538 m_error
= GSOCK_MEMERR
;
542 /* Wait for a connection (with timeout) */
543 if (Input_Timeout() == GSOCK_TIMEDOUT
)
545 GSocket_destroy(connection
);
546 /* m_error set by _GSocket_Input_Timeout */
550 connection
->m_fd
= accept(m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
552 if (connection
->m_fd
== INVALID_SOCKET
)
554 if (errno
== EWOULDBLOCK
)
555 m_error
= GSOCK_WOULDBLOCK
;
557 m_error
= GSOCK_IOERR
;
559 GSocket_destroy(connection
);
563 /* Initialize all fields */
564 connection
->m_server
= FALSE
;
565 connection
->m_stream
= TRUE
;
567 /* Setup the peer address field */
568 connection
->m_peer
= GAddress_new();
569 if (!connection
->m_peer
)
571 GSocket_destroy(connection
);
572 m_error
= GSOCK_MEMERR
;
575 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
576 if (err
!= GSOCK_NOERROR
)
578 GAddress_destroy(connection
->m_peer
);
579 GSocket_destroy(connection
);
583 #if defined(__EMX__) || defined(__VISAGECPP__)
584 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
586 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
588 gs_gui_functions
->Enable_Events(connection
);
593 int GSocket::SetReusable()
595 /* socket must not be null, and must not be in use/already bound */
596 if (this && m_fd
== INVALID_SOCKET
) {
603 /* Client specific parts */
606 * For stream (connection oriented) sockets, GSocket_Connect() tries
607 * to establish a client connection to a server using the peer address
608 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
609 * connection has been succesfully established, or one of the error
610 * codes listed below. Note that for nonblocking sockets, a return
611 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
612 * request can be completed later; you should use GSocket_Select()
613 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
614 * corresponding asynchronous events.
616 * For datagram (non connection oriented) sockets, GSocket_Connect()
617 * just sets the peer address established with GSocket_SetPeer() as
618 * default destination.
621 * GSOCK_INVSOCK - the socket is in use or not valid.
622 * GSOCK_INVADDR - the peer address has not been established.
623 * GSOCK_TIMEDOUT - timeout, the connection failed.
624 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
625 * GSOCK_MEMERR - couldn't allocate memory.
626 * GSOCK_IOERR - low-level error.
628 GSocketError
GSocket::Connect(GSocketStream stream
)
635 /* Enable CONNECTION events (needed for nonblocking connections) */
636 Enable(GSOCK_CONNECTION
);
638 if (m_fd
!= INVALID_SOCKET
)
640 m_error
= GSOCK_INVSOCK
;
641 return GSOCK_INVSOCK
;
646 m_error
= GSOCK_INVADDR
;
647 return GSOCK_INVADDR
;
650 /* Streamed or dgram socket? */
651 m_stream
= (stream
== GSOCK_STREAMED
);
653 m_establishing
= FALSE
;
655 /* Create the socket */
656 m_fd
= socket(m_peer
->m_realfamily
,
657 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
659 if (m_fd
== INVALID_SOCKET
)
661 m_error
= GSOCK_IOERR
;
664 #if defined(__EMX__) || defined(__VISAGECPP__)
665 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
667 ioctl(m_fd
, FIONBIO
, &arg
);
669 gs_gui_functions
->Enable_Events(this);
671 /* Connect it to the peer address, with a timeout (see below) */
672 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
678 /* If connect failed with EINPROGRESS and the GSocket object
679 * is in blocking mode, we select() for the specified timeout
680 * checking for writability to see if the connection request
683 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
685 if (Output_Timeout() == GSOCK_TIMEDOUT
)
688 /* m_error is set in _GSocket_Output_Timeout */
689 return GSOCK_TIMEDOUT
;
694 SOCKLEN_T len
= sizeof(error
);
696 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
699 return GSOCK_NOERROR
;
703 /* If connect failed with EINPROGRESS and the GSocket object
704 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
705 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
706 * this way if the connection completes, a GSOCK_CONNECTION
707 * event will be generated, if enabled.
709 if ((err
== EINPROGRESS
) && (m_non_blocking
))
711 m_establishing
= TRUE
;
712 m_error
= GSOCK_WOULDBLOCK
;
713 return GSOCK_WOULDBLOCK
;
716 /* If connect failed with an error other than EINPROGRESS,
717 * then the call to GSocket_Connect has failed.
720 m_error
= GSOCK_IOERR
;
724 return GSOCK_NOERROR
;
727 /* Datagram sockets */
729 /* GSocket_SetNonOriented:
730 * Sets up this socket as a non-connection oriented (datagram) socket.
731 * Before using this function, the local address must have been set
732 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
733 * on success, or one of the following otherwise.
736 * GSOCK_INVSOCK - the socket is in use.
737 * GSOCK_INVADDR - the local address has not been set.
738 * GSOCK_IOERR - low-level error.
740 GSocketError
GSocket::SetNonOriented()
746 if (m_fd
!= INVALID_SOCKET
)
748 m_error
= GSOCK_INVSOCK
;
749 return GSOCK_INVSOCK
;
754 m_error
= GSOCK_INVADDR
;
755 return GSOCK_INVADDR
;
758 /* Initialize all fields */
762 /* Create the socket */
763 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
765 if (m_fd
== INVALID_SOCKET
)
767 m_error
= GSOCK_IOERR
;
770 #if defined(__EMX__) || defined(__VISAGECPP__)
771 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
773 ioctl(m_fd
, FIONBIO
, &arg
);
775 gs_gui_functions
->Enable_Events(this);
777 /* Bind to the local address,
778 * and retrieve the actual address bound.
780 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
783 (SOCKLEN_T
*) &m_local
->m_len
) != 0))
786 m_error
= GSOCK_IOERR
;
790 return GSOCK_NOERROR
;
795 /* Like recv(), send(), ... */
796 int GSocket::Read(char *buffer
, int size
)
802 if (m_fd
== INVALID_SOCKET
|| m_server
)
804 m_error
= GSOCK_INVSOCK
;
808 /* Disable events during query of socket status */
809 Disable(GSOCK_INPUT
);
811 /* If the socket is blocking, wait for data (with a timeout) */
812 if (Input_Timeout() == GSOCK_TIMEDOUT
)
813 /* We no longer return here immediately, otherwise socket events would not be re-enabled! */
818 ret
= Recv_Stream(buffer
, size
);
820 ret
= Recv_Dgram(buffer
, size
);
825 if (errno
== EWOULDBLOCK
)
826 m_error
= GSOCK_WOULDBLOCK
;
828 m_error
= GSOCK_IOERR
;
831 /* Enable events again now that we are done processing */
837 int GSocket::Write(const char *buffer
, int size
)
843 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
845 if (m_fd
== INVALID_SOCKET
|| m_server
)
847 m_error
= GSOCK_INVSOCK
;
851 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
853 /* If the socket is blocking, wait for writability (with a timeout) */
854 if (Output_Timeout() == GSOCK_TIMEDOUT
)
857 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
861 ret
= Send_Stream(buffer
, size
);
863 ret
= Send_Dgram(buffer
, size
);
865 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
869 if (errno
== EWOULDBLOCK
)
871 m_error
= GSOCK_WOULDBLOCK
;
872 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
876 m_error
= GSOCK_IOERR
;
877 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
880 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
881 * in MSW). Once the first OUTPUT event is received, users can assume
882 * that the socket is writable until a read operation fails. Only then
883 * will further OUTPUT events be posted.
885 Enable(GSOCK_OUTPUT
);
889 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
895 * Polls the socket to determine its status. This function will
896 * check for the events specified in the 'flags' parameter, and
897 * it will return a mask indicating which operations can be
898 * performed. This function won't block, regardless of the
899 * mode (blocking | nonblocking) of the socket.
901 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
903 if (!gs_gui_functions
->CanUseEventLoop())
906 GSocketEventFlags result
= 0;
914 /* Do not use a static struct, Linux can garble it */
915 tv
.tv_sec
= m_timeout
/ 1000;
916 tv
.tv_usec
= (m_timeout
% 1000) / 1000;
921 FD_SET(m_fd
, &readfds
);
922 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
923 FD_SET(m_fd
, &writefds
);
924 FD_SET(m_fd
, &exceptfds
);
926 /* Check 'sticky' CONNECTION flag first */
927 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
929 /* If we have already detected a LOST event, then don't try
930 * to do any further processing.
932 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
934 m_establishing
= FALSE
;
936 return (GSOCK_LOST_FLAG
& flags
);
940 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
942 /* What to do here? */
943 return (result
& flags
);
946 /* Check for readability */
947 if (FD_ISSET(m_fd
, &readfds
))
951 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
953 result
|= GSOCK_INPUT_FLAG
;
957 if (m_server
&& m_stream
)
959 result
|= GSOCK_CONNECTION_FLAG
;
960 m_detected
|= GSOCK_CONNECTION_FLAG
;
964 m_detected
= GSOCK_LOST_FLAG
;
965 m_establishing
= FALSE
;
967 /* LOST event: Abort any further processing */
968 return (GSOCK_LOST_FLAG
& flags
);
973 /* Check for writability */
974 if (FD_ISSET(m_fd
, &writefds
))
976 if (m_establishing
&& !m_server
)
979 SOCKLEN_T len
= sizeof(error
);
981 m_establishing
= FALSE
;
983 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
987 m_detected
= GSOCK_LOST_FLAG
;
989 /* LOST event: Abort any further processing */
990 return (GSOCK_LOST_FLAG
& flags
);
994 result
|= GSOCK_CONNECTION_FLAG
;
995 m_detected
|= GSOCK_CONNECTION_FLAG
;
1000 result
|= GSOCK_OUTPUT_FLAG
;
1004 /* Check for exceptions and errors (is this useful in Unices?) */
1005 if (FD_ISSET(m_fd
, &exceptfds
))
1007 m_establishing
= FALSE
;
1008 m_detected
= GSOCK_LOST_FLAG
;
1010 /* LOST event: Abort any further processing */
1011 return (GSOCK_LOST_FLAG
& flags
);
1014 return (result
& flags
);
1021 return flags
& m_detected
;
1028 /* GSocket_SetNonBlocking:
1029 * Sets the socket to non-blocking mode. All IO calls will return
1032 void GSocket::SetNonBlocking(int non_block
)
1036 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1038 m_non_blocking
= non_block
;
1041 /* GSocket_SetTimeout:
1042 * Sets the timeout for blocking calls. Time is expressed in
1045 void GSocket::SetTimeout(unsigned long millisec
)
1049 m_timeout
= millisec
;
1052 /* GSocket_GetError:
1053 * Returns the last error occured for this socket. Note that successful
1054 * operations do not clear this back to GSOCK_NOERROR, so use it only
1057 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1067 * There is data to be read in the input buffer. If, after a read
1068 * operation, there is still data available, the callback function will
1071 * The socket is available for writing. That is, the next write call
1072 * won't block. This event is generated only once, when the connection is
1073 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1074 * when the output buffer empties again. This means that the app should
1075 * assume that it can write since the first OUTPUT event, and no more
1076 * OUTPUT events will be generated unless an error occurs.
1078 * Connection succesfully established, for client sockets, or incoming
1079 * client connection, for server sockets. Wait for this event (also watch
1080 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1082 * The connection is lost (or a connection request failed); this could
1083 * be due to a failure, or due to the peer closing it gracefully.
1086 /* GSocket_SetCallback:
1087 * Enables the callbacks specified by 'flags'. Note that 'flags'
1088 * may be a combination of flags OR'ed toghether, so the same
1089 * callback function can be made to accept different events.
1090 * The callback function must have the following prototype:
1092 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1094 void GSocket::SetCallback(GSocketEventFlags flags
,
1095 GSocketCallback callback
, char *cdata
)
1101 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1103 if ((flags
& (1 << count
)) != 0)
1105 m_cbacks
[count
] = callback
;
1106 m_data
[count
] = cdata
;
1111 /* GSocket_UnsetCallback:
1112 * Disables all callbacks specified by 'flags', which may be a
1113 * combination of flags OR'ed toghether.
1115 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1121 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1123 if ((flags
& (1 << count
)) != 0)
1125 m_cbacks
[count
] = NULL
;
1126 m_data
[count
] = NULL
;
1131 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1132 void *optval
, int *optlen
)
1134 if (getsockopt(m_fd
, level
, optname
, optval
, optlen
) == 0)
1136 return GSOCK_NOERROR
;
1138 return GSOCK_OPTERR
;
1141 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1142 const void *optval
, int optlen
)
1144 if (setsockopt(m_fd
, level
, optname
, optval
, optlen
) == 0)
1146 return GSOCK_NOERROR
;
1148 return GSOCK_OPTERR
;
1151 #define CALL_CALLBACK(socket, event) { \
1152 socket->Disable(event); \
1153 if (socket->m_cbacks[event]) \
1154 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1158 void GSocket::Enable(GSocketEvent event
)
1160 m_detected
&= ~(1 << event
);
1161 gs_gui_functions
->Install_Callback(this, event
);
1164 void GSocket::Disable(GSocketEvent event
)
1166 m_detected
|= (1 << event
);
1167 gs_gui_functions
->Uninstall_Callback(this, event
);
1170 /* _GSocket_Input_Timeout:
1171 * For blocking sockets, wait until data is available or
1172 * until timeout ellapses.
1174 GSocketError
GSocket::Input_Timeout()
1180 /* Linux select() will overwrite the struct on return */
1181 tv
.tv_sec
= (m_timeout
/ 1000);
1182 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1184 if (!m_non_blocking
)
1187 FD_SET(m_fd
, &readfds
);
1188 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1191 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1192 m_error
= GSOCK_TIMEDOUT
;
1193 return GSOCK_TIMEDOUT
;
1197 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1198 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1199 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1200 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1201 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1202 m_error
= GSOCK_TIMEDOUT
;
1203 return GSOCK_TIMEDOUT
;
1206 return GSOCK_NOERROR
;
1209 /* _GSocket_Output_Timeout:
1210 * For blocking sockets, wait until data can be sent without
1211 * blocking or until timeout ellapses.
1213 GSocketError
GSocket::Output_Timeout()
1219 /* Linux select() will overwrite the struct on return */
1220 tv
.tv_sec
= (m_timeout
/ 1000);
1221 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1223 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1225 if (!m_non_blocking
)
1228 FD_SET(m_fd
, &writefds
);
1229 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1232 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1233 m_error
= GSOCK_TIMEDOUT
;
1234 return GSOCK_TIMEDOUT
;
1238 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1239 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1240 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1241 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1242 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1243 m_error
= GSOCK_TIMEDOUT
;
1244 return GSOCK_TIMEDOUT
;
1246 if ( ! FD_ISSET(m_fd
, &writefds
) ) {
1247 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1250 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1255 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1258 return GSOCK_NOERROR
;
1261 int GSocket::Recv_Stream(char *buffer
, int size
)
1263 return recv(m_fd
, buffer
, size
, 0);
1266 int GSocket::Recv_Dgram(char *buffer
, int size
)
1268 struct sockaddr from
;
1269 SOCKLEN_T fromlen
= sizeof(from
);
1273 fromlen
= sizeof(from
);
1275 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1280 /* Translate a system address into a GSocket address */
1283 m_peer
= GAddress_new();
1286 m_error
= GSOCK_MEMERR
;
1290 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1291 if (err
!= GSOCK_NOERROR
)
1293 GAddress_destroy(m_peer
);
1302 int GSocket::Send_Stream(const char *buffer
, int size
)
1306 #ifndef __VISAGECPP__
1308 ret
= send(m_fd
, buffer
, size
, 0);
1311 ret
= send(m_fd
, (char *)buffer
, size
, 0);
1317 int GSocket::Send_Dgram(const char *buffer
, int size
)
1319 struct sockaddr
*addr
;
1325 m_error
= GSOCK_INVADDR
;
1329 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1330 if (err
!= GSOCK_NOERROR
)
1336 #ifndef __VISAGECPP__
1338 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1341 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1344 /* Frees memory allocated from _GAddress_translate_to */
1350 void GSocket::Detected_Read()
1354 /* If we have already detected a LOST event, then don't try
1355 * to do any further processing.
1357 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1359 m_establishing
= FALSE
;
1361 CALL_CALLBACK(this, GSOCK_LOST
);
1366 if (recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
1368 CALL_CALLBACK(this, GSOCK_INPUT
);
1372 if (m_server
&& m_stream
)
1374 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1378 CALL_CALLBACK(this, GSOCK_LOST
);
1384 void GSocket::Detected_Write()
1386 /* If we have already detected a LOST event, then don't try
1387 * to do any further processing.
1389 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1391 m_establishing
= FALSE
;
1393 CALL_CALLBACK(this, GSOCK_LOST
);
1398 if (m_establishing
&& !m_server
)
1401 SOCKLEN_T len
= sizeof(error
);
1403 m_establishing
= FALSE
;
1405 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1409 CALL_CALLBACK(this, GSOCK_LOST
);
1414 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1415 /* We have to fire this event by hand because CONNECTION (for clients)
1416 * and OUTPUT are internally the same and we just disabled CONNECTION
1417 * events with the above macro.
1419 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1424 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1428 /* Compatibility functions for GSocket */
1429 GSocket
*GSocket_new(void)
1431 GSocket
*newsocket
= new GSocket();
1432 if(newsocket
->IsOk())
1439 * -------------------------------------------------------------------------
1441 * -------------------------------------------------------------------------
1444 /* CHECK_ADDRESS verifies that the current address family is either
1445 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1446 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1447 * an appropiate error code.
1449 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1451 #define CHECK_ADDRESS(address, family) \
1453 if (address->m_family == GSOCK_NOFAMILY) \
1454 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1455 return address->m_error; \
1456 if (address->m_family != GSOCK_##family) \
1458 address->m_error = GSOCK_INVADDR; \
1459 return GSOCK_INVADDR; \
1463 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1465 if (address->m_family == GSOCK_NOFAMILY) \
1466 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1468 if (address->m_family != GSOCK_##family) \
1470 address->m_error = GSOCK_INVADDR; \
1476 GAddress
*GAddress_new(void)
1480 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1483 address
->m_family
= GSOCK_NOFAMILY
;
1484 address
->m_addr
= NULL
;
1490 GAddress
*GAddress_copy(GAddress
*address
)
1494 assert(address
!= NULL
);
1496 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1499 memcpy(addr2
, address
, sizeof(GAddress
));
1501 if (address
->m_addr
&& address
->m_len
> 0)
1503 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1504 if (addr2
->m_addr
== NULL
)
1509 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1515 void GAddress_destroy(GAddress
*address
)
1517 assert(address
!= NULL
);
1519 if (address
->m_addr
)
1520 free(address
->m_addr
);
1525 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1527 assert(address
!= NULL
);
1529 address
->m_family
= type
;
1532 GAddressType
GAddress_GetFamily(GAddress
*address
)
1534 assert(address
!= NULL
);
1536 return address
->m_family
;
1539 GSocketError
_GAddress_translate_from(GAddress
*address
,
1540 struct sockaddr
*addr
, int len
)
1542 address
->m_realfamily
= addr
->sa_family
;
1543 switch (addr
->sa_family
)
1546 address
->m_family
= GSOCK_INET
;
1549 address
->m_family
= GSOCK_UNIX
;
1553 address
->m_family
= GSOCK_INET6
;
1558 address
->m_error
= GSOCK_INVOP
;
1563 if (address
->m_addr
)
1564 free(address
->m_addr
);
1566 address
->m_len
= len
;
1567 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1569 if (address
->m_addr
== NULL
)
1571 address
->m_error
= GSOCK_MEMERR
;
1572 return GSOCK_MEMERR
;
1574 memcpy(address
->m_addr
, addr
, len
);
1576 return GSOCK_NOERROR
;
1579 GSocketError
_GAddress_translate_to(GAddress
*address
,
1580 struct sockaddr
**addr
, int *len
)
1582 if (!address
->m_addr
)
1584 address
->m_error
= GSOCK_INVADDR
;
1585 return GSOCK_INVADDR
;
1588 *len
= address
->m_len
;
1589 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1592 address
->m_error
= GSOCK_MEMERR
;
1593 return GSOCK_MEMERR
;
1596 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1597 return GSOCK_NOERROR
;
1601 * -------------------------------------------------------------------------
1602 * Internet address family
1603 * -------------------------------------------------------------------------
1606 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1608 address
->m_len
= sizeof(struct sockaddr_in
);
1609 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1610 if (address
->m_addr
== NULL
)
1612 address
->m_error
= GSOCK_MEMERR
;
1613 return GSOCK_MEMERR
;
1616 address
->m_family
= GSOCK_INET
;
1617 address
->m_realfamily
= PF_INET
;
1618 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1619 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1621 return GSOCK_NOERROR
;
1624 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1627 struct in_addr
*addr
;
1629 assert(address
!= NULL
);
1631 CHECK_ADDRESS(address
, INET
);
1633 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1635 /* If it is a numeric host name, convert it now */
1636 #if defined(HAVE_INET_ATON)
1637 if (inet_aton(hostname
, addr
) == 0)
1639 #elif defined(HAVE_INET_ADDR)
1640 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1643 /* Use gethostbyname by default */
1645 int val
= 1; /* VA doesn't like constants in conditional expressions */
1650 struct in_addr
*array_addr
;
1652 /* It is a real name, we solve it */
1653 if ((he
= gethostbyname(hostname
)) == NULL
)
1655 /* Reset to invalid address */
1656 addr
->s_addr
= INADDR_NONE
;
1657 address
->m_error
= GSOCK_NOHOST
;
1658 return GSOCK_NOHOST
;
1660 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1661 addr
->s_addr
= array_addr
[0].s_addr
;
1663 return GSOCK_NOERROR
;
1666 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1668 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1671 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1672 unsigned long hostaddr
)
1674 struct in_addr
*addr
;
1676 assert(address
!= NULL
);
1678 CHECK_ADDRESS(address
, INET
);
1680 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1681 addr
->s_addr
= htonl(hostaddr
);
1683 return GSOCK_NOERROR
;
1686 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1687 const char *protocol
)
1690 struct sockaddr_in
*addr
;
1692 assert(address
!= NULL
);
1693 CHECK_ADDRESS(address
, INET
);
1697 address
->m_error
= GSOCK_INVPORT
;
1698 return GSOCK_INVPORT
;
1701 se
= getservbyname(port
, protocol
);
1704 /* the cast to int suppresses compiler warnings about subscript having the
1706 if (isdigit((int)port
[0]))
1710 port_int
= atoi(port
);
1711 addr
= (struct sockaddr_in
*)address
->m_addr
;
1712 addr
->sin_port
= htons(port_int
);
1713 return GSOCK_NOERROR
;
1716 address
->m_error
= GSOCK_INVPORT
;
1717 return GSOCK_INVPORT
;
1720 addr
= (struct sockaddr_in
*)address
->m_addr
;
1721 addr
->sin_port
= se
->s_port
;
1723 return GSOCK_NOERROR
;
1726 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1728 struct sockaddr_in
*addr
;
1730 assert(address
!= NULL
);
1731 CHECK_ADDRESS(address
, INET
);
1733 addr
= (struct sockaddr_in
*)address
->m_addr
;
1734 addr
->sin_port
= htons(port
);
1736 return GSOCK_NOERROR
;
1739 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1743 struct sockaddr_in
*addr
;
1745 assert(address
!= NULL
);
1746 CHECK_ADDRESS(address
, INET
);
1748 addr
= (struct sockaddr_in
*)address
->m_addr
;
1749 addr_buf
= (char *)&(addr
->sin_addr
);
1751 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1754 address
->m_error
= GSOCK_NOHOST
;
1755 return GSOCK_NOHOST
;
1758 strncpy(hostname
, he
->h_name
, sbuf
);
1760 return GSOCK_NOERROR
;
1763 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1765 struct sockaddr_in
*addr
;
1767 assert(address
!= NULL
);
1768 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1770 addr
= (struct sockaddr_in
*)address
->m_addr
;
1772 return ntohl(addr
->sin_addr
.s_addr
);
1775 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1777 struct sockaddr_in
*addr
;
1779 assert(address
!= NULL
);
1780 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1782 addr
= (struct sockaddr_in
*)address
->m_addr
;
1783 return ntohs(addr
->sin_port
);
1787 * -------------------------------------------------------------------------
1788 * Unix address family
1789 * -------------------------------------------------------------------------
1792 #ifndef __VISAGECPP__
1793 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1795 address
->m_len
= sizeof(struct sockaddr_un
);
1796 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1797 if (address
->m_addr
== NULL
)
1799 address
->m_error
= GSOCK_MEMERR
;
1800 return GSOCK_MEMERR
;
1803 address
->m_family
= GSOCK_UNIX
;
1804 address
->m_realfamily
= PF_UNIX
;
1805 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1806 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1808 return GSOCK_NOERROR
;
1811 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1813 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1815 struct sockaddr_un
*addr
;
1817 assert(address
!= NULL
);
1819 CHECK_ADDRESS(address
, UNIX
);
1821 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1822 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1823 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1825 return GSOCK_NOERROR
;
1828 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1830 struct sockaddr_un
*addr
;
1832 assert(address
!= NULL
);
1833 CHECK_ADDRESS(address
, UNIX
);
1835 addr
= (struct sockaddr_un
*)address
->m_addr
;
1837 strncpy(path
, addr
->sun_path
, sbuf
);
1839 return GSOCK_NOERROR
;
1841 #endif /* !defined(__VISAGECPP__) */
1842 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */