]>
git.saurik.com Git - wxWidgets.git/blob - src/unix/gsocket.c
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
8 * -------------------------------------------------------------------------
12 * PLEASE don't put C++ comments here - this is a C source file.
15 #ifndef __GSOCKET_STANDALONE__
19 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
22 #include <sys/types.h>
24 #include <sys/ioctl.h>
30 u_char sun_len
; /* sockaddr len including null */
31 u_char sun_family
; /* AF_UNIX */
32 char sun_path
[108]; /* path name (gag) */
35 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
50 # include <sys/filio.h>
60 # define SOCKLEN_T unsigned int
64 # define SOCKLEN_T socklen_t
67 # define SOCKLEN_T int
71 #endif /* SOCKLEN_T */
74 * MSW defines this, Unices don't.
76 #ifndef INVALID_SOCKET
77 #define INVALID_SOCKET -1
81 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
82 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
85 #define INADDR_NONE INADDR_BROADCAST
88 #define MASK_SIGNAL() \
90 void (*old_handler)(int); \
92 old_handler = signal(SIGPIPE, SIG_IGN);
94 #define UNMASK_SIGNAL() \
95 signal(SIGPIPE, old_handler); \
99 #ifndef __GSOCKET_STANDALONE__
100 # include "wx/unix/gsockunx.h"
101 # include "wx/gsocket.h"
103 # include "gsockunx.h"
104 # include "gsocket.h"
105 #endif /* __GSOCKET_STANDALONE__ */
107 /* redefine some GUI-only functions to do nothing in console mode */
108 #if defined(wxUSE_GUI) && !wxUSE_GUI
109 # define _GSocket_GUI_Init(socket) (1)
110 # define _GSocket_GUI_Destroy(socket)
111 # define _GSocket_Enable_Events(socket)
112 # define _GSocket_Disable_Events(socket)
113 # define _GSocket_Install_Callback(socket, event)
114 # define _GSocket_Uninstall_Callback(socket, event)
115 #endif /* wxUSE_GUI */
117 /* debugging helpers */
118 #ifdef __GSOCKET_DEBUG__
119 # define GSocket_Debug(args) printf args
121 # define GSocket_Debug(args)
122 #endif /* __GSOCKET_DEBUG__ */
124 /* Global initialisers */
126 int GSocket_Init(void)
131 void GSocket_Cleanup(void)
135 /* Constructors / Destructors for GSocket */
137 GSocket
*GSocket_new(void)
142 socket
= (GSocket
*)malloc(sizeof(GSocket
));
147 socket
->m_fd
= INVALID_SOCKET
;
148 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
150 socket
->m_cbacks
[i
] = NULL
;
152 socket
->m_detected
= 0;
153 socket
->m_local
= NULL
;
154 socket
->m_peer
= NULL
;
155 socket
->m_error
= GSOCK_NOERROR
;
156 socket
->m_server
= FALSE
;
157 socket
->m_stream
= TRUE
;
158 socket
->m_gui_dependent
= NULL
;
159 socket
->m_non_blocking
= FALSE
;
160 socket
->m_timeout
= 10*60*1000;
161 /* 10 minutes * 60 sec * 1000 millisec */
162 socket
->m_establishing
= FALSE
;
164 /* Per-socket GUI-specific initialization */
165 success
= _GSocket_GUI_Init(socket
);
175 void GSocket_close(GSocket
*socket
)
177 _GSocket_Disable_Events(socket
);
179 socket
->m_fd
= INVALID_SOCKET
;
182 void GSocket_destroy(GSocket
*socket
)
184 assert(socket
!= NULL
);
186 /* Check that the socket is really shutdowned */
187 if (socket
->m_fd
!= INVALID_SOCKET
)
188 GSocket_Shutdown(socket
);
190 /* Per-socket GUI-specific cleanup */
191 _GSocket_GUI_Destroy(socket
);
193 /* Destroy private addresses */
195 GAddress_destroy(socket
->m_local
);
198 GAddress_destroy(socket
->m_peer
);
200 /* Destroy the socket itself */
205 * Disallow further read/write operations on this socket, close
206 * the fd and disable all callbacks.
208 void GSocket_Shutdown(GSocket
*socket
)
212 assert(socket
!= NULL
);
214 /* If socket has been created, shutdown it */
215 if (socket
->m_fd
!= INVALID_SOCKET
)
217 shutdown(socket
->m_fd
, 2);
218 GSocket_close(socket
);
221 /* Disable GUI callbacks */
222 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
223 socket
->m_cbacks
[evt
] = NULL
;
225 socket
->m_detected
= GSOCK_LOST_FLAG
;
228 /* Address handling */
234 * Set or get the local or peer address for this socket. The 'set'
235 * functions return GSOCK_NOERROR on success, an error code otherwise.
236 * The 'get' functions return a pointer to a GAddress object on success,
237 * or NULL otherwise, in which case they set the error code of the
238 * corresponding GSocket.
241 * GSOCK_INVSOCK - the socket is not valid.
242 * GSOCK_INVADDR - the address is not valid.
244 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
246 assert(socket
!= NULL
);
248 /* the socket must be initialized, or it must be a server */
249 if ((socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
))
251 socket
->m_error
= GSOCK_INVSOCK
;
252 return GSOCK_INVSOCK
;
256 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
258 socket
->m_error
= GSOCK_INVADDR
;
259 return GSOCK_INVADDR
;
263 GAddress_destroy(socket
->m_local
);
265 socket
->m_local
= GAddress_copy(address
);
267 return GSOCK_NOERROR
;
270 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
272 assert(socket
!= NULL
);
275 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
277 socket
->m_error
= GSOCK_INVADDR
;
278 return GSOCK_INVADDR
;
282 GAddress_destroy(socket
->m_peer
);
284 socket
->m_peer
= GAddress_copy(address
);
286 return GSOCK_NOERROR
;
289 GAddress
*GSocket_GetLocal(GSocket
*socket
)
292 struct sockaddr addr
;
293 SOCKLEN_T size
= sizeof(addr
);
296 assert(socket
!= NULL
);
298 /* try to get it from the m_local var first */
300 return GAddress_copy(socket
->m_local
);
302 /* else, if the socket is initialized, try getsockname */
303 if (socket
->m_fd
== INVALID_SOCKET
)
305 socket
->m_error
= GSOCK_INVSOCK
;
309 if (getsockname(socket
->m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
311 socket
->m_error
= GSOCK_IOERR
;
315 /* got a valid address from getsockname, create a GAddress object */
316 address
= GAddress_new();
319 socket
->m_error
= GSOCK_MEMERR
;
323 err
= _GAddress_translate_from(address
, &addr
, size
);
324 if (err
!= GSOCK_NOERROR
)
326 GAddress_destroy(address
);
327 socket
->m_error
= err
;
334 GAddress
*GSocket_GetPeer(GSocket
*socket
)
336 assert(socket
!= NULL
);
338 /* try to get it from the m_peer var */
340 return GAddress_copy(socket
->m_peer
);
345 /* Server specific parts */
347 /* GSocket_SetServer:
348 * Sets up this socket as a server. The local address must have been
349 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
350 * Returns GSOCK_NOERROR on success, one of the following otherwise:
353 * GSOCK_INVSOCK - the socket is in use.
354 * GSOCK_INVADDR - the local address has not been set.
355 * GSOCK_IOERR - low-level error.
357 GSocketError
GSocket_SetServer(GSocket
*sck
)
363 /* must not be in use */
364 if (sck
->m_fd
!= INVALID_SOCKET
)
366 sck
->m_error
= GSOCK_INVSOCK
;
367 return GSOCK_INVSOCK
;
370 /* the local addr must have been set */
373 sck
->m_error
= GSOCK_INVADDR
;
374 return GSOCK_INVADDR
;
377 /* Initialize all fields */
378 sck
->m_stream
= TRUE
;
379 sck
->m_server
= TRUE
;
380 sck
->m_oriented
= TRUE
;
382 /* Create the socket */
383 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
385 if (sck
->m_fd
== INVALID_SOCKET
)
387 sck
->m_error
= GSOCK_IOERR
;
391 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
392 _GSocket_Enable_Events(sck
);
394 /* Bind to the local address,
395 * retrieve the actual address bound,
396 * and listen up to 5 connections.
398 if ((bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
399 (getsockname(sck
->m_fd
,
400 sck
->m_local
->m_addr
,
401 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
402 (listen(sck
->m_fd
, 5) != 0))
405 sck
->m_error
= GSOCK_IOERR
;
409 return GSOCK_NOERROR
;
412 /* GSocket_WaitConnection:
413 * Waits for an incoming client connection. Returns a pointer to
414 * a GSocket object, or NULL if there was an error, in which case
415 * the last error field will be updated for the calling GSocket.
417 * Error codes (set in the calling GSocket)
418 * GSOCK_INVSOCK - the socket is not valid or not a server.
419 * GSOCK_TIMEDOUT - timeout, no incoming connections.
420 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
421 * GSOCK_MEMERR - couldn't allocate memory.
422 * GSOCK_IOERR - low-level error.
424 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
426 struct sockaddr from
;
427 SOCKLEN_T fromlen
= sizeof(from
);
432 assert(socket
!= NULL
);
434 /* Reenable CONNECTION events */
435 _GSocket_Enable(socket
, GSOCK_CONNECTION
);
437 /* If the socket has already been created, we exit immediately */
438 if (socket
->m_fd
== INVALID_SOCKET
|| !socket
->m_server
)
440 socket
->m_error
= GSOCK_INVSOCK
;
444 /* Create a GSocket object for the new connection */
445 connection
= GSocket_new();
449 socket
->m_error
= GSOCK_MEMERR
;
453 /* Wait for a connection (with timeout) */
454 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
456 GSocket_destroy(connection
);
457 /* socket->m_error set by _GSocket_Input_Timeout */
461 connection
->m_fd
= accept(socket
->m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
463 if (connection
->m_fd
== INVALID_SOCKET
)
465 if (errno
== EWOULDBLOCK
)
466 socket
->m_error
= GSOCK_WOULDBLOCK
;
468 socket
->m_error
= GSOCK_IOERR
;
470 GSocket_destroy(connection
);
474 /* Initialize all fields */
475 connection
->m_server
= FALSE
;
476 connection
->m_stream
= TRUE
;
477 connection
->m_oriented
= TRUE
;
479 /* Setup the peer address field */
480 connection
->m_peer
= GAddress_new();
481 if (!connection
->m_peer
)
483 GSocket_destroy(connection
);
484 socket
->m_error
= GSOCK_MEMERR
;
487 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
488 if (err
!= GSOCK_NOERROR
)
490 GAddress_destroy(connection
->m_peer
);
491 GSocket_destroy(connection
);
492 socket
->m_error
= err
;
496 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
497 _GSocket_Enable_Events(connection
);
502 /* Client specific parts */
505 * For stream (connection oriented) sockets, GSocket_Connect() tries
506 * to establish a client connection to a server using the peer address
507 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
508 * connection has been succesfully established, or one of the error
509 * codes listed below. Note that for nonblocking sockets, a return
510 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
511 * request can be completed later; you should use GSocket_Select()
512 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
513 * corresponding asynchronous events.
515 * For datagram (non connection oriented) sockets, GSocket_Connect()
516 * just sets the peer address established with GSocket_SetPeer() as
517 * default destination.
520 * GSOCK_INVSOCK - the socket is in use or not valid.
521 * GSOCK_INVADDR - the peer address has not been established.
522 * GSOCK_TIMEDOUT - timeout, the connection failed.
523 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
524 * GSOCK_MEMERR - couldn't allocate memory.
525 * GSOCK_IOERR - low-level error.
527 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
534 /* Enable CONNECTION events (needed for nonblocking connections) */
535 _GSocket_Enable(sck
, GSOCK_CONNECTION
);
537 if (sck
->m_fd
!= INVALID_SOCKET
)
539 sck
->m_error
= GSOCK_INVSOCK
;
540 return GSOCK_INVSOCK
;
545 sck
->m_error
= GSOCK_INVADDR
;
546 return GSOCK_INVADDR
;
549 /* Streamed or dgram socket? */
550 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
551 sck
->m_oriented
= TRUE
;
552 sck
->m_server
= FALSE
;
553 sck
->m_establishing
= FALSE
;
555 /* Create the socket */
556 sck
->m_fd
= socket(sck
->m_peer
->m_realfamily
,
557 sck
->m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
559 if (sck
->m_fd
== INVALID_SOCKET
)
561 sck
->m_error
= GSOCK_IOERR
;
565 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
566 _GSocket_Enable_Events(sck
);
568 /* Connect it to the peer address, with a timeout (see below) */
569 ret
= connect(sck
->m_fd
, sck
->m_peer
->m_addr
, sck
->m_peer
->m_len
);
575 /* If connect failed with EINPROGRESS and the GSocket object
576 * is in blocking mode, we select() for the specified timeout
577 * checking for writability to see if the connection request
580 if ((err
== EINPROGRESS
) && (!sck
->m_non_blocking
))
582 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
585 /* sck->m_error is set in _GSocket_Output_Timeout */
586 return GSOCK_TIMEDOUT
;
591 SOCKLEN_T len
= sizeof(error
);
593 getsockopt(sck
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
596 return GSOCK_NOERROR
;
600 /* If connect failed with EINPROGRESS and the GSocket object
601 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
602 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
603 * this way if the connection completes, a GSOCK_CONNECTION
604 * event will be generated, if enabled.
606 if ((err
== EINPROGRESS
) && (sck
->m_non_blocking
))
608 sck
->m_establishing
= TRUE
;
609 sck
->m_error
= GSOCK_WOULDBLOCK
;
610 return GSOCK_WOULDBLOCK
;
613 /* If connect failed with an error other than EINPROGRESS,
614 * then the call to GSocket_Connect has failed.
617 sck
->m_error
= GSOCK_IOERR
;
621 return GSOCK_NOERROR
;
624 /* Datagram sockets */
626 /* GSocket_SetNonOriented:
627 * Sets up this socket as a non-connection oriented (datagram) socket.
628 * Before using this function, the local address must have been set
629 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
630 * on success, or one of the following otherwise.
633 * GSOCK_INVSOCK - the socket is in use.
634 * GSOCK_INVADDR - the local address has not been set.
635 * GSOCK_IOERR - low-level error.
637 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
643 if (sck
->m_fd
!= INVALID_SOCKET
)
645 sck
->m_error
= GSOCK_INVSOCK
;
646 return GSOCK_INVSOCK
;
651 sck
->m_error
= GSOCK_INVADDR
;
652 return GSOCK_INVADDR
;
655 /* Initialize all fields */
656 sck
->m_stream
= FALSE
;
657 sck
->m_server
= FALSE
;
658 sck
->m_oriented
= FALSE
;
660 /* Create the socket */
661 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
663 if (sck
->m_fd
== INVALID_SOCKET
)
665 sck
->m_error
= GSOCK_IOERR
;
669 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
670 _GSocket_Enable_Events(sck
);
672 /* Bind to the local address,
673 * and retrieve the actual address bound.
675 if ((bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
676 (getsockname(sck
->m_fd
,
677 sck
->m_local
->m_addr
,
678 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
681 sck
->m_error
= GSOCK_IOERR
;
685 return GSOCK_NOERROR
;
690 /* Like recv(), send(), ... */
691 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
695 assert(socket
!= NULL
);
697 /* Reenable INPUT events */
698 _GSocket_Enable(socket
, GSOCK_INPUT
);
700 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
702 socket
->m_error
= GSOCK_INVSOCK
;
706 /* If the socket is blocking, wait for data (with a timeout) */
707 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
711 if (socket
->m_stream
)
712 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
714 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
718 if (errno
== EWOULDBLOCK
)
719 socket
->m_error
= GSOCK_WOULDBLOCK
;
721 socket
->m_error
= GSOCK_IOERR
;
727 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
731 assert(socket
!= NULL
);
733 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
735 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
737 socket
->m_error
= GSOCK_INVSOCK
;
741 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
743 /* If the socket is blocking, wait for writability (with a timeout) */
744 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
747 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
750 if (socket
->m_stream
)
751 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
753 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
755 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
759 if (errno
== EWOULDBLOCK
)
761 socket
->m_error
= GSOCK_WOULDBLOCK
;
762 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
766 socket
->m_error
= GSOCK_IOERR
;
767 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
770 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
771 * in MSW). Once the first OUTPUT event is received, users can assume
772 * that the socket is writable until a read operation fails. Only then
773 * will further OUTPUT events be posted.
775 _GSocket_Enable(socket
, GSOCK_OUTPUT
);
779 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
785 * Polls the socket to determine its status. This function will
786 * check for the events specified in the 'flags' parameter, and
787 * it will return a mask indicating which operations can be
788 * performed. This function won't block, regardless of the
789 * mode (blocking | nonblocking) of the socket.
791 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
793 #if defined(wxUSE_GUI) && !wxUSE_GUI
795 GSocketEventFlags result
= 0;
801 /* Do not use a static struct, Linux can garble it */
805 assert(socket
!= NULL
);
810 FD_SET(socket
->m_fd
, &readfds
);
811 FD_SET(socket
->m_fd
, &writefds
);
812 FD_SET(socket
->m_fd
, &exceptfds
);
814 /* Check 'sticky' CONNECTION flag first */
815 result
|= (GSOCK_CONNECTION_FLAG
& socket
->m_detected
);
817 /* If we have already detected a LOST event, then don't try
818 * to do any further processing.
820 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
822 socket
->m_establishing
= FALSE
;
824 return (GSOCK_LOST_FLAG
& flags
);
828 if (select(socket
->m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
830 /* What to do here? */
831 return (result
& flags
);
834 /* Check for readability */
835 if (FD_ISSET(socket
->m_fd
, &readfds
))
839 if (recv(socket
->m_fd
, &c
, 1, MSG_PEEK
) > 0)
841 result
|= GSOCK_INPUT_FLAG
;
845 if (socket
->m_server
&& socket
->m_stream
)
847 result
|= GSOCK_CONNECTION_FLAG
;
848 socket
->m_detected
|= GSOCK_CONNECTION_FLAG
;
852 socket
->m_detected
= GSOCK_LOST_FLAG
;
853 socket
->m_establishing
= FALSE
;
855 /* LOST event: Abort any further processing */
856 return (GSOCK_LOST_FLAG
& flags
);
861 /* Check for writability */
862 if (FD_ISSET(socket
->m_fd
, &writefds
))
864 if (socket
->m_establishing
&& !socket
->m_server
)
867 SOCKLEN_T len
= sizeof(error
);
869 socket
->m_establishing
= FALSE
;
871 getsockopt(socket
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
875 socket
->m_detected
= GSOCK_LOST_FLAG
;
877 /* LOST event: Abort any further processing */
878 return (GSOCK_LOST_FLAG
& flags
);
882 result
|= GSOCK_CONNECTION_FLAG
;
883 socket
->m_detected
|= GSOCK_CONNECTION_FLAG
;
888 result
|= GSOCK_OUTPUT_FLAG
;
892 /* Check for exceptions and errors (is this useful in Unices?) */
893 if (FD_ISSET(socket
->m_fd
, &exceptfds
))
895 socket
->m_establishing
= FALSE
;
896 socket
->m_detected
= GSOCK_LOST_FLAG
;
898 /* LOST event: Abort any further processing */
899 return (GSOCK_LOST_FLAG
& flags
);
902 return (result
& flags
);
906 assert(socket
!= NULL
);
907 return flags
& socket
->m_detected
;
909 #endif /* !wxUSE_GUI */
914 /* GSocket_SetNonBlocking:
915 * Sets the socket to non-blocking mode. All IO calls will return
918 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
920 assert(socket
!= NULL
);
922 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
924 socket
->m_non_blocking
= non_block
;
927 /* GSocket_SetTimeout:
928 * Sets the timeout for blocking calls. Time is expressed in
931 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
933 assert(socket
!= NULL
);
935 socket
->m_timeout
= millisec
;
939 * Returns the last error occured for this socket. Note that successful
940 * operations do not clear this back to GSOCK_NOERROR, so use it only
943 GSocketError
GSocket_GetError(GSocket
*socket
)
945 assert(socket
!= NULL
);
947 return socket
->m_error
;
953 * There is data to be read in the input buffer. If, after a read
954 * operation, there is still data available, the callback function will
957 * The socket is available for writing. That is, the next write call
958 * won't block. This event is generated only once, when the connection is
959 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
960 * when the output buffer empties again. This means that the app should
961 * assume that it can write since the first OUTPUT event, and no more
962 * OUTPUT events will be generated unless an error occurs.
964 * Connection succesfully established, for client sockets, or incoming
965 * client connection, for server sockets. Wait for this event (also watch
966 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
968 * The connection is lost (or a connection request failed); this could
969 * be due to a failure, or due to the peer closing it gracefully.
972 /* GSocket_SetCallback:
973 * Enables the callbacks specified by 'flags'. Note that 'flags'
974 * may be a combination of flags OR'ed toghether, so the same
975 * callback function can be made to accept different events.
976 * The callback function must have the following prototype:
978 * void function(GSocket *socket, GSocketEvent event, char *cdata)
980 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
981 GSocketCallback callback
, char *cdata
)
985 assert(socket
!= NULL
);
987 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
989 if ((flags
& (1 << count
)) != 0)
991 socket
->m_cbacks
[count
] = callback
;
992 socket
->m_data
[count
] = cdata
;
997 /* GSocket_UnsetCallback:
998 * Disables all callbacks specified by 'flags', which may be a
999 * combination of flags OR'ed toghether.
1001 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1005 assert(socket
!= NULL
);
1007 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1009 if ((flags
& (1 << count
)) != 0)
1011 socket
->m_cbacks
[count
] = NULL
;
1012 socket
->m_data
[count
] = NULL
;
1018 #define CALL_CALLBACK(socket, event) { \
1019 _GSocket_Disable(socket, event); \
1020 if (socket->m_cbacks[event]) \
1021 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1025 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
)
1027 socket
->m_detected
&= ~(1 << event
);
1028 _GSocket_Install_Callback(socket
, event
);
1031 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
)
1033 socket
->m_detected
|= (1 << event
);
1034 _GSocket_Uninstall_Callback(socket
, event
);
1037 /* _GSocket_Input_Timeout:
1038 * For blocking sockets, wait until data is available or
1039 * until timeout ellapses.
1041 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1047 /* Linux select() will overwrite the struct on return */
1048 tv
.tv_sec
= (socket
->m_timeout
/ 1000);
1049 tv
.tv_usec
= (socket
->m_timeout
% 1000) * 1000;
1051 if (!socket
->m_non_blocking
)
1054 FD_SET(socket
->m_fd
, &readfds
);
1055 ret
= select(socket
->m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1058 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1059 socket
->m_error
= GSOCK_TIMEDOUT
;
1060 return GSOCK_TIMEDOUT
;
1064 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1065 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1066 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1067 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1068 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1069 socket
->m_error
= GSOCK_TIMEDOUT
;
1070 return GSOCK_TIMEDOUT
;
1073 return GSOCK_NOERROR
;
1076 /* _GSocket_Output_Timeout:
1077 * For blocking sockets, wait until data can be sent without
1078 * blocking or until timeout ellapses.
1080 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1086 /* Linux select() will overwrite the struct on return */
1087 tv
.tv_sec
= (socket
->m_timeout
/ 1000);
1088 tv
.tv_usec
= (socket
->m_timeout
% 1000) * 1000;
1090 GSocket_Debug( ("m_non_blocking has: %d\n", (int)socket
->m_non_blocking
) );
1092 if (!socket
->m_non_blocking
)
1095 FD_SET(socket
->m_fd
, &writefds
);
1096 ret
= select(socket
->m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1099 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1100 socket
->m_error
= GSOCK_TIMEDOUT
;
1101 return GSOCK_TIMEDOUT
;
1105 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1106 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1107 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1108 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1109 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1110 socket
->m_error
= GSOCK_TIMEDOUT
;
1111 return GSOCK_TIMEDOUT
;
1113 if ( ! FD_ISSET(socket
->m_fd
, &writefds
) ) {
1114 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1117 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1122 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1125 return GSOCK_NOERROR
;
1128 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1130 return recv(socket
->m_fd
, buffer
, size
, 0);
1133 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1135 struct sockaddr from
;
1136 SOCKLEN_T fromlen
= sizeof(from
);
1140 fromlen
= sizeof(from
);
1142 ret
= recvfrom(socket
->m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1147 /* Translate a system address into a GSocket address */
1148 if (!socket
->m_peer
)
1150 socket
->m_peer
= GAddress_new();
1151 if (!socket
->m_peer
)
1153 socket
->m_error
= GSOCK_MEMERR
;
1157 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1158 if (err
!= GSOCK_NOERROR
)
1160 GAddress_destroy(socket
->m_peer
);
1161 socket
->m_peer
= NULL
;
1162 socket
->m_error
= err
;
1169 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1174 ret
= send(socket
->m_fd
, buffer
, size
, 0);
1180 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1182 struct sockaddr
*addr
;
1186 if (!socket
->m_peer
)
1188 socket
->m_error
= GSOCK_INVADDR
;
1192 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1193 if (err
!= GSOCK_NOERROR
)
1195 socket
->m_error
= err
;
1200 ret
= sendto(socket
->m_fd
, buffer
, size
, 0, addr
, len
);
1203 /* Frees memory allocated from _GAddress_translate_to */
1209 void _GSocket_Detected_Read(GSocket
*socket
)
1213 /* If we have already detected a LOST event, then don't try
1214 * to do any further processing.
1216 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
1218 socket
->m_establishing
= FALSE
;
1220 CALL_CALLBACK(socket
, GSOCK_LOST
);
1221 GSocket_Shutdown(socket
);
1225 if (recv(socket
->m_fd
, &c
, 1, MSG_PEEK
) > 0)
1227 CALL_CALLBACK(socket
, GSOCK_INPUT
);
1231 if (socket
->m_server
&& socket
->m_stream
)
1233 CALL_CALLBACK(socket
, GSOCK_CONNECTION
);
1237 CALL_CALLBACK(socket
, GSOCK_LOST
);
1238 GSocket_Shutdown(socket
);
1243 void _GSocket_Detected_Write(GSocket
*socket
)
1245 /* If we have already detected a LOST event, then don't try
1246 * to do any further processing.
1248 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
1250 socket
->m_establishing
= FALSE
;
1252 CALL_CALLBACK(socket
, GSOCK_LOST
);
1253 GSocket_Shutdown(socket
);
1257 if (socket
->m_establishing
&& !socket
->m_server
)
1260 SOCKLEN_T len
= sizeof(error
);
1262 socket
->m_establishing
= FALSE
;
1264 getsockopt(socket
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1268 CALL_CALLBACK(socket
, GSOCK_LOST
);
1269 GSocket_Shutdown(socket
);
1273 CALL_CALLBACK(socket
, GSOCK_CONNECTION
);
1274 /* We have to fire this event by hand because CONNECTION (for clients)
1275 * and OUTPUT are internally the same and we just disabled CONNECTION
1276 * events with the above macro.
1278 CALL_CALLBACK(socket
, GSOCK_OUTPUT
);
1283 CALL_CALLBACK(socket
, GSOCK_OUTPUT
);
1288 * -------------------------------------------------------------------------
1290 * -------------------------------------------------------------------------
1293 /* CHECK_ADDRESS verifies that the current address family is either
1294 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1295 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1296 * an appropiate error code.
1298 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1300 #define CHECK_ADDRESS(address, family) \
1302 if (address->m_family == GSOCK_NOFAMILY) \
1303 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1304 return address->m_error; \
1305 if (address->m_family != GSOCK_##family) \
1307 address->m_error = GSOCK_INVADDR; \
1308 return GSOCK_INVADDR; \
1312 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1314 if (address->m_family == GSOCK_NOFAMILY) \
1315 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1317 if (address->m_family != GSOCK_##family) \
1319 address->m_error = GSOCK_INVADDR; \
1325 GAddress
*GAddress_new(void)
1329 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1332 address
->m_family
= GSOCK_NOFAMILY
;
1333 address
->m_addr
= NULL
;
1339 GAddress
*GAddress_copy(GAddress
*address
)
1343 assert(address
!= NULL
);
1345 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1348 memcpy(addr2
, address
, sizeof(GAddress
));
1350 if (address
->m_addr
&& address
->m_len
> 0)
1352 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1353 if (addr2
->m_addr
== NULL
)
1358 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1364 void GAddress_destroy(GAddress
*address
)
1366 assert(address
!= NULL
);
1368 if (address
->m_addr
)
1369 free(address
->m_addr
);
1374 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1376 assert(address
!= NULL
);
1378 address
->m_family
= type
;
1381 GAddressType
GAddress_GetFamily(GAddress
*address
)
1383 assert(address
!= NULL
);
1385 return address
->m_family
;
1388 GSocketError
_GAddress_translate_from(GAddress
*address
,
1389 struct sockaddr
*addr
, int len
)
1391 address
->m_realfamily
= addr
->sa_family
;
1392 switch (addr
->sa_family
)
1395 address
->m_family
= GSOCK_INET
;
1398 address
->m_family
= GSOCK_UNIX
;
1402 address
->m_family
= GSOCK_INET6
;
1407 address
->m_error
= GSOCK_INVOP
;
1412 if (address
->m_addr
)
1413 free(address
->m_addr
);
1415 address
->m_len
= len
;
1416 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1418 if (address
->m_addr
== NULL
)
1420 address
->m_error
= GSOCK_MEMERR
;
1421 return GSOCK_MEMERR
;
1423 memcpy(address
->m_addr
, addr
, len
);
1425 return GSOCK_NOERROR
;
1428 GSocketError
_GAddress_translate_to(GAddress
*address
,
1429 struct sockaddr
**addr
, int *len
)
1431 if (!address
->m_addr
)
1433 address
->m_error
= GSOCK_INVADDR
;
1434 return GSOCK_INVADDR
;
1437 *len
= address
->m_len
;
1438 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1441 address
->m_error
= GSOCK_MEMERR
;
1442 return GSOCK_MEMERR
;
1445 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1446 return GSOCK_NOERROR
;
1450 * -------------------------------------------------------------------------
1451 * Internet address family
1452 * -------------------------------------------------------------------------
1455 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1457 address
->m_len
= sizeof(struct sockaddr_in
);
1458 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1459 if (address
->m_addr
== NULL
)
1461 address
->m_error
= GSOCK_MEMERR
;
1462 return GSOCK_MEMERR
;
1465 address
->m_family
= GSOCK_INET
;
1466 address
->m_realfamily
= PF_INET
;
1467 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1468 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1470 return GSOCK_NOERROR
;
1473 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1476 struct in_addr
*addr
;
1478 assert(address
!= NULL
);
1480 CHECK_ADDRESS(address
, INET
);
1482 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1484 /* If it is a numeric host name, convert it now */
1485 #if defined(HAVE_INET_ATON)
1486 if (inet_aton(hostname
, addr
) == 0)
1488 #elif defined(HAVE_INET_ADDR)
1489 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1492 /* Use gethostbyname by default */
1496 struct in_addr
*array_addr
;
1498 /* It is a real name, we solve it */
1499 if ((he
= gethostbyname(hostname
)) == NULL
)
1501 /* Reset to invalid address */
1502 addr
->s_addr
= INADDR_NONE
;
1503 address
->m_error
= GSOCK_NOHOST
;
1504 return GSOCK_NOHOST
;
1506 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1507 addr
->s_addr
= array_addr
[0].s_addr
;
1509 return GSOCK_NOERROR
;
1512 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1514 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1517 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1518 unsigned long hostaddr
)
1520 struct in_addr
*addr
;
1522 assert(address
!= NULL
);
1524 CHECK_ADDRESS(address
, INET
);
1526 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1527 addr
->s_addr
= hostaddr
;
1529 return GSOCK_NOERROR
;
1532 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1533 const char *protocol
)
1536 struct sockaddr_in
*addr
;
1538 assert(address
!= NULL
);
1539 CHECK_ADDRESS(address
, INET
);
1543 address
->m_error
= GSOCK_INVPORT
;
1544 return GSOCK_INVPORT
;
1547 se
= getservbyname(port
, protocol
);
1550 /* the cast to int suppresses compiler warnings about subscript having the
1552 if (isdigit((int)port
[0]))
1556 port_int
= atoi(port
);
1557 addr
= (struct sockaddr_in
*)address
->m_addr
;
1558 addr
->sin_port
= htons(port_int
);
1559 return GSOCK_NOERROR
;
1562 address
->m_error
= GSOCK_INVPORT
;
1563 return GSOCK_INVPORT
;
1566 addr
= (struct sockaddr_in
*)address
->m_addr
;
1567 addr
->sin_port
= se
->s_port
;
1569 return GSOCK_NOERROR
;
1572 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1574 struct sockaddr_in
*addr
;
1576 assert(address
!= NULL
);
1577 CHECK_ADDRESS(address
, INET
);
1579 addr
= (struct sockaddr_in
*)address
->m_addr
;
1580 addr
->sin_port
= htons(port
);
1582 return GSOCK_NOERROR
;
1585 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1589 struct sockaddr_in
*addr
;
1591 assert(address
!= NULL
);
1592 CHECK_ADDRESS(address
, INET
);
1594 addr
= (struct sockaddr_in
*)address
->m_addr
;
1595 addr_buf
= (char *)&(addr
->sin_addr
);
1597 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1600 address
->m_error
= GSOCK_NOHOST
;
1601 return GSOCK_NOHOST
;
1604 strncpy(hostname
, he
->h_name
, sbuf
);
1606 return GSOCK_NOERROR
;
1609 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1611 struct sockaddr_in
*addr
;
1613 assert(address
!= NULL
);
1614 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1616 addr
= (struct sockaddr_in
*)address
->m_addr
;
1618 return addr
->sin_addr
.s_addr
;
1621 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1623 struct sockaddr_in
*addr
;
1625 assert(address
!= NULL
);
1626 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1628 addr
= (struct sockaddr_in
*)address
->m_addr
;
1629 return ntohs(addr
->sin_port
);
1633 * -------------------------------------------------------------------------
1634 * Unix address family
1635 * -------------------------------------------------------------------------
1638 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1640 address
->m_len
= sizeof(struct sockaddr_un
);
1641 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1642 if (address
->m_addr
== NULL
)
1644 address
->m_error
= GSOCK_MEMERR
;
1645 return GSOCK_MEMERR
;
1648 address
->m_family
= GSOCK_UNIX
;
1649 address
->m_realfamily
= PF_UNIX
;
1650 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1651 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1653 return GSOCK_NOERROR
;
1656 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1658 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1660 struct sockaddr_un
*addr
;
1662 assert(address
!= NULL
);
1664 CHECK_ADDRESS(address
, UNIX
);
1666 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1667 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1668 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1670 return GSOCK_NOERROR
;
1673 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1675 struct sockaddr_un
*addr
;
1677 assert(address
!= NULL
);
1678 CHECK_ADDRESS(address
, UNIX
);
1680 addr
= (struct sockaddr_un
*)address
->m_addr
;
1682 strncpy(path
, addr
->sun_path
, sbuf
);
1684 return GSOCK_NOERROR
;
1687 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */
1689 /* vi:sts=4:sw=4:et */