1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Authors: Guilhem Lavaux,
5 * Guillermo Rodriguez Garcia <guille@iies.es> (maintainer)
7 * Purpose: GSocket main mac file
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 <CoreServices/CoreServices.h>
32 #define OTUNIXERRORS 1
33 #include <OpenTransport.h>
34 #include <OpenTransportProviders.h>
35 #include <OpenTptInternet.h>
38 #define OTAssert( str , cond ) /* does not exists in Carbon */
52 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
53 * on all unices. INADDR_BROADCAST should be fine to indicate an error.
55 #ifndef INADDR_BROADCAST
56 #define INADDR_BROADCAST 0xFFFFFFFFUL
59 #define INADDR_NONE INADDR_BROADCAST
62 #define INADDR_ANY 0x0UL
64 #ifndef __GSOCKET_STANDALONE__
66 #include "wx/mac/macnotfy.h"
67 #include "wx/mac/gsockmac.h"
68 #include "wx/gsocket.h"
75 #endif /* __GSOCKET_STANDALONE__ */
81 extern pascal void OTDebugStr(const char* str
);
86 InetSvcRef gInetSvcRef
= 0 ;
89 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
);
91 /* Input: ep - endpointref on which to negotiate the option
92 enableReuseIPMode - desired option setting - true/false
93 Return: kOTNoError indicates that the option was successfully negotiated
94 OSStatus is an error if < 0, otherwise, the status field is
97 IMPORTANT NOTE: The endpoint is assumed to be in synchronous more, otherwise
98 this code will not function as desired
102 OSStatus
DoNegotiateIPReuseAddrOption(EndpointRef ep
, Boolean enableReuseIPMode
)
105 UInt8 buf
[kOTFourByteOptionSize
]; // define buffer for fourByte Option size
106 TOption
* opt
; // option ptr to make items easier to access
111 if (!OTIsSynchronous(ep
))
115 opt
= (TOption
*)buf
; // set option ptr to buffer
117 req
.opt
.len
= sizeof(buf
);
118 req
.flags
= T_NEGOTIATE
; // negotiate for option
121 ret
.opt
.maxlen
= kOTFourByteOptionSize
;
123 opt
->level
= INET_IP
; // dealing with an IP Level function
125 opt
->name
= kIP_REUSEADDR
;
127 opt
->name
= IP_REUSEADDR
;
129 opt
->len
= kOTFourByteOptionSize
;
131 *(UInt32
*)opt
->value
= enableReuseIPMode
; // set the desired option level, true or false
133 err
= OTOptionManagement(ep
, &req
, &ret
);
135 // if no error then return the option status value
136 if (err
== kOTNoError
)
138 if (opt
->status
!= T_SUCCESS
)
148 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult
, void *cookie
) ;
149 pascal void OTInetEventHandler(void*s
, OTEventCode event
, OTResult result
, void *cookie
)
152 GSocket
* sock
= (GSocket
*) s
;
154 if ( event
== kOTSyncIdleEvent
)
162 wxMacAddEvent( sock
->m_mac_events
, _GSocket_Internal_Proc
, event
, s
, wakeUp
) ;
168 static void SetDefaultEndpointModes(EndpointRef ep
, void *data
)
169 // This routine sets the supplied endpoint into the default
170 // mode used in this application. The specifics are:
171 // blocking, synchronous, and using synch idle events with
172 // the standard YieldingNotifier.
174 OSStatus junk
= kOTNoError
;
175 OTAssert ("SetDefaultEndpointModes:invalid ref", ep
!= kOTInvalidEndpointRef
) ;
176 junk
= OTSetAsynchronous(ep
);
177 OTAssert("SetDefaultEndpointModes: Could not set asynchronous", junk
== noErr
);
179 junk = OTSetBlocking(ep);
180 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
181 junk = OTSetSynchronous(ep);
182 OTAssert("SetDefaultEndpointModes: Could not set synchronous", junk == noErr);
183 junk = OTSetBlocking(ep);
184 OTAssert("SetDefaultEndpointModes: Could not set blocking", junk == noErr);
186 junk
= OTInstallNotifier(ep
, OTInetEventHandler
, data
);
187 OTAssert("SetDefaultEndpointModes: Could not install notifier", junk
== noErr
);
189 junk = OTUseSyncIdleEvents(ep, true);
190 OTAssert("SetDefaultEndpointModes: Could not use sync idle events", junk == noErr);
194 /* Global initialisers */
201 int GSocket_Verify_Inited() ;
202 int GSocket_Verify_Inited()
206 // Marc Newsam: added the clientcontext variable
207 // however, documentation is unclear how this works
208 OTClientContextPtr clientcontext
;
213 InitOpenTransportInContext(kInitOTForApplicationMask
, &clientcontext
);
215 gInetSvcRef
= OTOpenInternetServicesInContext(kDefaultInternetServicesPath
,
216 NULL
, &err
, clientcontext
);
221 InitOpenTransport() ;
223 gInetSvcRef
= OTOpenInternetServices(kDefaultInternetServicesPath
, NULL
, &err
);
225 if ( gInetSvcRef
== NULL
|| err
!= kOTNoError
)
227 OTAssert("Could not open Inet Services", err
== noErr
);
233 void GSocket_Cleanup()
235 if ( gOTInited
!= 0 )
237 if ( gInetSvcRef
!= NULL
)
238 OTCloseProvider( gInetSvcRef
);
240 CloseOpenTransportInContext( NULL
) ;
242 CloseOpenTransport() ;
247 /* Constructors / Destructors for GSocket */
249 GSocket
*GSocket_new()
255 if ( GSocket_Verify_Inited() == FALSE
)
258 socket
= (GSocket
*)malloc(sizeof(GSocket
));
263 socket
->m_endpoint
= NULL
;
264 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
266 socket
->m_cbacks
[i
] = NULL
;
268 socket
->m_detected
= 0;
269 socket
->m_local
= NULL
;
270 socket
->m_peer
= NULL
;
271 socket
->m_error
= GSOCK_NOERROR
;
272 socket
->m_server
= FALSE
;
273 socket
->m_stream
= TRUE
;
274 socket
->m_non_blocking
= FALSE
;
275 socket
->m_timeout
= 1*1000;
276 /* 10 sec * 1000 millisec */
277 socket
->m_takesEvents
= TRUE
;
278 socket
->m_mac_events
= wxMacGetNotifierTable() ;
282 void GSocket_destroy(GSocket
*socket
)
284 assert(socket
!= NULL
);
286 /* Check that the socket is really shutdowned */
287 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
288 GSocket_Shutdown(socket
);
291 /* Destroy private addresses */
293 GAddress_destroy(socket
->m_local
);
296 GAddress_destroy(socket
->m_peer
);
298 /* Destroy the socket itself */
303 * Disallow further read/write operations on this socket, close
304 * the fd and disable all callbacks.
306 void GSocket_Shutdown(GSocket
*socket
)
311 assert(socket
!= NULL
);
313 /* If socket has been created, shutdown it */
314 if (socket
->m_endpoint
!= kOTInvalidEndpointRef
)
316 err
= OTSndOrderlyDisconnect( socket
->m_endpoint
) ;
317 if ( err
!= kOTNoError
)
321 err
= OTRcvOrderlyDisconnect( socket
->m_endpoint
) ;
322 err
= OTUnbind( socket
->m_endpoint
) ;
323 err
= OTCloseProvider( socket
->m_endpoint
) ;
324 socket
->m_endpoint
= kOTInvalidEndpointRef
;
327 /* Disable GUI callbacks */
328 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
329 socket
->m_cbacks
[evt
] = NULL
;
331 socket
->m_detected
= 0;
332 _GSocket_Disable_Events(socket
);
333 wxMacRemoveAllNotifiersForData( wxMacGetNotifierTable() , socket
) ;
337 /* Address handling */
343 * Set or get the local or peer address for this socket. The 'set'
344 * functions return GSOCK_NOERROR on success, an error code otherwise.
345 * The 'get' functions return a pointer to a GAddress object on success,
346 * or NULL otherwise, in which case they set the error code of the
347 * corresponding GSocket.
350 * GSOCK_INVSOCK - the socket is not valid.
351 * GSOCK_INVADDR - the address is not valid.
353 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
355 assert(socket
!= NULL
);
357 /* the socket must be initialized, or it must be a server */
358 if ((socket
->m_endpoint
!= kOTInvalidEndpointRef
&& !socket
->m_server
))
360 socket
->m_error
= GSOCK_INVSOCK
;
361 return GSOCK_INVSOCK
;
365 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
367 socket
->m_error
= GSOCK_INVADDR
;
368 return GSOCK_INVADDR
;
372 GAddress_destroy(socket
->m_local
);
374 socket
->m_local
= GAddress_copy(address
);
376 return GSOCK_NOERROR
;
379 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
381 assert(socket
!= NULL
);
384 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
386 socket
->m_error
= GSOCK_INVADDR
;
387 return GSOCK_INVADDR
;
391 GAddress_destroy(socket
->m_peer
);
393 socket
->m_peer
= GAddress_copy(address
);
395 return GSOCK_NOERROR
;
398 GAddress
*GSocket_GetLocal(GSocket
*socket
)
400 GAddress
*address
= NULL
;
404 assert(socket
!= NULL
);
406 /* try to get it from the m_local var first */
408 return GAddress_copy(socket
->m_local
);
410 /* else, if the socket is initialized, try getsockname */
411 if (socket
->m_endpoint
== kOTInvalidEndpointRef
)
413 socket
->m_error
= GSOCK_INVSOCK
;
418 /* we do not support multihoming with this code at the moment
419 OTGetProtAddress will have to be used then - but we don't have a handy
420 method to use right now
423 InetInterfaceInfo info
;
424 OTInetGetInterfaceInfo(&info
, kDefaultInetInterface
);
425 loc
.fHost
= info
.fAddress
;
427 loc
.fAddressType
= AF_INET
;
430 /* got a valid address from getsockname, create a GAddress object */
431 address
= GAddress_new();
434 socket
->m_error
= GSOCK_MEMERR
;
438 err
= _GAddress_translate_from(address
, &loc
);
439 if (err
!= GSOCK_NOERROR
)
441 GAddress_destroy(address
);
442 socket
->m_error
= err
;
449 GAddress
*GSocket_GetPeer(GSocket
*socket
)
451 assert(socket
!= NULL
);
453 /* try to get it from the m_peer var */
455 return GAddress_copy(socket
->m_peer
);
460 /* Server specific parts */
462 /* GSocket_SetServer:
463 * Sets up this socket as a server. The local address must have been
464 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
465 * Returns GSOCK_NOERROR on success, one of the following otherwise:
468 * GSOCK_INVSOCK - the socket is in use.
469 * GSOCK_INVADDR - the local address has not been set.
470 * GSOCK_IOERR - low-level error.
472 GSocketError
GSocket_SetServer(GSocket
*sck
)
479 /* must not be in use */
480 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
482 sck
->m_error
= GSOCK_INVSOCK
;
483 return GSOCK_INVSOCK
;
486 /* the local addr must have been set */
489 sck
->m_error
= GSOCK_INVADDR
;
490 return GSOCK_INVADDR
;
493 /* Initialize all fields */
494 sck
->m_stream
= TRUE
;
495 sck
->m_server
= TRUE
;
496 sck
->m_oriented
= TRUE
;
500 /* Create the socket */
501 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
502 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
503 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
505 sck
->m_error
= GSOCK_IOERR
;
509 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
510 _GSocket_Enable_Events(sck
);
512 /* Bind to the local address,
513 * retrieve the actual address bound,
514 * and listen up to 5 connections.
516 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
517 (getsockname(sck
->m_endpoint
,
518 sck
->m_local
->m_addr
,
519 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0) ||
520 (listen(sck
->m_endpoint
, 5) != 0))
522 close(sck
->m_endpoint
);
523 sck
->m_endpoint
= -1;
524 sck
->m_error
= GSOCK_IOERR
;
528 return GSOCK_NOERROR
;
531 /* GSocket_WaitConnection:
532 * Waits for an incoming client connection. Returns a pointer to
533 * a GSocket object, or NULL if there was an error, in which case
534 * the last error field will be updated for the calling GSocket.
536 * Error codes (set in the calling GSocket)
537 * GSOCK_INVSOCK - the socket is not valid or not a server.
538 * GSOCK_TIMEDOUT - timeout, no incoming connections.
539 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
540 * GSOCK_MEMERR - couldn't allocate memory.
541 * GSOCK_IOERR - low-level error.
543 GSocket
*GSocket_WaitConnection(GSocket
*socket
)
545 GSocket
*connection
= NULL
;
550 assert(socket
!= NULL
);
552 /* Reenable CONNECTION events */
553 socket
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
555 /* If the socket has already been created, we exit immediately */
556 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| !socket
->m_server
)
558 socket
->m_error
= GSOCK_INVSOCK
;
562 /* Create a GSocket object for the new connection */
563 connection
= GSocket_new();
567 socket
->m_error
= GSOCK_MEMERR
;
571 /* Wait for a connection (with timeout) */
572 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
574 GSocket_destroy(connection
);
575 /* socket->m_error set by _GSocket_Input_Timeout */
581 connection
->m_endpoint
= accept(socket
->m_endpoint
, &from
, (SOCKLEN_T
*) &fromlen
);
584 if (connection
->m_endpoint
== kOTInvalidEndpointRef
)
586 if (errno
== EWOULDBLOCK
)
587 socket
->m_error
= GSOCK_WOULDBLOCK
;
589 socket
->m_error
= GSOCK_IOERR
;
591 GSocket_destroy(connection
);
595 /* Initialize all fields */
596 connection
->m_server
= FALSE
;
597 connection
->m_stream
= TRUE
;
598 connection
->m_oriented
= TRUE
;
600 /* Setup the peer address field */
601 connection
->m_peer
= GAddress_new();
602 if (!connection
->m_peer
)
604 GSocket_destroy(connection
);
605 socket
->m_error
= GSOCK_MEMERR
;
610 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
611 if (err
!= GSOCK_NOERROR
)
613 GAddress_destroy(connection
->m_peer
);
614 GSocket_destroy(connection
);
615 socket
->m_error
= err
;
619 ioctl(connection
->m_endpoint
, FIONBIO
, &arg
);
621 _GSocket_Enable_Events(connection
);
626 /* Datagram sockets */
628 /* GSocket_SetNonOriented:
629 * Sets up this socket as a non-connection oriented (datagram) socket.
630 * Before using this function, the local address must have been set
631 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
632 * on success, or one of the following otherwise.
635 * GSOCK_INVSOCK - the socket is in use.
636 * GSOCK_INVADDR - the local address has not been set.
637 * GSOCK_IOERR - low-level error.
639 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
645 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
647 sck
->m_error
= GSOCK_INVSOCK
;
648 return GSOCK_INVSOCK
;
653 sck
->m_error
= GSOCK_INVADDR
;
654 return GSOCK_INVADDR
;
657 /* Initialize all fields */
658 sck
->m_stream
= FALSE
;
659 sck
->m_server
= FALSE
;
660 sck
->m_oriented
= FALSE
;
662 /* Create the socket */
666 sck
->m_endpoint
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
667 socket_set_ref( sck
->m_endpoint
, (unsigned long) &gMacNetEvents
, (unsigned long) sck
) ;
669 if (sck
->m_endpoint
== kOTInvalidEndpointRef
)
671 sck
->m_error
= GSOCK_IOERR
;
677 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
679 _GSocket_Enable_Events(sck
);
681 /* Bind to the local address,
682 * and retrieve the actual address bound.
686 if ((bind(sck
->m_endpoint
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
687 (getsockname(sck
->m_endpoint
,
688 sck
->m_local
->m_addr
,
689 (SOCKLEN_T
*) &sck
->m_local
->m_len
) != 0))
691 close(sck
->m_endpoint
);
692 sck
->m_endpoint
= -1;
693 sck
->m_error
= GSOCK_IOERR
;
697 return GSOCK_NOERROR
;
700 /* Client specific parts */
703 * For stream (connection oriented) sockets, GSocket_Connect() tries
704 * to establish a client connection to a server using the peer address
705 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
706 * connection has been succesfully established, or one of the error
707 * codes listed below. Note that for nonblocking sockets, a return
708 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
709 * request can be completed later; you should use GSocket_Select()
710 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
711 * corresponding asynchronous events.
713 * For datagram (non connection oriented) sockets, GSocket_Connect()
714 * just sets the peer address established with GSocket_SetPeer() as
715 * default destination.
718 * GSOCK_INVSOCK - the socket is in use or not valid.
719 * GSOCK_INVADDR - the peer address has not been established.
720 * GSOCK_TIMEDOUT - timeout, the connection failed.
721 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
722 * GSOCK_MEMERR - couldn't allocate memory.
723 * GSOCK_IOERR - low-level error.
725 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
732 OSStatus err
= kOTNoError
;
737 /* Enable CONNECTION events (needed for nonblocking connections) */
738 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
740 if (sck
->m_endpoint
!= kOTInvalidEndpointRef
)
742 sck
->m_error
= GSOCK_INVSOCK
;
743 return GSOCK_INVSOCK
;
748 sck
->m_error
= GSOCK_INVADDR
;
749 return GSOCK_INVADDR
;
752 /* Streamed or dgram socket? */
753 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
754 sck
->m_oriented
= TRUE
;
755 sck
->m_server
= FALSE
;
757 /* Create the socket */
760 OTOpenEndpointInContext( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
, NULL
) ;
763 OTOpenEndpoint( OTCreateConfiguration( kTCPName
) , 0 , &info
, &err
) ;
765 if ( sck
->m_endpoint
== kOTInvalidEndpointRef
|| err
!= kOTNoError
)
767 sck
->m_endpoint
= kOTInvalidEndpointRef
;
768 sck
->m_error
= GSOCK_IOERR
;
771 err
= OTBind( sck
->m_endpoint
, nil
, nil
) ;
772 if ( err
!= kOTNoError
)
776 SetDefaultEndpointModes( sck
->m_endpoint
, sck
) ;
779 ioctl(sck
->m_endpoint
, FIONBIO
, &arg
);
781 _GSocket_Enable_Events(sck
);
783 _GAddress_translate_to( sck
->m_peer
, &addr
) ;
784 memset( &peer
, 0 , sizeof( TCall
) ) ;
785 peer
.addr
.len
= sizeof( InetAddress
) ;
786 peer
.addr
.buf
= (unsigned char*) &addr
;
787 err
= OTConnect( sck
->m_endpoint
, &peer
, nil
) ;
790 /* If connect failed with EINPROGRESS and the GSocket object
791 * is in blocking mode, we select() for the specified timeout
792 * checking for writability to see if the connection request
796 if ((err
== kOTNoDataErr
) && (!sck
->m_non_blocking
))
798 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
800 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
801 sck
->m_endpoint
= kOTInvalidEndpointRef
;
802 /* sck->m_error is set in _GSocket_Output_Timeout */
803 return GSOCK_TIMEDOUT
;
809 SOCKLEN_T len = sizeof(error);
811 getsockopt(sck->m_endpoint, SOL_SOCKET, SO_ERROR, (void*) &error, &len);
815 return GSOCK_NOERROR
;
819 /* If connect failed with EINPROGRESS and the GSocket object
820 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
821 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
822 * this way if the connection completes, a GSOCK_CONNECTION
823 * event will be generated, if enabled.
825 if ((err
== kOTNoDataErr
) && (sck
->m_non_blocking
))
827 sck
->m_error
= GSOCK_WOULDBLOCK
;
828 return GSOCK_WOULDBLOCK
;
831 /* If connect failed with an error other than EINPROGRESS,
832 * then the call to GSocket_Connect has failed.
834 OTSndOrderlyDisconnect( sck
->m_endpoint
) ;
836 sck
->m_endpoint
= kOTInvalidEndpointRef
;
837 sck
->m_error
= GSOCK_IOERR
;
840 // OTInetEventHandler(sck, T_CONNECT , kOTNoError , NULL ) ;
841 return GSOCK_NOERROR
;
846 /* Like recv(), send(), ... */
847 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
851 assert(socket
!= NULL
);
853 /* Reenable INPUT events */
854 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
856 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
858 socket
->m_error
= GSOCK_INVSOCK
;
862 /* If the socket is blocking, wait for data (with a timeout) */
863 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
867 if (socket
->m_stream
)
868 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
870 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
874 if (errno
== EWOULDBLOCK
)
875 socket
->m_error
= GSOCK_WOULDBLOCK
;
877 socket
->m_error
= GSOCK_IOERR
;
883 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
887 assert(socket
!= NULL
);
889 if (socket
->m_endpoint
== kOTInvalidEndpointRef
|| socket
->m_server
)
891 socket
->m_error
= GSOCK_INVSOCK
;
895 /* If the socket is blocking, wait for writability (with a timeout) */
896 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
900 if (socket
->m_stream
)
901 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
903 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
907 if (errno
== EWOULDBLOCK
)
908 socket
->m_error
= GSOCK_WOULDBLOCK
;
910 socket
->m_error
= GSOCK_IOERR
;
912 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
913 * in MSW). Once the first OUTPUT event is received, users can assume
914 * that the socket is writable until a read operation fails. Only then
915 * will further OUTPUT events be posted.
917 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
925 * Polls the socket to determine its status. This function will
926 * check for the events specified in the 'flags' parameter, and
927 * it will return a mask indicating which operations can be
928 * performed. This function won't block, regardless of the
929 * mode (blocking | nonblocking) of the socket.
931 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
934 assert(socket
!= NULL
);
935 wxMacProcessNotifierEvents() ;
937 state = OTGetEndpointState(socket->m_endpoint);
939 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_INPUT_FLAG ) )
942 OTCountDataBytes( socket->m_endpoint , &sz ) ;
943 if ( state == T_INCON || sz > 0 )
945 socket->m_detected |= GSOCK_INPUT_FLAG ;
946 (socket->m_cbacks[GSOCK_INPUT])(socket, GSOCK_INPUT, socket->m_data[GSOCK_INPUT]);
949 if ( ( flags & GSOCK_INPUT_FLAG ) && ! ( socket->m_detected & GSOCK_OUTPUT_FLAG ) )
951 if ( state == T_DATAXFER || state == T_INREL )
953 socket->m_detected |=GSOCK_OUTPUT_FLAG ;
954 (socket->m_cbacks[GSOCK_OUTPUT])(socket, GSOCK_OUTPUT, socket->m_data[GSOCK_OUTPUT]);
958 return ( flags
& socket
->m_detected
) ;
963 /* GSocket_SetNonBlocking:
964 * Sets the socket to non-blocking mode. All IO calls will return
967 void GSocket_SetNonBlocking(GSocket
*socket
, int non_block
)
969 assert(socket
!= NULL
);
971 socket
->m_non_blocking
= non_block
;
974 /* GSocket_SetTimeout:
975 * Sets the timeout for blocking calls. Time is expressed in
978 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisec
)
980 assert(socket
!= NULL
);
982 // this is usually set too high and we have not yet been able to detect a closed
983 // stream, thus we leave the 10 sec timeout
984 // socket->m_timeout = millisec;
988 * Returns the last error occured for this socket. Note that successful
989 * operations do not clear this back to GSOCK_NOERROR, so use it only
992 GSocketError
GSocket_GetError(GSocket
*socket
)
994 assert(socket
!= NULL
);
996 return socket
->m_error
;
1002 * There is data to be read in the input buffer. If, after a read
1003 * operation, there is still data available, the callback function will
1006 * The socket is available for writing. That is, the next write call
1007 * won't block. This event is generated only once, when the connection is
1008 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1009 * when the output buffer empties again. This means that the app should
1010 * assume that it can write since the first OUTPUT event, and no more
1011 * OUTPUT events will be generated unless an error occurs.
1013 * Connection succesfully established, for client sockets, or incoming
1014 * client connection, for server sockets. Wait for this event (also watch
1015 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1017 * The connection is lost (or a connection request failed); this could
1018 * be due to a failure, or due to the peer closing it gracefully.
1021 /* GSocket_SetCallback:
1022 * Enables the callbacks specified by 'flags'. Note that 'flags'
1023 * may be a combination of flags OR'ed toghether, so the same
1024 * callback function can be made to accept different events.
1025 * The callback function must have the following prototype:
1027 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1029 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
1030 GSocketCallback callback
, char *cdata
)
1034 assert(socket
!= NULL
);
1036 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1038 if ((flags
& (1 << count
)) != 0)
1040 socket
->m_cbacks
[count
] = callback
;
1041 socket
->m_data
[count
] = cdata
;
1046 /* GSocket_UnsetCallback:
1047 * Disables all callbacks specified by 'flags', which may be a
1048 * combination of flags OR'ed toghether.
1050 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
1054 assert(socket
!= NULL
);
1056 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1058 if ((flags
& (1 << count
)) != 0)
1060 socket
->m_cbacks
[count
] = NULL
;
1061 socket
->m_data
[count
] = NULL
;
1067 #define CALL_CALLBACK(socket, event) { \
1068 _GSocket_Disable(socket, event); \
1069 if (socket->m_cbacks[event]) \
1070 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1073 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1077 OTByteCount sz
= 0 ;
1079 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1082 res
= OTRcv( socket
->m_endpoint
, buffer
, size
, &flags
) ;
1088 // we simulate another read event if there are still bytes
1089 if ( socket
->m_takesEvents
)
1091 OTByteCount sz
= 0 ;
1092 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1095 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1096 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1102 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1107 struct sockaddr from
;
1108 SOCKLEN_T fromlen
= sizeof(from
);
1111 fromlen
= sizeof(from
);
1113 ret
= recvfrom(socket
->m_endpoint
, buffer
, size
, 0, &from
, (SOCKLEN_T
*) &fromlen
);
1118 /* Translate a system address into a GSocket address */
1119 if (!socket
->m_peer
)
1121 socket
->m_peer
= GAddress_new();
1122 if (!socket
->m_peer
)
1124 socket
->m_error
= GSOCK_MEMERR
;
1128 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1129 if (err
!= GSOCK_NOERROR
)
1131 GAddress_destroy(socket
->m_peer
);
1132 socket
->m_peer
= NULL
;
1133 socket
->m_error
= err
;
1140 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1145 res
= OTSnd( socket
->m_endpoint
, (void*) buffer
, size
, flags
) ;
1149 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1154 struct sockaddr
*addr
;
1158 if (!socket
->m_peer
)
1160 socket
->m_error
= GSOCK_INVADDR
;
1164 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1165 if (err
!= GSOCK_NOERROR
)
1167 socket
->m_error
= err
;
1171 ret
= sendto(socket
->m_endpoint
, buffer
, size
, 0, addr
, len
);
1173 /* Frees memory allocated from _GAddress_translate_to */
1181 * -------------------------------------------------------------------------
1183 * -------------------------------------------------------------------------
1186 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1187 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1188 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1190 #define CHECK_ADDRESS(address, family, retval) \
1192 if (address->m_family == GSOCK_NOFAMILY) \
1193 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1194 return address->m_error; \
1195 if (address->m_family != GSOCK_##family) \
1197 address->m_error = GSOCK_INVADDR; \
1202 GAddress
*GAddress_new()
1206 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1209 address
->m_family
= GSOCK_NOFAMILY
;
1210 address
->m_host
= INADDR_NONE
;
1211 address
->m_port
= 0 ;
1216 GAddress
*GAddress_copy(GAddress
*address
)
1220 assert(address
!= NULL
);
1222 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1225 memcpy(addr2
, address
, sizeof(GAddress
));
1229 void GAddress_destroy(GAddress
*address
)
1231 assert(address
!= NULL
);
1236 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1238 assert(address
!= NULL
);
1240 address
->m_family
= type
;
1243 GAddressType
GAddress_GetFamily(GAddress
*address
)
1245 assert(address
!= NULL
);
1247 return address
->m_family
;
1250 GSocketError
_GAddress_translate_from(GAddress
*address
,
1253 switch (addr
->fAddressType
)
1256 address
->m_family
= GSOCK_INET
;
1260 address
->m_family
= GSOCK_INET6
;
1265 address
->m_error
= GSOCK_INVOP
;
1269 address
->m_host
= addr
->fHost
;
1270 address
->m_port
= addr
->fPort
;
1271 return GSOCK_NOERROR
;
1274 GSocketError
_GAddress_translate_to(GAddress
*address
,
1277 if ( GSocket_Verify_Inited() == FALSE
)
1278 return GSOCK_IOERR
;
1279 memset(addr
, 0 , sizeof(struct InetAddress
));
1280 OTInitInetAddress( addr
, address
->m_port
, address
->m_host
) ;
1281 return GSOCK_NOERROR
;
1285 * -------------------------------------------------------------------------
1286 * Internet address family
1287 * -------------------------------------------------------------------------
1290 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1292 address
->m_family
= GSOCK_INET
;
1293 address
->m_host
= kOTAnyInetAddress
;
1295 return GSOCK_NOERROR
;
1298 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1300 InetHostInfo hinfo
;
1303 if ( GSocket_Verify_Inited() == FALSE
)
1304 return GSOCK_IOERR
;
1306 assert(address
!= NULL
);
1308 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1309 ret
= OTInetStringToAddress( gInetSvcRef
, (char*) hostname
, &hinfo
) ;
1310 if ( ret
!= kOTNoError
)
1312 address
->m_host
= INADDR_NONE
;
1313 address
->m_error
= GSOCK_NOHOST
;
1314 return GSOCK_NOHOST
;
1316 address
->m_host
= hinfo
.addrs
[0] ;
1317 return GSOCK_NOERROR
;
1320 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1322 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1325 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1326 unsigned long hostaddr
)
1328 struct in_addr
*addr
;
1330 assert(address
!= NULL
);
1332 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1334 address
->m_host
= hostaddr
;
1336 return GSOCK_NOERROR
;
1339 struct service_entry
1342 unsigned short port
;
1345 typedef struct service_entry service_entry
;
1347 service_entry gServices
[] =
1349 { "http" , 80 , "tcp" }
1352 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1353 const char *protocol
)
1358 assert(address
!= NULL
);
1359 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1363 address
->m_error
= GSOCK_INVPORT
;
1364 return GSOCK_INVPORT
;
1366 for ( i
= 0 ; i
< sizeof( gServices
) / sizeof( service_entry
) ; ++i
)
1368 if ( strcmp( port
, gServices
[i
].name
) == 0 )
1370 if ( protocol
== NULL
|| strcmp( protocol
, gServices
[i
].protocol
) )
1372 address
->m_port
= gServices
[i
].port
;
1373 return GSOCK_NOERROR
;
1378 if (isdigit(port
[0]))
1380 address
->m_port
= atoi(port
);
1381 return GSOCK_NOERROR
;
1384 address
->m_error
= GSOCK_INVPORT
;
1385 return GSOCK_INVPORT
;
1388 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1392 assert(address
!= NULL
);
1393 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1394 address
->m_port
= port
;
1396 return GSOCK_NOERROR
;
1399 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1401 InetDomainName name
;
1402 if ( GSocket_Verify_Inited() == FALSE
)
1403 return GSOCK_IOERR
;
1405 assert(address
!= NULL
);
1406 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1408 OTInetAddressToName( gInetSvcRef
, address
->m_host
, name
) ;
1409 strncpy( hostname
, name
, sbuf
) ;
1410 return GSOCK_NOERROR
;
1413 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1415 assert(address
!= NULL
);
1416 CHECK_ADDRESS(address
, INET
, 0);
1418 return address
->m_host
;
1421 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1423 assert(address
!= NULL
);
1424 CHECK_ADDRESS(address
, INET
, 0);
1426 return address
->m_port
;
1429 void _GSocket_Enable_Events(GSocket
*socket
)
1431 if ( socket
->m_takesEvents
)
1436 socket
->m_takesEvents
= TRUE
;
1437 state
= OTGetEndpointState(socket
->m_endpoint
);
1440 OTByteCount sz
= 0 ;
1441 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1442 if ( state
== T_INCON
|| sz
> 0 )
1444 socket
->m_detected
|= GSOCK_INPUT_FLAG
;
1445 (socket
->m_cbacks
[GSOCK_INPUT
])(socket
, GSOCK_INPUT
, socket
->m_data
[GSOCK_INPUT
]);
1449 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1451 socket
->m_detected
|=GSOCK_OUTPUT_FLAG
;
1452 (socket
->m_cbacks
[GSOCK_OUTPUT
])(socket
, GSOCK_OUTPUT
, socket
->m_data
[GSOCK_OUTPUT
]);
1458 void _GSocket_Disable_Events(GSocket
*socket
)
1460 socket
->m_takesEvents
= FALSE
;
1463 /* _GSocket_Input_Timeout:
1464 * For blocking sockets, wait until data is available or
1465 * until timeout ellapses.
1467 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1469 if ( !socket
->m_non_blocking
)
1471 UnsignedWide now
, start
;
1472 short formerTakesEvents
= socket
->m_takesEvents
;
1473 Microseconds(&start
);
1475 socket
->m_takesEvents
= FALSE
;
1477 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1480 OTByteCount sz
= 0 ;
1481 state
= OTGetEndpointState(socket
->m_endpoint
);
1483 OTCountDataBytes( socket
->m_endpoint
, &sz
) ;
1484 if ( state
== T_INCON
|| sz
> 0 )
1486 socket
->m_takesEvents
= formerTakesEvents
;
1487 return GSOCK_NOERROR
;
1491 socket
->m_takesEvents
= formerTakesEvents
;
1492 socket
->m_error
= GSOCK_TIMEDOUT
;
1493 return GSOCK_TIMEDOUT
;
1495 return GSOCK_NOERROR
;
1498 /* _GSocket_Output_Timeout:
1499 * For blocking sockets, wait until data can be sent without
1500 * blocking or until timeout ellapses.
1502 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1504 if ( !socket
->m_non_blocking
)
1506 UnsignedWide now
, start
;
1507 short formerTakesEvents
= socket
->m_takesEvents
;
1508 Microseconds(&start
);
1510 socket
->m_takesEvents
= FALSE
;
1512 while( (now
.hi
* 4294967296.0 + now
.lo
) - (start
.hi
* 4294967296.0 + start
.lo
) < socket
->m_timeout
* 1000.0 )
1515 state
= OTGetEndpointState(socket
->m_endpoint
);
1517 if ( state
== T_DATAXFER
|| state
== T_INREL
)
1519 socket
->m_takesEvents
= formerTakesEvents
;
1520 return GSOCK_NOERROR
;
1524 socket
->m_takesEvents
= formerTakesEvents
;
1525 socket
->m_error
= GSOCK_TIMEDOUT
;
1526 return GSOCK_TIMEDOUT
;
1528 return GSOCK_NOERROR
;
1532 * There is data to be read in the input buffer. If, after a read
1533 * operation, there is still data available, the callback function will
1536 * The socket is available for writing. That is, the next write call
1537 * won't block. This event is generated only once, when the connection is
1538 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1539 * when the output buffer empties again. This means that the app should
1540 * assume that it can write since the first OUTPUT event, and no more
1541 * OUTPUT events will be generated unless an error occurs.
1543 * Connection succesfully established, for client sockets, or incoming
1544 * client connection, for server sockets. Wait for this event (also watch
1545 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1547 * The connection is lost (or a connection request failed); this could
1548 * be due to a failure, or due to the peer closing it gracefully.
1551 void _GSocket_Internal_Proc(unsigned long e
, void* d
)
1554 GSocket
* socket
= (GSocket
*) d
;
1555 OTEventCode ev
= (OTEventCode
) e
;
1557 GSocketEvent event2
;
1558 GSocketCallback cback
;
1560 GSocketCallback cback2
;
1565 event
= GSOCK_MAX_EVENT
;
1566 event2
= GSOCK_MAX_EVENT
;
1572 /* Check that the socket still exists (it has not been
1573 * destroyed) and for safety, check that the m_endpoint field
1574 * is what we expect it to be.
1576 if ((socket
!= NULL
) && (socket
->m_takesEvents
))
1581 event
= GSOCK_CONNECTION
;
1584 event
= GSOCK_CONNECTION
;
1585 event2
= GSOCK_OUTPUT
;
1589 retCall
.addr
.buf
= NULL
;
1590 retCall
.addr
.maxlen
= 0;
1591 retCall
.opt
.buf
= NULL
;
1592 retCall
.opt
.maxlen
= 0;
1593 retCall
.udata
.buf
= NULL
;
1594 retCall
.udata
.maxlen
= 0;
1595 OTRcvConnect( socket
->m_endpoint
, &retCall
) ;
1599 event
= GSOCK_LOST
;
1603 event
= GSOCK_OUTPUT
;
1606 event
= GSOCK_INPUT
;
1609 event
= GSOCK_INPUT
;
1612 if (event
!= GSOCK_MAX_EVENT
)
1614 cback
= socket
->m_cbacks
[event
];
1615 data
= socket
->m_data
[event
];
1617 if (event
== GSOCK_LOST
)
1618 socket
->m_detected
= GSOCK_LOST_FLAG
;
1620 socket
->m_detected
|= (1 << event
);
1622 if (event2
!= GSOCK_MAX_EVENT
)
1624 cback2
= socket
->m_cbacks
[event2
];
1625 data2
= socket
->m_data
[event2
];
1627 if (event2
== GSOCK_LOST
)
1628 socket
->m_detected
= GSOCK_LOST_FLAG
;
1630 socket
->m_detected
|= (1 << event2
);
1634 /* OK, we can now leave the critical section because we have
1635 * already obtained the callback address (we make no further
1636 * accesses to socket->whatever). However, the app should
1637 * be prepared to handle events from a socket that has just
1642 (cback
)(socket
, event
, data
);
1644 (cback2
)(socket
, event2
, data2
);
1648 /* Hack added for Mac OS X */
1649 GSocketError
GAddress_UNIX_GetPath(GAddress
*addr
, char *path
, size_t buf
)
1653 GSocketError
GAddress_UNIX_SetPath(GAddress
*addr
, const char *path
)
1657 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */