]>
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
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 /* redefine some GUI-only functions to do nothing in console mode */
114 #if defined(wxUSE_GUI) && !wxUSE_GUI
115 # define _GSocket_GUI_Init(socket) (1)
116 # define _GSocket_GUI_Destroy(socket)
117 # define _GSocket_Enable_Events(socket)
118 # define _GSocket_Disable_Events(socket)
119 # define _GSocket_Install_Callback(socket, event)
120 # define _GSocket_Uninstall_Callback(socket, event)
121 #endif /* wxUSE_GUI */
123 /* debugging helpers */
124 #ifdef __GSOCKET_DEBUG__
125 # define GSocket_Debug(args) printf args
127 # define GSocket_Debug(args)
128 #endif /* __GSOCKET_DEBUG__ */
130 /* Global initialisers */
132 int GSocket_Init(void)
137 void GSocket_Cleanup(void)
141 /* Constructors / Destructors for GSocket */
143 GSocket
*GSocket_new(void)
148 socket
= (GSocket
*)malloc(sizeof(GSocket
));
153 socket
->m_fd
= INVALID_SOCKET
;
154 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
156 socket
->m_cbacks
[i
] = NULL
;
158 socket
->m_detected
= 0;
159 socket
->m_local
= NULL
;
160 socket
->m_peer
= NULL
;
161 socket
->m_error
= GSOCK_NOERROR
;
162 socket
->m_server
= FALSE
;
163 socket
->m_stream
= TRUE
;
164 socket
->m_gui_dependent
= NULL
;
165 socket
->m_non_blocking
= FALSE
;
166 socket
->m_timeout
= 10*60*1000;
167 /* 10 minutes * 60 sec * 1000 millisec */
168 socket
->m_establishing
= FALSE
;
170 /* Per-socket GUI-specific initialization */
171 success
= _GSocket_GUI_Init(socket
);
181 void GSocket_close(GSocket
*socket
)
183 _GSocket_Disable_Events(socket
);
185 socket
->m_fd
= INVALID_SOCKET
;
188 void GSocket_destroy(GSocket
*socket
)
190 assert(socket
!= NULL
);
192 /* Check that the socket is really shutdowned */
193 if (socket
->m_fd
!= INVALID_SOCKET
)
194 GSocket_Shutdown(socket
);
196 /* Per-socket GUI-specific cleanup */
197 _GSocket_GUI_Destroy(socket
);
199 /* Destroy private addresses */
201 GAddress_destroy(socket
->m_local
);
204 GAddress_destroy(socket
->m_peer
);
206 /* Destroy the socket itself */
211 * Disallow further read/write operations on this socket, close
212 * the fd and disable all callbacks.
214 void GSocket_Shutdown(GSocket
*socket
)
218 assert(socket
!= NULL
);
220 /* If socket has been created, shutdown it */
221 if (socket
->m_fd
!= INVALID_SOCKET
)
223 shutdown(socket
->m_fd
, 2);
224 GSocket_close(socket
);
227 /* Disable GUI callbacks */
228 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
229 socket
->m_cbacks
[evt
] = NULL
;
231 socket
->m_detected
= GSOCK_LOST_FLAG
;
234 /* Address handling */
240 * Set or get the local or peer address for this socket. The 'set'
241 * functions return GSOCK_NOERROR on success, an error code otherwise.
242 * The 'get' functions return a pointer to a GAddress object on success,
243 * or NULL otherwise, in which case they set the error code of the
244 * corresponding GSocket.
247 * GSOCK_INVSOCK - the socket is not valid.
248 * GSOCK_INVADDR - the address is not valid.
250 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
252 assert(socket
!= NULL
);
254 /* the socket must be initialized, or it must be a server */
255 if ((socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
))
257 socket
->m_error
= GSOCK_INVSOCK
;
258 return GSOCK_INVSOCK
;
262 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
264 socket
->m_error
= GSOCK_INVADDR
;
265 return GSOCK_INVADDR
;
269 GAddress_destroy(socket
->m_local
);
271 socket
->m_local
= GAddress_copy(address
);
273 return GSOCK_NOERROR
;
276 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
278 assert(socket
!= NULL
);
281 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
283 socket
->m_error
= GSOCK_INVADDR
;
284 return GSOCK_INVADDR
;
288 GAddress_destroy(socket
->m_peer
);
290 socket
->m_peer
= GAddress_copy(address
);
292 return GSOCK_NOERROR
;
295 GAddress
*GSocket_GetLocal(GSocket
*socket
)
298 struct sockaddr addr
;
299 SOCKLEN_T size
= sizeof(addr
);
302 assert(socket
!= NULL
);
304 /* try to get it from the m_local var first */
306 return GAddress_copy(socket
->m_local
);
308 /* else, if the socket is initialized, try getsockname */
309 if (socket
->m_fd
== INVALID_SOCKET
)
311 socket
->m_error
= GSOCK_INVSOCK
;
315 if (getsockname(socket
->m_fd
, &addr
, (SOCKLEN_T
*) &size
) < 0)
317 socket
->m_error
= GSOCK_IOERR
;
321 /* got a valid address from getsockname, create a GAddress object */
322 address
= GAddress_new();
325 socket
->m_error
= GSOCK_MEMERR
;
329 err
= _GAddress_translate_from(address
, &addr
, size
);
330 if (err
!= GSOCK_NOERROR
)
332 GAddress_destroy(address
);
333 socket
->m_error
= err
;
340 GAddress
*GSocket_GetPeer(GSocket
*socket
)
342 assert(socket
!= NULL
);
344 /* try to get it from the m_peer var */
346 return GAddress_copy(socket
->m_peer
);
351 /* Server specific parts */
353 /* GSocket_SetServer:
354 * Sets up this socket as a server. The local address must have been
355 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
356 * Returns GSOCK_NOERROR on success, one of the following otherwise:
359 * GSOCK_INVSOCK - the socket is in use.
360 * GSOCK_INVADDR - the local address has not been set.
361 * GSOCK_IOERR - low-level error.
363 GSocketError
GSocket_SetServer(GSocket
*sck
)
369 /* must not be in use */
370 if (sck
->m_fd
!= INVALID_SOCKET
)
372 sck
->m_error
= GSOCK_INVSOCK
;
373 return GSOCK_INVSOCK
;
376 /* the local addr must have been set */
379 sck
->m_error
= GSOCK_INVADDR
;
380 return GSOCK_INVADDR
;
383 /* Initialize all fields */
384 sck
->m_stream
= TRUE
;
385 sck
->m_server
= TRUE
;
386 sck
->m_oriented
= TRUE
;
388 /* Create the socket */
389 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
391 if (sck
->m_fd
== INVALID_SOCKET
)
393 sck
->m_error
= GSOCK_IOERR
;
397 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
398 _GSocket_Enable_Events(sck
);
400 /* Bind to the local address,
401 * retrieve the actual address bound,
402 * and listen up to 5 connections.
404 if ((bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
405 (getsockname(sck
->m_fd
,
406 sck
->m_local
->m_addr
,
407 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
408 (listen(sck
->m_fd
, 5) != 0))
411 sck
->m_error
= GSOCK_IOERR
;
415 return GSOCK_NOERROR
;
418 /* GSocket_WaitConnection:
419 * Waits for an incoming client connection. Returns a pointer to
420 * a GSocket object, or NULL if there was an error, in which case
421 * the last error field will be updated for the calling GSocket.
423 * Error codes (set in the calling GSocket)
424 * GSOCK_INVSOCK - the socket is not valid or not a server.
425 * GSOCK_TIMEDOUT - timeout, no incoming connections.
426 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
427 * GSOCK_MEMERR - couldn't allocate memory.
428 * GSOCK_IOERR - low-level error.
430 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
432 struct sockaddr from
;
433 SOCKLEN_T fromlen
= sizeof(from
);
438 assert(socket
!= NULL
);
440 /* Reenable CONNECTION events */
441 _GSocket_Enable(socket
, GSOCK_CONNECTION
);
443 /* If the socket has already been created, we exit immediately */
444 if (socket
->m_fd
== INVALID_SOCKET
|| !socket
->m_server
)
446 socket
->m_error
= GSOCK_INVSOCK
;
450 /* Create a GSocket object for the new connection */
451 connection
= GSocket_new();
455 socket
->m_error
= GSOCK_MEMERR
;
459 /* Wait for a connection (with timeout) */
460 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
462 GSocket_destroy(connection
);
463 /* socket->m_error set by _GSocket_Input_Timeout */
467 connection
->m_fd
= accept(socket
->m_fd
, &from
, (SOCKLEN_T
*) &fromlen
);
469 if (connection
->m_fd
== INVALID_SOCKET
)
471 if (errno
== EWOULDBLOCK
)
472 socket
->m_error
= GSOCK_WOULDBLOCK
;
474 socket
->m_error
= GSOCK_IOERR
;
476 GSocket_destroy(connection
);
480 /* Initialize all fields */
481 connection
->m_server
= FALSE
;
482 connection
->m_stream
= TRUE
;
483 connection
->m_oriented
= TRUE
;
485 /* Setup the peer address field */
486 connection
->m_peer
= GAddress_new();
487 if (!connection
->m_peer
)
489 GSocket_destroy(connection
);
490 socket
->m_error
= GSOCK_MEMERR
;
493 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
494 if (err
!= GSOCK_NOERROR
)
496 GAddress_destroy(connection
->m_peer
);
497 GSocket_destroy(connection
);
498 socket
->m_error
= err
;
502 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
503 _GSocket_Enable_Events(connection
);
508 /* Client specific parts */
511 * For stream (connection oriented) sockets, GSocket_Connect() tries
512 * to establish a client connection to a server using the peer address
513 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
514 * connection has been succesfully established, or one of the error
515 * codes listed below. Note that for nonblocking sockets, a return
516 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
517 * request can be completed later; you should use GSocket_Select()
518 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
519 * corresponding asynchronous events.
521 * For datagram (non connection oriented) sockets, GSocket_Connect()
522 * just sets the peer address established with GSocket_SetPeer() as
523 * default destination.
526 * GSOCK_INVSOCK - the socket is in use or not valid.
527 * GSOCK_INVADDR - the peer address has not been established.
528 * GSOCK_TIMEDOUT - timeout, the connection failed.
529 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
530 * GSOCK_MEMERR - couldn't allocate memory.
531 * GSOCK_IOERR - low-level error.
533 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
540 /* Enable CONNECTION events (needed for nonblocking connections) */
541 _GSocket_Enable(sck
, GSOCK_CONNECTION
);
543 if (sck
->m_fd
!= INVALID_SOCKET
)
545 sck
->m_error
= GSOCK_INVSOCK
;
546 return GSOCK_INVSOCK
;
551 sck
->m_error
= GSOCK_INVADDR
;
552 return GSOCK_INVADDR
;
555 /* Streamed or dgram socket? */
556 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
557 sck
->m_oriented
= TRUE
;
558 sck
->m_server
= FALSE
;
559 sck
->m_establishing
= FALSE
;
561 /* Create the socket */
562 sck
->m_fd
= socket(sck
->m_peer
->m_realfamily
,
563 sck
->m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
565 if (sck
->m_fd
== INVALID_SOCKET
)
567 sck
->m_error
= GSOCK_IOERR
;
571 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
572 _GSocket_Enable_Events(sck
);
574 /* Connect it to the peer address, with a timeout (see below) */
575 ret
= connect(sck
->m_fd
, sck
->m_peer
->m_addr
, sck
->m_peer
->m_len
);
581 /* If connect failed with EINPROGRESS and the GSocket object
582 * is in blocking mode, we select() for the specified timeout
583 * checking for writability to see if the connection request
586 if ((err
== EINPROGRESS
) && (!sck
->m_non_blocking
))
588 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
591 /* sck->m_error is set in _GSocket_Output_Timeout */
592 return GSOCK_TIMEDOUT
;
597 SOCKLEN_T len
= sizeof(error
);
599 getsockopt(sck
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*) &error
, &len
);
602 return GSOCK_NOERROR
;
606 /* If connect failed with EINPROGRESS and the GSocket object
607 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
608 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
609 * this way if the connection completes, a GSOCK_CONNECTION
610 * event will be generated, if enabled.
612 if ((err
== EINPROGRESS
) && (sck
->m_non_blocking
))
614 sck
->m_establishing
= TRUE
;
615 sck
->m_error
= GSOCK_WOULDBLOCK
;
616 return GSOCK_WOULDBLOCK
;
619 /* If connect failed with an error other than EINPROGRESS,
620 * then the call to GSocket_Connect has failed.
623 sck
->m_error
= GSOCK_IOERR
;
627 return GSOCK_NOERROR
;
630 /* Datagram sockets */
632 /* GSocket_SetNonOriented:
633 * Sets up this socket as a non-connection oriented (datagram) socket.
634 * Before using this function, the local address must have been set
635 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
636 * on success, or one of the following otherwise.
639 * GSOCK_INVSOCK - the socket is in use.
640 * GSOCK_INVADDR - the local address has not been set.
641 * GSOCK_IOERR - low-level error.
643 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
649 if (sck
->m_fd
!= INVALID_SOCKET
)
651 sck
->m_error
= GSOCK_INVSOCK
;
652 return GSOCK_INVSOCK
;
657 sck
->m_error
= GSOCK_INVADDR
;
658 return GSOCK_INVADDR
;
661 /* Initialize all fields */
662 sck
->m_stream
= FALSE
;
663 sck
->m_server
= FALSE
;
664 sck
->m_oriented
= FALSE
;
666 /* Create the socket */
667 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
669 if (sck
->m_fd
== INVALID_SOCKET
)
671 sck
->m_error
= GSOCK_IOERR
;
675 ioctl(sck
->m_fd
, FIONBIO
, &arg
);
676 _GSocket_Enable_Events(sck
);
678 /* Bind to the local address,
679 * and retrieve the actual address bound.
681 if ((bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
682 (getsockname(sck
->m_fd
,
683 sck
->m_local
->m_addr
,
684 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
687 sck
->m_error
= GSOCK_IOERR
;
691 return GSOCK_NOERROR
;
696 /* Like recv(), send(), ... */
697 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
701 assert(socket
!= NULL
);
703 /* Reenable INPUT events */
704 _GSocket_Enable(socket
, GSOCK_INPUT
);
706 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
708 socket
->m_error
= GSOCK_INVSOCK
;
712 /* If the socket is blocking, wait for data (with a timeout) */
713 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
717 if (socket
->m_stream
)
718 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
720 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
724 if (errno
== EWOULDBLOCK
)
725 socket
->m_error
= GSOCK_WOULDBLOCK
;
727 socket
->m_error
= GSOCK_IOERR
;
733 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
737 assert(socket
!= NULL
);
739 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
741 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
743 socket
->m_error
= GSOCK_INVSOCK
;
747 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
749 /* If the socket is blocking, wait for writability (with a timeout) */
750 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
753 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
756 if (socket
->m_stream
)
757 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
759 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
761 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
765 if (errno
== EWOULDBLOCK
)
767 socket
->m_error
= GSOCK_WOULDBLOCK
;
768 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
772 socket
->m_error
= GSOCK_IOERR
;
773 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
776 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
777 * in MSW). Once the first OUTPUT event is received, users can assume
778 * that the socket is writable until a read operation fails. Only then
779 * will further OUTPUT events be posted.
781 _GSocket_Enable(socket
, GSOCK_OUTPUT
);
785 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
791 * Polls the socket to determine its status. This function will
792 * check for the events specified in the 'flags' parameter, and
793 * it will return a mask indicating which operations can be
794 * performed. This function won't block, regardless of the
795 * mode (blocking | nonblocking) of the socket.
797 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
799 #if defined(wxUSE_GUI) && !wxUSE_GUI
801 GSocketEventFlags result
= 0;
807 /* Do not use a static struct, Linux can garble it */
811 assert(socket
!= NULL
);
816 FD_SET(socket
->m_fd
, &readfds
);
817 FD_SET(socket
->m_fd
, &writefds
);
818 FD_SET(socket
->m_fd
, &exceptfds
);
820 /* Check 'sticky' CONNECTION flag first */
821 result
|= (GSOCK_CONNECTION_FLAG
& socket
->m_detected
);
823 /* If we have already detected a LOST event, then don't try
824 * to do any further processing.
826 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
828 socket
->m_establishing
= FALSE
;
830 return (GSOCK_LOST_FLAG
& flags
);
834 if (select(socket
->m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
836 /* What to do here? */
837 return (result
& flags
);
840 /* Check for readability */
841 if (FD_ISSET(socket
->m_fd
, &readfds
))
845 if (recv(socket
->m_fd
, &c
, 1, MSG_PEEK
) > 0)
847 result
|= GSOCK_INPUT_FLAG
;
851 if (socket
->m_server
&& socket
->m_stream
)
853 result
|= GSOCK_CONNECTION_FLAG
;
854 socket
->m_detected
|= GSOCK_CONNECTION_FLAG
;
858 socket
->m_detected
= GSOCK_LOST_FLAG
;
859 socket
->m_establishing
= FALSE
;
861 /* LOST event: Abort any further processing */
862 return (GSOCK_LOST_FLAG
& flags
);
867 /* Check for writability */
868 if (FD_ISSET(socket
->m_fd
, &writefds
))
870 if (socket
->m_establishing
&& !socket
->m_server
)
873 SOCKLEN_T len
= sizeof(error
);
875 socket
->m_establishing
= FALSE
;
877 getsockopt(socket
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
881 socket
->m_detected
= GSOCK_LOST_FLAG
;
883 /* LOST event: Abort any further processing */
884 return (GSOCK_LOST_FLAG
& flags
);
888 result
|= GSOCK_CONNECTION_FLAG
;
889 socket
->m_detected
|= GSOCK_CONNECTION_FLAG
;
894 result
|= GSOCK_OUTPUT_FLAG
;
898 /* Check for exceptions and errors (is this useful in Unices?) */
899 if (FD_ISSET(socket
->m_fd
, &exceptfds
))
901 socket
->m_establishing
= FALSE
;
902 socket
->m_detected
= GSOCK_LOST_FLAG
;
904 /* LOST event: Abort any further processing */
905 return (GSOCK_LOST_FLAG
& flags
);
908 return (result
& flags
);
912 assert(socket
!= NULL
);
913 return flags
& socket
->m_detected
;
915 #endif /* !wxUSE_GUI */
920 /* GSocket_SetNonBlocking:
921 * Sets the socket to non-blocking mode. All IO calls will return
924 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
926 assert(socket
!= NULL
);
928 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
930 socket
->m_non_blocking
= non_block
;
933 /* GSocket_SetTimeout:
934 * Sets the timeout for blocking calls. Time is expressed in
937 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
939 assert(socket
!= NULL
);
941 socket
->m_timeout
= millisec
;
945 * Returns the last error occured for this socket. Note that successful
946 * operations do not clear this back to GSOCK_NOERROR, so use it only
949 GSocketError
GSocket_GetError(GSocket
*socket
)
951 assert(socket
!= NULL
);
953 return socket
->m_error
;
959 * There is data to be read in the input buffer. If, after a read
960 * operation, there is still data available, the callback function will
963 * The socket is available for writing. That is, the next write call
964 * won't block. This event is generated only once, when the connection is
965 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
966 * when the output buffer empties again. This means that the app should
967 * assume that it can write since the first OUTPUT event, and no more
968 * OUTPUT events will be generated unless an error occurs.
970 * Connection succesfully established, for client sockets, or incoming
971 * client connection, for server sockets. Wait for this event (also watch
972 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
974 * The connection is lost (or a connection request failed); this could
975 * be due to a failure, or due to the peer closing it gracefully.
978 /* GSocket_SetCallback:
979 * Enables the callbacks specified by 'flags'. Note that 'flags'
980 * may be a combination of flags OR'ed toghether, so the same
981 * callback function can be made to accept different events.
982 * The callback function must have the following prototype:
984 * void function(GSocket *socket, GSocketEvent event, char *cdata)
986 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
987 GSocketCallback callback
, char *cdata
)
991 assert(socket
!= NULL
);
993 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
995 if ((flags
& (1 << count
)) != 0)
997 socket
->m_cbacks
[count
] = callback
;
998 socket
->m_data
[count
] = cdata
;
1003 /* GSocket_UnsetCallback:
1004 * Disables all callbacks specified by 'flags', which may be a
1005 * combination of flags OR'ed toghether.
1007 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1011 assert(socket
!= NULL
);
1013 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1015 if ((flags
& (1 << count
)) != 0)
1017 socket
->m_cbacks
[count
] = NULL
;
1018 socket
->m_data
[count
] = NULL
;
1024 #define CALL_CALLBACK(socket, event) { \
1025 _GSocket_Disable(socket, event); \
1026 if (socket->m_cbacks[event]) \
1027 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1031 void _GSocket_Enable(GSocket
*socket
, GSocketEvent event
)
1033 socket
->m_detected
&= ~(1 << event
);
1034 _GSocket_Install_Callback(socket
, event
);
1037 void _GSocket_Disable(GSocket
*socket
, GSocketEvent event
)
1039 socket
->m_detected
|= (1 << event
);
1040 _GSocket_Uninstall_Callback(socket
, event
);
1043 /* _GSocket_Input_Timeout:
1044 * For blocking sockets, wait until data is available or
1045 * until timeout ellapses.
1047 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1053 /* Linux select() will overwrite the struct on return */
1054 tv
.tv_sec
= (socket
->m_timeout
/ 1000);
1055 tv
.tv_usec
= (socket
->m_timeout
% 1000) * 1000;
1057 if (!socket
->m_non_blocking
)
1060 FD_SET(socket
->m_fd
, &readfds
);
1061 ret
= select(socket
->m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1064 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1065 socket
->m_error
= GSOCK_TIMEDOUT
;
1066 return GSOCK_TIMEDOUT
;
1070 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1071 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1072 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1073 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1074 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1075 socket
->m_error
= GSOCK_TIMEDOUT
;
1076 return GSOCK_TIMEDOUT
;
1079 return GSOCK_NOERROR
;
1082 /* _GSocket_Output_Timeout:
1083 * For blocking sockets, wait until data can be sent without
1084 * blocking or until timeout ellapses.
1086 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1092 /* Linux select() will overwrite the struct on return */
1093 tv
.tv_sec
= (socket
->m_timeout
/ 1000);
1094 tv
.tv_usec
= (socket
->m_timeout
% 1000) * 1000;
1096 GSocket_Debug( ("m_non_blocking has: %d\n", (int)socket
->m_non_blocking
) );
1098 if (!socket
->m_non_blocking
)
1101 FD_SET(socket
->m_fd
, &writefds
);
1102 ret
= select(socket
->m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1105 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1106 socket
->m_error
= GSOCK_TIMEDOUT
;
1107 return GSOCK_TIMEDOUT
;
1111 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1112 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1113 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1114 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1115 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1116 socket
->m_error
= GSOCK_TIMEDOUT
;
1117 return GSOCK_TIMEDOUT
;
1119 if ( ! FD_ISSET(socket
->m_fd
, &writefds
) ) {
1120 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1123 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1128 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1131 return GSOCK_NOERROR
;
1134 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1136 return recv(socket
->m_fd
, buffer
, size
, 0);
1139 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1141 struct sockaddr from
;
1142 SOCKLEN_T fromlen
= sizeof(from
);
1146 fromlen
= sizeof(from
);
1148 ret
= recvfrom(socket
->m_fd
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1153 /* Translate a system address into a GSocket address */
1154 if (!socket
->m_peer
)
1156 socket
->m_peer
= GAddress_new();
1157 if (!socket
->m_peer
)
1159 socket
->m_error
= GSOCK_MEMERR
;
1163 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1164 if (err
!= GSOCK_NOERROR
)
1166 GAddress_destroy(socket
->m_peer
);
1167 socket
->m_peer
= NULL
;
1168 socket
->m_error
= err
;
1175 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1180 ret
= send(socket
->m_fd
, buffer
, size
, 0);
1186 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1188 struct sockaddr
*addr
;
1192 if (!socket
->m_peer
)
1194 socket
->m_error
= GSOCK_INVADDR
;
1198 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1199 if (err
!= GSOCK_NOERROR
)
1201 socket
->m_error
= err
;
1206 ret
= sendto(socket
->m_fd
, buffer
, size
, 0, addr
, len
);
1209 /* Frees memory allocated from _GAddress_translate_to */
1215 void _GSocket_Detected_Read(GSocket
*socket
)
1219 /* If we have already detected a LOST event, then don't try
1220 * to do any further processing.
1222 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
1224 socket
->m_establishing
= FALSE
;
1226 CALL_CALLBACK(socket
, GSOCK_LOST
);
1227 GSocket_Shutdown(socket
);
1231 if (recv(socket
->m_fd
, &c
, 1, MSG_PEEK
) > 0)
1233 CALL_CALLBACK(socket
, GSOCK_INPUT
);
1237 if (socket
->m_server
&& socket
->m_stream
)
1239 CALL_CALLBACK(socket
, GSOCK_CONNECTION
);
1243 CALL_CALLBACK(socket
, GSOCK_LOST
);
1244 GSocket_Shutdown(socket
);
1249 void _GSocket_Detected_Write(GSocket
*socket
)
1251 /* If we have already detected a LOST event, then don't try
1252 * to do any further processing.
1254 if ((socket
->m_detected
& GSOCK_LOST_FLAG
) != 0)
1256 socket
->m_establishing
= FALSE
;
1258 CALL_CALLBACK(socket
, GSOCK_LOST
);
1259 GSocket_Shutdown(socket
);
1263 if (socket
->m_establishing
&& !socket
->m_server
)
1266 SOCKLEN_T len
= sizeof(error
);
1268 socket
->m_establishing
= FALSE
;
1270 getsockopt(socket
->m_fd
, SOL_SOCKET
, SO_ERROR
, (void*)&error
, &len
);
1274 CALL_CALLBACK(socket
, GSOCK_LOST
);
1275 GSocket_Shutdown(socket
);
1279 CALL_CALLBACK(socket
, GSOCK_CONNECTION
);
1280 /* We have to fire this event by hand because CONNECTION (for clients)
1281 * and OUTPUT are internally the same and we just disabled CONNECTION
1282 * events with the above macro.
1284 CALL_CALLBACK(socket
, GSOCK_OUTPUT
);
1289 CALL_CALLBACK(socket
, GSOCK_OUTPUT
);
1294 * -------------------------------------------------------------------------
1296 * -------------------------------------------------------------------------
1299 /* CHECK_ADDRESS verifies that the current address family is either
1300 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1301 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1302 * an appropiate error code.
1304 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1306 #define CHECK_ADDRESS(address, family) \
1308 if (address->m_family == GSOCK_NOFAMILY) \
1309 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1310 return address->m_error; \
1311 if (address->m_family != GSOCK_##family) \
1313 address->m_error = GSOCK_INVADDR; \
1314 return GSOCK_INVADDR; \
1318 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1320 if (address->m_family == GSOCK_NOFAMILY) \
1321 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1323 if (address->m_family != GSOCK_##family) \
1325 address->m_error = GSOCK_INVADDR; \
1331 GAddress
*GAddress_new(void)
1335 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1338 address
->m_family
= GSOCK_NOFAMILY
;
1339 address
->m_addr
= NULL
;
1345 GAddress
*GAddress_copy(GAddress
*address
)
1349 assert(address
!= NULL
);
1351 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1354 memcpy(addr2
, address
, sizeof(GAddress
));
1356 if (address
->m_addr
&& address
->m_len
> 0)
1358 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1359 if (addr2
->m_addr
== NULL
)
1364 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1370 void GAddress_destroy(GAddress
*address
)
1372 assert(address
!= NULL
);
1374 if (address
->m_addr
)
1375 free(address
->m_addr
);
1380 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1382 assert(address
!= NULL
);
1384 address
->m_family
= type
;
1387 GAddressType
GAddress_GetFamily(GAddress
*address
)
1389 assert(address
!= NULL
);
1391 return address
->m_family
;
1394 GSocketError
_GAddress_translate_from(GAddress
*address
,
1395 struct sockaddr
*addr
, int len
)
1397 address
->m_realfamily
= addr
->sa_family
;
1398 switch (addr
->sa_family
)
1401 address
->m_family
= GSOCK_INET
;
1404 address
->m_family
= GSOCK_UNIX
;
1408 address
->m_family
= GSOCK_INET6
;
1413 address
->m_error
= GSOCK_INVOP
;
1418 if (address
->m_addr
)
1419 free(address
->m_addr
);
1421 address
->m_len
= len
;
1422 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1424 if (address
->m_addr
== NULL
)
1426 address
->m_error
= GSOCK_MEMERR
;
1427 return GSOCK_MEMERR
;
1429 memcpy(address
->m_addr
, addr
, len
);
1431 return GSOCK_NOERROR
;
1434 GSocketError
_GAddress_translate_to(GAddress
*address
,
1435 struct sockaddr
**addr
, int *len
)
1437 if (!address
->m_addr
)
1439 address
->m_error
= GSOCK_INVADDR
;
1440 return GSOCK_INVADDR
;
1443 *len
= address
->m_len
;
1444 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1447 address
->m_error
= GSOCK_MEMERR
;
1448 return GSOCK_MEMERR
;
1451 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1452 return GSOCK_NOERROR
;
1456 * -------------------------------------------------------------------------
1457 * Internet address family
1458 * -------------------------------------------------------------------------
1461 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1463 address
->m_len
= sizeof(struct sockaddr_in
);
1464 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1465 if (address
->m_addr
== NULL
)
1467 address
->m_error
= GSOCK_MEMERR
;
1468 return GSOCK_MEMERR
;
1471 address
->m_family
= GSOCK_INET
;
1472 address
->m_realfamily
= PF_INET
;
1473 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1474 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1476 return GSOCK_NOERROR
;
1479 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1482 struct in_addr
*addr
;
1484 assert(address
!= NULL
);
1486 CHECK_ADDRESS(address
, INET
);
1488 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1490 /* If it is a numeric host name, convert it now */
1491 #if defined(HAVE_INET_ATON)
1492 if (inet_aton(hostname
, addr
) == 0)
1494 #elif defined(HAVE_INET_ADDR)
1495 if ( (addr
->s_addr
= inet_addr(hostname
)) == -1 )
1498 /* Use gethostbyname by default */
1502 struct in_addr
*array_addr
;
1504 /* It is a real name, we solve it */
1505 if ((he
= gethostbyname(hostname
)) == NULL
)
1507 /* Reset to invalid address */
1508 addr
->s_addr
= INADDR_NONE
;
1509 address
->m_error
= GSOCK_NOHOST
;
1510 return GSOCK_NOHOST
;
1512 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1513 addr
->s_addr
= array_addr
[0].s_addr
;
1515 return GSOCK_NOERROR
;
1518 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1520 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1523 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1524 unsigned long hostaddr
)
1526 struct in_addr
*addr
;
1528 assert(address
!= NULL
);
1530 CHECK_ADDRESS(address
, INET
);
1532 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1533 addr
->s_addr
= hostaddr
;
1535 return GSOCK_NOERROR
;
1538 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1539 const char *protocol
)
1542 struct sockaddr_in
*addr
;
1544 assert(address
!= NULL
);
1545 CHECK_ADDRESS(address
, INET
);
1549 address
->m_error
= GSOCK_INVPORT
;
1550 return GSOCK_INVPORT
;
1553 se
= getservbyname(port
, protocol
);
1556 /* the cast to int suppresses compiler warnings about subscript having the
1558 if (isdigit((int)port
[0]))
1562 port_int
= atoi(port
);
1563 addr
= (struct sockaddr_in
*)address
->m_addr
;
1564 addr
->sin_port
= htons(port_int
);
1565 return GSOCK_NOERROR
;
1568 address
->m_error
= GSOCK_INVPORT
;
1569 return GSOCK_INVPORT
;
1572 addr
= (struct sockaddr_in
*)address
->m_addr
;
1573 addr
->sin_port
= se
->s_port
;
1575 return GSOCK_NOERROR
;
1578 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1580 struct sockaddr_in
*addr
;
1582 assert(address
!= NULL
);
1583 CHECK_ADDRESS(address
, INET
);
1585 addr
= (struct sockaddr_in
*)address
->m_addr
;
1586 addr
->sin_port
= htons(port
);
1588 return GSOCK_NOERROR
;
1591 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1595 struct sockaddr_in
*addr
;
1597 assert(address
!= NULL
);
1598 CHECK_ADDRESS(address
, INET
);
1600 addr
= (struct sockaddr_in
*)address
->m_addr
;
1601 addr_buf
= (char *)&(addr
->sin_addr
);
1603 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1606 address
->m_error
= GSOCK_NOHOST
;
1607 return GSOCK_NOHOST
;
1610 strncpy(hostname
, he
->h_name
, sbuf
);
1612 return GSOCK_NOERROR
;
1615 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1617 struct sockaddr_in
*addr
;
1619 assert(address
!= NULL
);
1620 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1622 addr
= (struct sockaddr_in
*)address
->m_addr
;
1624 return addr
->sin_addr
.s_addr
;
1627 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1629 struct sockaddr_in
*addr
;
1631 assert(address
!= NULL
);
1632 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1634 addr
= (struct sockaddr_in
*)address
->m_addr
;
1635 return ntohs(addr
->sin_port
);
1639 * -------------------------------------------------------------------------
1640 * Unix address family
1641 * -------------------------------------------------------------------------
1644 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1646 address
->m_len
= sizeof(struct sockaddr_un
);
1647 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
1648 if (address
->m_addr
== NULL
)
1650 address
->m_error
= GSOCK_MEMERR
;
1651 return GSOCK_MEMERR
;
1654 address
->m_family
= GSOCK_UNIX
;
1655 address
->m_realfamily
= PF_UNIX
;
1656 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
1657 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
1659 return GSOCK_NOERROR
;
1662 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
1664 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1666 struct sockaddr_un
*addr
;
1668 assert(address
!= NULL
);
1670 CHECK_ADDRESS(address
, UNIX
);
1672 addr
= ((struct sockaddr_un
*)address
->m_addr
);
1673 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
1674 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
1676 return GSOCK_NOERROR
;
1679 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1681 struct sockaddr_un
*addr
;
1683 assert(address
!= NULL
);
1684 CHECK_ADDRESS(address
, UNIX
);
1686 addr
= (struct sockaddr_un
*)address
->m_addr
;
1688 strncpy(path
, addr
->sun_path
, sbuf
);
1690 return GSOCK_NOERROR
;
1693 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */