1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Authors: Guilhem Lavaux,
5 * Guillermo Rodriguez Garcia <guille@iies.es> (maintainer)
6 * Purpose: GSocket main Unix file
7 * Licence: The wxWindows licence
9 * -------------------------------------------------------------------------
13 * PLEASE don't put C++ comments here - this is a C source file.
16 #ifndef __GSOCKET_STANDALONE__
20 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
23 #include <sys/types.h>
25 #include <sys/ioctl.h>
31 u_char sun_len
; /* sockaddr len including null */
32 u_char sun_family
; /* AF_UNIX */
33 char sun_path
[108]; /* path name (gag) */
36 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
51 # include <sys/filio.h>
61 # define SOCKLEN_T unsigned int
65 # define SOCKLEN_T socklen_t
68 # define SOCKLEN_T int
72 #endif /* SOCKLEN_T */
75 * MSW defines this, Unices don't.
77 #ifndef INVALID_SOCKET
78 #define INVALID_SOCKET -1
81 /* UnixWare reportedly needs this for FIONBIO definition */
83 #include <sys/filio.h>
87 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
88 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
91 #define INADDR_NONE INADDR_BROADCAST
94 #define MASK_SIGNAL() \
96 void (*old_handler)(int); \
98 old_handler = signal(SIGPIPE, SIG_IGN);
100 #define UNMASK_SIGNAL() \
101 signal(SIGPIPE, old_handler); \
105 #ifndef __GSOCKET_STANDALONE__
106 # include "wx/unix/gsockunx.h"
107 # include "wx/gsocket.h"
109 # include "gsockunx.h"
110 # include "gsocket.h"
111 #endif /* __GSOCKET_STANDALONE__ */
113 /* debugging helpers */
114 #ifdef __GSOCKET_DEBUG__
115 # define GSocket_Debug(args) printf args
117 # define GSocket_Debug(args)
118 #endif /* __GSOCKET_DEBUG__ */
120 /* Table of GUI-related functions. We must call them indirectly because
121 * of wxBase and GUI separation: */
123 static struct GSocketGUIFunctionsTable
*gs_gui_functions
;
125 #define USE_GUI() (gs_gui_functions != NULL)
127 /* Define macros to simplify indirection: */
128 #define _GSocket_GUI_Init() \
129 if (gs_gui_functions) gs_gui_functions->GUI_Init()
130 #define _GSocket_GUI_Cleanup() \
131 if (gs_gui_functions) gs_gui_functions->GUI_Cleanup()
132 #define _GSocket_GUI_Init_Socket(socket) \
133 (gs_gui_functions ? gs_gui_functions->GUI_Init_Socket(socket) : 1)
134 #define _GSocket_GUI_Destroy_Socket(socket) \
135 if (gs_gui_functions) gs_gui_functions->GUI_Destroy_Socket(socket)
136 #define _GSocket_Enable_Events(socket) \
137 if (gs_gui_functions) gs_gui_functions->Enable_Events(socket)
138 #define _GSocket_Disable_Events(socket) \
139 if (gs_gui_functions) gs_gui_functions->Disable_Events(socket)
140 #define _GSocket_Install_Callback(socket, event) \
141 if (gs_gui_functions) gs_gui_functions->Install_Callback(socket, event)
142 #define _GSocket_Uninstall_Callback(socket, event) \
143 if (gs_gui_functions) gs_gui_functions->Uninstall_Callback(socket, event)
145 static struct GSocketBaseFunctionsTable gs_base_functions
=
147 _GSocket_Detected_Read
,
148 _GSocket_Detected_Write
151 /* Global initialisers */
153 void GSocket_SetGUIFunctions(struct GSocketGUIFunctionsTable
*guifunc
)
155 gs_gui_functions
= guifunc
;
158 int GSocket_Init(void)
160 if (gs_gui_functions
)
162 if ( !gs_gui_functions
->GUI_Init() )
168 void GSocket_Cleanup(void)
170 if (gs_gui_functions
)
172 gs_gui_functions
->GUI_Cleanup();
176 /* Constructors / Destructors for GSocket */
178 GSocket
*GSocket_new(void)
183 socket
= (GSocket
*)malloc(sizeof(GSocket
));
188 socket
->m_fd
= INVALID_SOCKET
;
189 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
191 socket
->m_cbacks
[i
] = NULL
;
193 socket
->m_detected
= 0;
194 socket
->m_local
= NULL
;
195 socket
->m_peer
= NULL
;
196 socket
->m_error
= GSOCK_NOERROR
;
197 socket
->m_server
= FALSE
;
198 socket
->m_stream
= TRUE
;
199 socket
->m_gui_dependent
= NULL
;
200 socket
->m_non_blocking
= FALSE
;
201 socket
->m_timeout
= 10*60*1000;
202 /* 10 minutes * 60 sec * 1000 millisec */
203 socket
->m_establishing
= FALSE
;
205 socket
->m_functions
= &gs_base_functions
;
207 /* Per-socket GUI-specific initialization */
208 success
= _GSocket_GUI_Init_Socket(socket
);
218 void GSocket_close(GSocket
*socket
)
220 _GSocket_Disable_Events(socket
);
222 socket
->m_fd
= INVALID_SOCKET
;
225 void GSocket_destroy(GSocket
*socket
)
227 assert(socket
!= NULL
);
229 /* Check that the socket is really shutdowned */
230 if (socket
->m_fd
!= INVALID_SOCKET
)
231 GSocket_Shutdown(socket
);
233 /* Per-socket GUI-specific cleanup */
234 _GSocket_GUI_Destroy_Socket(socket
);
236 /* Destroy private addresses */
238 GAddress_destroy(socket
->m_local
);
241 GAddress_destroy(socket
->m_peer
);
243 /* Destroy the socket itself */
248 * Disallow further read/write operations on this socket, close
249 * the fd and disable all callbacks.
251 void GSocket_Shutdown(GSocket
*socket
)
255 assert(socket
!= NULL
);
257 /* If socket has been created, shutdown it */
258 if (socket
->m_fd
!= INVALID_SOCKET
)
260 shutdown(socket
->m_fd
, 2);
261 GSocket_close(socket
);
264 /* Disable GUI callbacks */
265 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
266 socket
->m_cbacks
[evt
] = NULL
;
268 socket
->m_detected
= GSOCK_LOST_FLAG
;
271 /* Address handling */
277 * Set or get the local or peer address for this socket. The 'set'
278 * functions return GSOCK_NOERROR on success, an error code otherwise.
279 * The 'get' functions return a pointer to a GAddress object on success,
280 * or NULL otherwise, in which case they set the error code of the
281 * corresponding GSocket.
284 * GSOCK_INVSOCK - the socket is not valid.
285 * GSOCK_INVADDR - the address is not valid.
287 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
289 assert(socket
!= NULL
);
291 /* the socket must be initialized, or it must be a server */
292 if ((socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
))
294 socket
->m_error
= GSOCK_INVSOCK
;
295 return GSOCK_INVSOCK
;
299 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
301 socket
->m_error
= GSOCK_INVADDR
;
302 return GSOCK_INVADDR
;
306 GAddress_destroy(socket
->m_local
);
308 socket
->m_local
= GAddress_copy(address
);
310 return GSOCK_NOERROR
;
313 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
315 assert(socket
!= NULL
);
318 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
320 socket
->m_error
= GSOCK_INVADDR
;
321 return GSOCK_INVADDR
;
325 GAddress_destroy(socket
->m_peer
);
327 socket
->m_peer
= GAddress_copy(address
);
329 return GSOCK_NOERROR
;
332 GAddress
*GSocket_GetLocal(GSocket
*socket
)
335 struct sockaddr addr
;
336 SOCKLEN_T size
= sizeof(addr
);
339 assert(socket
!= NULL
);
341 /* try to get it from the m_local var first */
343 return GAddress_copy(socket
->m_local
);
345 /* else, if the socket is initialized, try getsockname */
346 if (socket
->m_fd
== INVALID_SOCKET
)
348 socket
->m_error
= GSOCK_INVSOCK
;
352 if (getsockname(socket
->m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
354 socket
->m_error
= GSOCK_IOERR
;
358 /* got a valid address from getsockname, create a GAddress object */
359 address
= GAddress_new();
362 socket
->m_error
= GSOCK_MEMERR
;
366 err
= _GAddress_translate_from(address
, &addr
, size
);
367 if (err
!= GSOCK_NOERROR
)
369 GAddress_destroy(address
);
370 socket
->m_error
= err
;
377 GAddress
*GSocket_GetPeer(GSocket
*socket
)
379 assert(socket
!= NULL
);
381 /* try to get it from the m_peer var */
383 return GAddress_copy(socket
->m_peer
);
388 /* Server specific parts */
390 /* GSocket_SetServer:
391 * Sets up this socket as a server. The local address must have been
392 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
393 * Returns GSOCK_NOERROR on success, one of the following otherwise:
396 * GSOCK_INVSOCK - the socket is in use.
397 * GSOCK_INVADDR - the local address has not been set.
398 * GSOCK_IOERR - low-level error.
400 GSocketError
GSocket_SetServer(GSocket
*sck
)
406 /* must not be in use */
407 if (sck
->m_fd
!= INVALID_SOCKET
)
409 sck
->m_error
= GSOCK_INVSOCK
;
410 return GSOCK_INVSOCK
;
413 /* the local addr must have been set */
416 sck
->m_error
= GSOCK_INVADDR
;
417 return GSOCK_INVADDR
;
420 /* Initialize all fields */
421 sck
->m_stream
= TRUE
;
422 sck
->m_server
= TRUE
;
423 sck
->m_oriented
= TRUE
;
425 /* Create the socket */
426 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
428 if (sck
->m_fd
== INVALID_SOCKET
)
430 sck
->m_error
= GSOCK_IOERR
;
434 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
435 _GSocket_Enable_Events(sck
);
437 /* Bind to the local address,
438 * retrieve the actual address bound,
439 * and listen up to 5 connections.
441 if ((bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
442 (getsockname(sck
->m_fd
,
443 sck
->m_local
->m_addr
,
444 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
445 (listen(sck
->m_fd
, 5) != 0))
448 sck
->m_error
= GSOCK_IOERR
;
452 return GSOCK_NOERROR
;
455 /* GSocket_WaitConnection:
456 * Waits for an incoming client connection. Returns a pointer to
457 * a GSocket object, or NULL if there was an error, in which case
458 * the last error field will be updated for the calling GSocket.
460 * Error codes (set in the calling GSocket)
461 * GSOCK_INVSOCK - the socket is not valid or not a server.
462 * GSOCK_TIMEDOUT - timeout, no incoming connections.
463 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
464 * GSOCK_MEMERR - couldn't allocate memory.
465 * GSOCK_IOERR - low-level error.
467 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
469 struct sockaddr from
;
470 SOCKLEN_T fromlen
= sizeof(from
);
475 assert(socket
!= NULL
);
477 /* Reenable CONNECTION events */
478 _GSocket_Enable(socket
, GSOCK_CONNECTION
);
480 /* If the socket has already been created, we exit immediately */
481 if (socket
->m_fd
== INVALID_SOCKET
|| !socket
->m_server
)
483 socket
->m_error
= GSOCK_INVSOCK
;
487 /* Create a GSocket object for the new connection */
488 connection
= GSocket_new();
492 socket
->m_error
= GSOCK_MEMERR
;
496 /* Wait for a connection (with timeout) */
497 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
499 GSocket_destroy(connection
);
500 /* socket->m_error set by _GSocket_Input_Timeout */
504 connection
->m_fd
= accept(socket
->m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
506 if (connection
->m_fd
== INVALID_SOCKET
)
508 if (errno
== EWOULDBLOCK
)
509 socket
->m_error
= GSOCK_WOULDBLOCK
;
511 socket
->m_error
= GSOCK_IOERR
;
513 GSocket_destroy(connection
);
517 /* Initialize all fields */
518 connection
->m_server
= FALSE
;
519 connection
->m_stream
= TRUE
;
520 connection
->m_oriented
= TRUE
;
522 /* Setup the peer address field */
523 connection
->m_peer
= GAddress_new();
524 if (!connection
->m_peer
)
526 GSocket_destroy(connection
);
527 socket
->m_error
= GSOCK_MEMERR
;
530 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
531 if (err
!= GSOCK_NOERROR
)
533 GAddress_destroy(connection
->m_peer
);
534 GSocket_destroy(connection
);
535 socket
->m_error
= err
;
539 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
540 _GSocket_Enable_Events(connection
);
545 /* Client specific parts */
548 * For stream (connection oriented) sockets, GSocket_Connect() tries
549 * to establish a client connection to a server using the peer address
550 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
551 * connection has been succesfully established, or one of the error
552 * codes listed below. Note that for nonblocking sockets, a return
553 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
554 * request can be completed later; you should use GSocket_Select()
555 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
556 * corresponding asynchronous events.
558 * For datagram (non connection oriented) sockets, GSocket_Connect()
559 * just sets the peer address established with GSocket_SetPeer() as
560 * default destination.
563 * GSOCK_INVSOCK - the socket is in use or not valid.
564 * GSOCK_INVADDR - the peer address has not been established.
565 * GSOCK_TIMEDOUT - timeout, the connection failed.
566 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
567 * GSOCK_MEMERR - couldn't allocate memory.
568 * GSOCK_IOERR - low-level error.
570 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
577 /* Enable CONNECTION events (needed for nonblocking connections) */
578 _GSocket_Enable(sck
, GSOCK_CONNECTION
);
580 if (sck
->m_fd
!= INVALID_SOCKET
)
582 sck
->m_error
= GSOCK_INVSOCK
;
583 return GSOCK_INVSOCK
;
588 sck
->m_error
= GSOCK_INVADDR
;
589 return GSOCK_INVADDR
;
592 /* Streamed or dgram socket? */
593 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
594 sck
->m_oriented
= TRUE
;
595 sck
->m_server
= FALSE
;
596 sck
->m_establishing
= FALSE
;
598 /* Create the socket */
599 sck
->m_fd
= socket(sck
->m_peer
->m_realfamily
,
600 sck
->m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
602 if (sck
->m_fd
== INVALID_SOCKET
)
604 sck
->m_error
= GSOCK_IOERR
;
608 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
609 _GSocket_Enable_Events(sck
);
611 /* Connect it to the peer address, with a timeout (see below) */
612 ret
= connect(sck
->m_fd
, sck
->m_peer
->m_addr
, sck
->m_peer
->m_len
);
618 /* If connect failed with EINPROGRESS and the GSocket object
619 * is in blocking mode, we select() for the specified timeout
620 * checking for writability to see if the connection request
623 if ((err
== EINPROGRESS
) && (!sck
->m_non_blocking
))
625 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
628 /* sck->m_error is set in _GSocket_Output_Timeout */
629 return GSOCK_TIMEDOUT
;
634 SOCKLEN_T len
= sizeof(error
);
636 getsockopt(sck
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
639 return GSOCK_NOERROR
;
643 /* If connect failed with EINPROGRESS and the GSocket object
644 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
645 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
646 * this way if the connection completes, a GSOCK_CONNECTION
647 * event will be generated, if enabled.
649 if ((err
== EINPROGRESS
) && (sck
->m_non_blocking
))
651 sck
->m_establishing
= TRUE
;
652 sck
->m_error
= GSOCK_WOULDBLOCK
;
653 return GSOCK_WOULDBLOCK
;
656 /* If connect failed with an error other than EINPROGRESS,
657 * then the call to GSocket_Connect has failed.
660 sck
->m_error
= GSOCK_IOERR
;
664 return GSOCK_NOERROR
;
667 /* Datagram sockets */
669 /* GSocket_SetNonOriented:
670 * Sets up this socket as a non-connection oriented (datagram) socket.
671 * Before using this function, the local address must have been set
672 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
673 * on success, or one of the following otherwise.
676 * GSOCK_INVSOCK - the socket is in use.
677 * GSOCK_INVADDR - the local address has not been set.
678 * GSOCK_IOERR - low-level error.
680 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
686 if (sck
->m_fd
!= INVALID_SOCKET
)
688 sck
->m_error
= GSOCK_INVSOCK
;
689 return GSOCK_INVSOCK
;
694 sck
->m_error
= GSOCK_INVADDR
;
695 return GSOCK_INVADDR
;
698 /* Initialize all fields */
699 sck
->m_stream
= FALSE
;
700 sck
->m_server
= FALSE
;
701 sck
->m_oriented
= FALSE
;
703 /* Create the socket */
704 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
706 if (sck
->m_fd
== INVALID_SOCKET
)
708 sck
->m_error
= GSOCK_IOERR
;
712 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
713 _GSocket_Enable_Events(sck
);
715 /* Bind to the local address,
716 * and retrieve the actual address bound.
718 if ((bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
719 (getsockname(sck
->m_fd
,
720 sck
->m_local
->m_addr
,
721 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
724 sck
->m_error
= GSOCK_IOERR
;
728 return GSOCK_NOERROR
;
733 /* Like recv(), send(), ... */
734 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
738 assert(socket
!= NULL
);
740 /* Reenable INPUT events */
741 _GSocket_Enable(socket
, GSOCK_INPUT
);
743 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
745 socket
->m_error
= GSOCK_INVSOCK
;
749 /* If the socket is blocking, wait for data (with a timeout) */
750 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
754 if (socket
->m_stream
)
755 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
757 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
761 if (errno
== EWOULDBLOCK
)
762 socket
->m_error
= GSOCK_WOULDBLOCK
;
764 socket
->m_error
= GSOCK_IOERR
;
770 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
774 assert(socket
!= NULL
);
776 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
778 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
780 socket
->m_error
= GSOCK_INVSOCK
;
784 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
786 /* If the socket is blocking, wait for writability (with a timeout) */
787 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
790 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
793 if (socket
->m_stream
)
794 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
796 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
798 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
802 if (errno
== EWOULDBLOCK
)
804 socket
->m_error
= GSOCK_WOULDBLOCK
;
805 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
809 socket
->m_error
= GSOCK_IOERR
;
810 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
813 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
814 * in MSW). Once the first OUTPUT event is received, users can assume
815 * that the socket is writable until a read operation fails. Only then
816 * will further OUTPUT events be posted.
818 _GSocket_Enable(socket
, GSOCK_OUTPUT
);
822 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
828 * Polls the socket to determine its status. This function will
829 * check for the events specified in the 'flags' parameter, and
830 * it will return a mask indicating which operations can be
831 * performed. This function won't block, regardless of the
832 * mode (blocking | nonblocking) of the socket.
834 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
839 GSocketEventFlags result
= 0;
845 /* Do not use a static struct, Linux can garble it */
849 assert(socket
!= NULL
);
854 FD_SET(socket
->m_fd
, &readfds
);
855 FD_SET(socket
->m_fd
, &writefds
);
856 FD_SET(socket
->m_fd
, &exceptfds
);
858 /* Check 'sticky' CONNECTION flag first */
859 result
|= (GSOCK_CONNECTION_FLAG
& socket
->m_detected
);
861 /* If we have already detected a LOST event, then don't try
862 * to do any further processing.
864 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
866 socket
->m_establishing
= FALSE
;
868 return (GSOCK_LOST_FLAG
& flags
);
872 if (select(socket
->m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
874 /* What to do here? */
875 return (result
& flags
);
878 /* Check for readability */
879 if (FD_ISSET(socket
->m_fd
, &readfds
))
883 if (recv(socket
->m_fd
, &c
, 1, MSG_PEEK
) > 0)
885 result
|= GSOCK_INPUT_FLAG
;
889 if (socket
->m_server
&& socket
->m_stream
)
891 result
|= GSOCK_CONNECTION_FLAG
;
892 socket
->m_detected
|= GSOCK_CONNECTION_FLAG
;
896 socket
->m_detected
= GSOCK_LOST_FLAG
;
897 socket
->m_establishing
= FALSE
;
899 /* LOST event: Abort any further processing */
900 return (GSOCK_LOST_FLAG
& flags
);
905 /* Check for writability */
906 if (FD_ISSET(socket
->m_fd
, &writefds
))
908 if (socket
->m_establishing
&& !socket
->m_server
)
911 SOCKLEN_T len
= sizeof(error
);
913 socket
->m_establishing
= FALSE
;
915 getsockopt(socket
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
919 socket
->m_detected
= GSOCK_LOST_FLAG
;
921 /* LOST event: Abort any further processing */
922 return (GSOCK_LOST_FLAG
& flags
);
926 result
|= GSOCK_CONNECTION_FLAG
;
927 socket
->m_detected
|= GSOCK_CONNECTION_FLAG
;
932 result
|= GSOCK_OUTPUT_FLAG
;
936 /* Check for exceptions and errors (is this useful in Unices?) */
937 if (FD_ISSET(socket
->m_fd
, &exceptfds
))
939 socket
->m_establishing
= FALSE
;
940 socket
->m_detected
= GSOCK_LOST_FLAG
;
942 /* LOST event: Abort any further processing */
943 return (GSOCK_LOST_FLAG
& flags
);
946 return (result
& flags
);
952 assert(socket
!= NULL
);
953 return flags
& socket
->m_detected
;
960 /* GSocket_SetNonBlocking:
961 * Sets the socket to non-blocking mode. All IO calls will return
964 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
966 assert(socket
!= NULL
);
968 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
970 socket
->m_non_blocking
= non_block
;
973 /* GSocket_SetTimeout:
974 * Sets the timeout for blocking calls. Time is expressed in
977 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
979 assert(socket
!= NULL
);
981 socket
->m_timeout
= millisec
;
985 * Returns the last error occured for this socket. Note that successful
986 * operations do not clear this back to GSOCK_NOERROR, so use it only
989 GSocketError
GSocket_GetError(GSocket
*socket
)
991 assert(socket
!= NULL
);
993 return socket
->m_error
;
999 * There is data to be read in the input buffer. If, after a read
1000 * operation, there is still data available, the callback function will
1003 * The socket is available for writing. That is, the next write call
1004 * won't block. This event is generated only once, when the connection is
1005 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1006 * when the output buffer empties again. This means that the app should
1007 * assume that it can write since the first OUTPUT event, and no more
1008 * OUTPUT events will be generated unless an error occurs.
1010 * Connection succesfully established, for client sockets, or incoming
1011 * client connection, for server sockets. Wait for this event (also watch
1012 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1014 * The connection is lost (or a connection request failed); this could
1015 * be due to a failure, or due to the peer closing it gracefully.
1018 /* GSocket_SetCallback:
1019 * Enables the callbacks specified by 'flags'. Note that 'flags'
1020 * may be a combination of flags OR'ed toghether, so the same
1021 * callback function can be made to accept different events.
1022 * The callback function must have the following prototype:
1024 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1026 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1027 GSocketCallback callback
, char *cdata
)
1031 assert(socket
!= NULL
);
1033 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1035 if ((flags
& (1 << count
)) != 0)
1037 socket
->m_cbacks
[count
] = callback
;
1038 socket
->m_data
[count
] = cdata
;
1043 /* GSocket_UnsetCallback:
1044 * Disables all callbacks specified by 'flags', which may be a
1045 * combination of flags OR'ed toghether.
1047 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1051 assert(socket
!= NULL
);
1053 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1055 if ((flags
& (1 << count
)) != 0)
1057 socket
->m_cbacks
[count
] = NULL
;
1058 socket
->m_data
[count
] = NULL
;
1064 #define CALL_CALLBACK(socket, event) { \
1065 _GSocket_Disable(socket, event); \
1066 if (socket->m_cbacks[event]) \
1067 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1071 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
)
1073 socket
->m_detected
&= ~(1 << event
);
1074 _GSocket_Install_Callback(socket
, event
);
1077 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
)
1079 socket
->m_detected
|= (1 << event
);
1080 _GSocket_Uninstall_Callback(socket
, event
);
1083 /* _GSocket_Input_Timeout:
1084 * For blocking sockets, wait until data is available or
1085 * until timeout ellapses.
1087 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1093 /* Linux select() will overwrite the struct on return */
1094 tv
.tv_sec
= (socket
->m_timeout
/ 1000);
1095 tv
.tv_usec
= (socket
->m_timeout
% 1000) * 1000;
1097 if (!socket
->m_non_blocking
)
1100 FD_SET(socket
->m_fd
, &readfds
);
1101 ret
= select(socket
->m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1104 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1105 socket
->m_error
= GSOCK_TIMEDOUT
;
1106 return GSOCK_TIMEDOUT
;
1110 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1111 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1112 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1113 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1114 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1115 socket
->m_error
= GSOCK_TIMEDOUT
;
1116 return GSOCK_TIMEDOUT
;
1119 return GSOCK_NOERROR
;
1122 /* _GSocket_Output_Timeout:
1123 * For blocking sockets, wait until data can be sent without
1124 * blocking or until timeout ellapses.
1126 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1132 /* Linux select() will overwrite the struct on return */
1133 tv
.tv_sec
= (socket
->m_timeout
/ 1000);
1134 tv
.tv_usec
= (socket
->m_timeout
% 1000) * 1000;
1136 GSocket_Debug( ("m_non_blocking has: %d\n", (int)socket
->m_non_blocking
) );
1138 if (!socket
->m_non_blocking
)
1141 FD_SET(socket
->m_fd
, &writefds
);
1142 ret
= select(socket
->m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1145 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1146 socket
->m_error
= GSOCK_TIMEDOUT
;
1147 return GSOCK_TIMEDOUT
;
1151 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1152 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1153 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1154 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1155 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1156 socket
->m_error
= GSOCK_TIMEDOUT
;
1157 return GSOCK_TIMEDOUT
;
1159 if ( ! FD_ISSET(socket
->m_fd
, &writefds
) ) {
1160 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1163 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1168 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1171 return GSOCK_NOERROR
;
1174 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1176 return recv(socket
->m_fd
, buffer
, size
, 0);
1179 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1181 struct sockaddr from
;
1182 SOCKLEN_T fromlen
= sizeof(from
);
1186 fromlen
= sizeof(from
);
1188 ret
= recvfrom(socket
->m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1193 /* Translate a system address into a GSocket address */
1194 if (!socket
->m_peer
)
1196 socket
->m_peer
= GAddress_new();
1197 if (!socket
->m_peer
)
1199 socket
->m_error
= GSOCK_MEMERR
;
1203 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1204 if (err
!= GSOCK_NOERROR
)
1206 GAddress_destroy(socket
->m_peer
);
1207 socket
->m_peer
= NULL
;
1208 socket
->m_error
= err
;
1215 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1220 ret
= send(socket
->m_fd
, buffer
, size
, 0);
1226 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1228 struct sockaddr
*addr
;
1232 if (!socket
->m_peer
)
1234 socket
->m_error
= GSOCK_INVADDR
;
1238 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1239 if (err
!= GSOCK_NOERROR
)
1241 socket
->m_error
= err
;
1246 ret
= sendto(socket
->m_fd
, buffer
, size
, 0, addr
, len
);
1249 /* Frees memory allocated from _GAddress_translate_to */
1255 void _GSocket_Detected_Read(GSocket
*socket
)
1259 /* If we have already detected a LOST event, then don't try
1260 * to do any further processing.
1262 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
1264 socket
->m_establishing
= FALSE
;
1266 CALL_CALLBACK(socket
, GSOCK_LOST
);
1267 GSocket_Shutdown(socket
);
1271 if (recv(socket
->m_fd
, &c
, 1, MSG_PEEK
) > 0)
1273 CALL_CALLBACK(socket
, GSOCK_INPUT
);
1277 if (socket
->m_server
&& socket
->m_stream
)
1279 CALL_CALLBACK(socket
, GSOCK_CONNECTION
);
1283 CALL_CALLBACK(socket
, GSOCK_LOST
);
1284 GSocket_Shutdown(socket
);
1289 void _GSocket_Detected_Write(GSocket
*socket
)
1291 /* If we have already detected a LOST event, then don't try
1292 * to do any further processing.
1294 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
1296 socket
->m_establishing
= FALSE
;
1298 CALL_CALLBACK(socket
, GSOCK_LOST
);
1299 GSocket_Shutdown(socket
);
1303 if (socket
->m_establishing
&& !socket
->m_server
)
1306 SOCKLEN_T len
= sizeof(error
);
1308 socket
->m_establishing
= FALSE
;
1310 getsockopt(socket
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1314 CALL_CALLBACK(socket
, GSOCK_LOST
);
1315 GSocket_Shutdown(socket
);
1319 CALL_CALLBACK(socket
, GSOCK_CONNECTION
);
1320 /* We have to fire this event by hand because CONNECTION (for clients)
1321 * and OUTPUT are internally the same and we just disabled CONNECTION
1322 * events with the above macro.
1324 CALL_CALLBACK(socket
, GSOCK_OUTPUT
);
1329 CALL_CALLBACK(socket
, GSOCK_OUTPUT
);
1334 * -------------------------------------------------------------------------
1336 * -------------------------------------------------------------------------
1339 /* CHECK_ADDRESS verifies that the current address family is either
1340 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1341 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1342 * an appropiate error code.
1344 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1346 #define CHECK_ADDRESS(address, family) \
1348 if (address->m_family == GSOCK_NOFAMILY) \
1349 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1350 return address->m_error; \
1351 if (address->m_family != GSOCK_##family) \
1353 address->m_error = GSOCK_INVADDR; \
1354 return GSOCK_INVADDR; \
1358 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1360 if (address->m_family == GSOCK_NOFAMILY) \
1361 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1363 if (address->m_family != GSOCK_##family) \
1365 address->m_error = GSOCK_INVADDR; \
1371 GAddress
*GAddress_new(void)
1375 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1378 address
->m_family
= GSOCK_NOFAMILY
;
1379 address
->m_addr
= NULL
;
1385 GAddress
*GAddress_copy(GAddress
*address
)
1389 assert(address
!= NULL
);
1391 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1394 memcpy(addr2
, address
, sizeof(GAddress
));
1396 if (address
->m_addr
&& address
->m_len
> 0)
1398 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1399 if (addr2
->m_addr
== NULL
)
1404 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1410 void GAddress_destroy(GAddress
*address
)
1412 assert(address
!= NULL
);
1414 if (address
->m_addr
)
1415 free(address
->m_addr
);
1420 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1422 assert(address
!= NULL
);
1424 address
->m_family
= type
;
1427 GAddressType
GAddress_GetFamily(GAddress
*address
)
1429 assert(address
!= NULL
);
1431 return address
->m_family
;
1434 GSocketError
_GAddress_translate_from(GAddress
*address
,
1435 struct sockaddr
*addr
, int len
)
1437 address
->m_realfamily
= addr
->sa_family
;
1438 switch (addr
->sa_family
)
1441 address
->m_family
= GSOCK_INET
;
1444 address
->m_family
= GSOCK_UNIX
;
1448 address
->m_family
= GSOCK_INET6
;
1453 address
->m_error
= GSOCK_INVOP
;
1458 if (address
->m_addr
)
1459 free(address
->m_addr
);
1461 address
->m_len
= len
;
1462 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1464 if (address
->m_addr
== NULL
)
1466 address
->m_error
= GSOCK_MEMERR
;
1467 return GSOCK_MEMERR
;
1469 memcpy(address
->m_addr
, addr
, len
);
1471 return GSOCK_NOERROR
;
1474 GSocketError
_GAddress_translate_to(GAddress
*address
,
1475 struct sockaddr
**addr
, int *len
)
1477 if (!address
->m_addr
)
1479 address
->m_error
= GSOCK_INVADDR
;
1480 return GSOCK_INVADDR
;
1483 *len
= address
->m_len
;
1484 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1487 address
->m_error
= GSOCK_MEMERR
;
1488 return GSOCK_MEMERR
;
1491 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1492 return GSOCK_NOERROR
;
1496 * -------------------------------------------------------------------------
1497 * Internet address family
1498 * -------------------------------------------------------------------------
1501 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1503 address
->m_len
= sizeof(struct sockaddr_in
);
1504 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1505 if (address
->m_addr
== NULL
)
1507 address
->m_error
= GSOCK_MEMERR
;
1508 return GSOCK_MEMERR
;
1511 address
->m_family
= GSOCK_INET
;
1512 address
->m_realfamily
= PF_INET
;
1513 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1514 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1516 return GSOCK_NOERROR
;
1519 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1522 struct in_addr
*addr
;
1524 assert(address
!= NULL
);
1526 CHECK_ADDRESS(address
, INET
);
1528 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1530 /* If it is a numeric host name, convert it now */
1531 #if defined(HAVE_INET_ATON)
1532 if (inet_aton(hostname
, addr
) == 0)
1534 #elif defined(HAVE_INET_ADDR)
1535 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1538 /* Use gethostbyname by default */
1542 struct in_addr
*array_addr
;
1544 /* It is a real name, we solve it */
1545 if ((he
= gethostbyname(hostname
)) == NULL
)
1547 /* Reset to invalid address */
1548 addr
->s_addr
= INADDR_NONE
;
1549 address
->m_error
= GSOCK_NOHOST
;
1550 return GSOCK_NOHOST
;
1552 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1553 addr
->s_addr
= array_addr
[0].s_addr
;
1555 return GSOCK_NOERROR
;
1558 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1560 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1563 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1564 unsigned long hostaddr
)
1566 struct in_addr
*addr
;
1568 assert(address
!= NULL
);
1570 CHECK_ADDRESS(address
, INET
);
1572 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1573 addr
->s_addr
= hostaddr
;
1575 return GSOCK_NOERROR
;
1578 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1579 const char *protocol
)
1582 struct sockaddr_in
*addr
;
1584 assert(address
!= NULL
);
1585 CHECK_ADDRESS(address
, INET
);
1589 address
->m_error
= GSOCK_INVPORT
;
1590 return GSOCK_INVPORT
;
1593 se
= getservbyname(port
, protocol
);
1596 /* the cast to int suppresses compiler warnings about subscript having the
1598 if (isdigit((int)port
[0]))
1602 port_int
= atoi(port
);
1603 addr
= (struct sockaddr_in
*)address
->m_addr
;
1604 addr
->sin_port
= htons(port_int
);
1605 return GSOCK_NOERROR
;
1608 address
->m_error
= GSOCK_INVPORT
;
1609 return GSOCK_INVPORT
;
1612 addr
= (struct sockaddr_in
*)address
->m_addr
;
1613 addr
->sin_port
= se
->s_port
;
1615 return GSOCK_NOERROR
;
1618 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1620 struct sockaddr_in
*addr
;
1622 assert(address
!= NULL
);
1623 CHECK_ADDRESS(address
, INET
);
1625 addr
= (struct sockaddr_in
*)address
->m_addr
;
1626 addr
->sin_port
= htons(port
);
1628 return GSOCK_NOERROR
;
1631 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1635 struct sockaddr_in
*addr
;
1637 assert(address
!= NULL
);
1638 CHECK_ADDRESS(address
, INET
);
1640 addr
= (struct sockaddr_in
*)address
->m_addr
;
1641 addr_buf
= (char *)&(addr
->sin_addr
);
1643 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1646 address
->m_error
= GSOCK_NOHOST
;
1647 return GSOCK_NOHOST
;
1650 strncpy(hostname
, he
->h_name
, sbuf
);
1652 return GSOCK_NOERROR
;
1655 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1657 struct sockaddr_in
*addr
;
1659 assert(address
!= NULL
);
1660 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1662 addr
= (struct sockaddr_in
*)address
->m_addr
;
1664 return addr
->sin_addr
.s_addr
;
1667 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1669 struct sockaddr_in
*addr
;
1671 assert(address
!= NULL
);
1672 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1674 addr
= (struct sockaddr_in
*)address
->m_addr
;
1675 return ntohs(addr
->sin_port
);
1679 * -------------------------------------------------------------------------
1680 * Unix address family
1681 * -------------------------------------------------------------------------
1684 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1686 address
->m_len
= sizeof(struct sockaddr_un
);
1687 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1688 if (address
->m_addr
== NULL
)
1690 address
->m_error
= GSOCK_MEMERR
;
1691 return GSOCK_MEMERR
;
1694 address
->m_family
= GSOCK_UNIX
;
1695 address
->m_realfamily
= PF_UNIX
;
1696 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1697 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1699 return GSOCK_NOERROR
;
1702 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1704 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1706 struct sockaddr_un
*addr
;
1708 assert(address
!= NULL
);
1710 CHECK_ADDRESS(address
, UNIX
);
1712 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1713 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1714 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1716 return GSOCK_NOERROR
;
1719 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1721 struct sockaddr_un
*addr
;
1723 assert(address
!= NULL
);
1724 CHECK_ADDRESS(address
, UNIX
);
1726 addr
= (struct sockaddr_un
*)address
->m_addr
;
1728 strncpy(path
, addr
->sun_path
, sbuf
);
1730 return GSOCK_NOERROR
;
1733 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */